<template>
  <div class="p-4">
    <!-- 页面标题和返回按钮 -->
    <div class="flex items-center gap-2 mb-4">
      <el-button icon="ArrowLeft" @click="handleBack">返回</el-button>
      <span class="text-lg font-medium">基本设置</span>
    </div>

    <el-card shadow="never" v-loading="loading">
      <el-form ref="contractFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="合同类型" prop="contractType">
              <el-select v-model="form.contractType" placeholder="请选择合同类型" class="w-full">
                <el-option v-for="dict in contract_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户编号" prop="customerNo">
              <el-input v-model="form.customerNo" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同编号" prop="contractNo">
              <el-input v-model="form.contractNo" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="合同名称" prop="contractName">
              <el-input v-model="form.contractName" placeholder="请输入合同名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="我方负责人" prop="projectLeader">
              <el-input v-model="form.projectLeader" placeholder="请输入我方负责人" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="起始时间" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择起始时间"
                class="w-full"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="截止时间" prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择截止时间"
                class="w-full"
                style="width: 100%"
                :disabled-date="disabledEndDate"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="上传时间" prop="uploadTime">
              <el-date-picker
                v-model="form.uploadTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择"
                class="w-full"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同金额" prop="contractAmount">
              <el-input v-model="form.contractAmount" placeholder="请输入合同金额" style="width: 95%" />万元
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="附件管理" prop="annex">
              <el-upload></el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 保存按钮 -->
        <el-row :gutter="20">
          <el-col :span="24" class="text-left">
            <el-button :loading="buttonLoading" type="primary" @click="submitForm">提交</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>
<script setup name="CustomerCreateContract" lang="ts">
import { listContract, getContract, delContract, addContract, updateContract } from '@/api/customer/customerFile/contract';
import { ContractVO, ContractQuery, ContractForm } from '@/api/customer/customerFile/contract/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { contract_type } = toRefs<any>(proxy?.useDict('contract_type'));
const route = useRoute();
const router = useRouter();

const contractFormRef = ref<ElFormInstance>();
const buttonLoading = ref(false);
const loading = ref(false);
const contractId = ref<string | number>('');

const initFormData: ContractForm = {
  id: undefined,
  customerNo: undefined,
  customerId: undefined,
  customerName: undefined,
  contractNo: undefined,
  contractName: undefined,
  contractAmount: undefined,
  customerLeader: undefined,
  projectLeader: undefined,
  contractType: undefined,
  startTime: undefined,
  endTime: undefined,
  uploadTime: undefined,
  settlementType: undefined,
  contractStatus: undefined,
  approvalStatus: undefined,
  annex: undefined,
  remark: undefined
};
const data = reactive<PageData<ContractForm, ContractQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    customerNo: undefined,
    customerId: undefined,
    contractNo: undefined,
    contractName: undefined,
    contractAmount: undefined,
    customerLeader: undefined,
    projectLeader: undefined,
    contractType: undefined,
    startTime: undefined,
    endTime: undefined,
    uploadTime: undefined,
    settlementType: undefined,
    contractStatus: undefined,
    approvalStatus: undefined,
    annex: undefined,
    platformCode: undefined,
    params: {}
  },
  rules: {
    contractName: [{ required: true, message: '合同名称不能为空', trigger: 'blur' }],
    contractType: [{ required: true, message: '合同类型不能为空', trigger: 'change' }],
    contractAmount: [{ required: true, message: '合同金额不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 禁用截止日期：只能选择起始日期之后的日期 */
const disabledEndDate = (time: Date) => {
  if (!form.value.startTime) {
    return false;
  }
  const startDate = new Date(form.value.startTime);
  return time.getTime() < startDate.getTime();
};

/** 返回按钮 */
const handleBack = () => {
  router.back();
};

/** 加载合同数据 */
const loadContractData = async () => {
  if (!contractId.value) return;

  try {
    loading.value = true;
    const res = await getContract(contractId.value);
    if (res.data) {
      Object.assign(form.value, res.data);
    }
  } catch (error) {
    console.error('加载合同数据失败:', error);
    proxy?.$modal.msgError('加载合同数据失败');
  } finally {
    loading.value = false;
  }
};

/** 提交表单 */
const submitForm = () => {
  contractFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        if (form.value.id) {
          await updateContract(form.value);
          proxy?.$modal.msgSuccess('保存成功');
        } else {
          await addContract(form.value);
          proxy?.$modal.msgSuccess('创建成功');
        }
        // 保存成功后返回
        router.back();
      } catch (error) {
        console.error('保存失败:', error);
        proxy?.$modal.msgError('保存失败，请重试');
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

onMounted(() => {
  // 从路由获取合同ID（编辑模式）
  if (route.query.id) {
    contractId.value = route.query.id as string | number;
    loadContractData();
  }
  // 从路由获取客户信息（新增模式）
  if (route.query.customerNo) {
    form.value.customerNo = route.query.customerNo as string;
  }
  if (route.query.customerId) {
    form.value.customerId = route.query.customerId as string | number;
  }
  if (route.query.customerName) {
    form.value.customerName = route.query.customerName as string;
  }
});
</script>
