<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="合同编号" prop="contractNo">
              <el-input v-model="queryParams.contractNo" placeholder="请输入合同编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="合同名称" prop="contractName">
              <el-input v-model="queryParams.contractName" placeholder="请输入合同名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="合同类型" prop="contractType">
              <el-select v-model="queryParams.contractType" placeholder="请选择合同类型" clearable>
                <el-option v-for="dict in contract_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="合同状态" prop="approvalStatus">
              <el-select v-model="queryParams.approvalStatus" placeholder="请选择合同状态" clearable>
                <el-option v-for="dict in contract_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="20">
            <span>合同管理信息列表</span>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['customer:contract:add']">新增合同</el-button>
          </el-col>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="contractList" @selection-change="handleSelectionChange">
        <el-table-column label="合同编号" align="center" prop="contractNo" />
        <el-table-column label="合同名称" align="center" prop="contractName" />
        <el-table-column label="合同类型" align="center" prop="contractType">
          <template #default="scope">
            <dict-tag :options="contract_type" :value="scope.row.contractType" />
          </template>
        </el-table-column>
        <el-table-column label="起始时间" align="center" prop="startTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="截至时间" align="center" prop="endTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="上传时间" align="center" prop="uploadTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.uploadTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="approvalStatus">
          <template #default="scope">
            <dict-tag :options="contract_status" :value="scope.row.approvalStatus" />
          </template>
        </el-table-column>

        <el-table-column label="附件管理" align="center" prop="annex" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['customer:contract:edit']">编辑</el-button>
            <el-button link type="primary" icon="Edit" @click="handleReview(scope.row)" v-hasPermi="['customer:contract:edit']">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改客户合同对话框 -->
    <el-drawer :title="dialog.title" v-model="dialog.visible" size="70%" direction="rtl" :close-on-click-modal="true" append-to-body>
      <el-form ref="contractFormRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="合同编号" prop="contractNo">
              <el-input v-model="form.contractNo" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同名称" prop="contractName">
              <el-input v-model="form.contractName" placeholder="请输入合同名称" :disabled="isViewMode" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同类型" prop="contractType">
              <el-select v-model="form.contractType" placeholder="请选择合同类型" class="w-full" :disabled="isViewMode">
                <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-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="合同金额" prop="contractAmount">
              <el-input v-model="form.contractAmount" placeholder="请输入合同金额" :disabled="isViewMode" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户编号" prop="customerNo">
              <el-input v-model="form.customerNo" placeholder="请输入客户编号" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="form.customerName" placeholder="请输入客户名称" :disabled="isViewMode" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="客户负责人" prop="customerLeader">
              <el-input v-model="form.customerLeader" placeholder="请输入客户负责人" :disabled="isViewMode" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="我方负责人" prop="projectLeader">
              <el-input v-model="form.projectLeader" placeholder="请输入我方负责人" :disabled="isViewMode" />
            </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%"
                :disabled="isViewMode"
              />
            </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="isViewMode"
                :disabled-date="disabledEndDate"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item label="附件管理" prop="annex">
              <el-upload action="#" :auto-upload="false" :disabled="isViewMode">
                <el-button type="primary" :disabled="isViewMode">选择文件</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="!isViewMode" :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">{{ isViewMode ? '关 闭' : '取 消' }}</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="Contract" lang="ts">
import { listContract, getContract, delContract, addContract, updateContract } from '@/api/customer/customerFile/contract';
import { ContractVO, ContractQuery, ContractForm } from '@/api/customer/customerFile/contract/types';
// 接收父组件传递的props
const props = defineProps<{
  customerId?: string;
  customerNo?: string;
  customerName?: string;
}>();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { contract_type, contract_status } = toRefs<any>(proxy?.useDict('contract_type', 'contract_status'));

const contractList = ref<ContractVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const contractFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 是否为查看模式
const isViewMode = ref(false);

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: {
    customerNo: [{ required: true, message: '客户编号不能为空', trigger: 'blur' }],
    contractAmount: [{ required: true, message: '合同金额不能为空', trigger: 'blur' }],
    contractType: [{ required: true, message: '合同类型不能为空', trigger: 'change' }],
    startTime: [{ required: true, message: '合同开始时间不能为空', trigger: 'blur' }],
    endTime: [{ required: true, message: '合同结束时间不能为空', trigger: 'blur' }]
  }
});

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

/** 禁用截止日期：只能选择起始日期之后的日期 */
const disabledEndDate = (time: Date) => {
  if (!form.value.startTime) {
    return false; // 如果没有选择起始时间，不限制
  }
  // 将起始时间字符串转换为Date对象
  const startDate = new Date(form.value.startTime);
  // 截止日期必须大于起始日期
  return time.getTime() < startDate.getTime();
};

/** 查询客户合同列表 */
const getList = async () => {
  loading.value = true;
  // 使用props传递的customerId进行查询
  if (props.customerId) {
    queryParams.value.customerId = props.customerId;
  }
  const res = await listContract(queryParams.value);
  contractList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  contractFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ContractVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  isViewMode.value = false; // 取消查看模式
  // 将props中的客户信息赋值给form
  if (props.customerId) {
    form.value.customerId = props.customerId;
  }
  if (props.customerNo) {
    form.value.customerNo = props.customerNo;
  }
  if (props.customerName) {
    form.value.customerName = props.customerName;
  }
  dialog.visible = true;
  dialog.title = '添加客户合同';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ContractVO) => {
  reset();
  isViewMode.value = false; // 取消查看模式
  const _id = row?.id || ids.value[0];
  const res = await getContract(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改客户合同';
};
/** 查看按钮操作 */
const handleReview = async (row?: ContractVO) => {
  reset();
  isViewMode.value = true; // 设置为查看模式
  const _id = row?.id || ids.value[0];
  const res = await getContract(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '查看合同详情';
};

/** 提交按钮 */
const submitForm = () => {
  contractFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;

      if (form.value.id) {
        await updateContract(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addContract(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ContractVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除客户合同编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delContract(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'customer/contract/export',
    {
      ...queryParams.value
    },
    `contract_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  // 初始化时将customerId赋值给queryParams
  if (props.customerId) {
    queryParams.value.customerId = props.customerId;
  }
  getList();
});

// 监听props变化
watch(
  () => props.customerId,
  (newId) => {
    if (newId) {
      queryParams.value.customerId = newId;
      getList();
    }
  }
);
</script>
