<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="contractType">
              <el-select
                v-model="queryParams.contractType"
                placeholder="请选择合同类型"
                clearable
                filterable
                style="width: 200px"
                @keyup.enter="handleQuery"
              >
                <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="contractName">
              <el-input v-model="queryParams.contractName" placeholder="请输入合同名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="状态" prop="contractStatus">
              <el-select
                v-model="queryParams.contractStatus"
                placeholder="请选择状态"
                clearable
                filterable
                style="width: 200px"
                @keyup.enter="handleQuery"
              >
                <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-row>
      </template>

      <el-table v-loading="loading" border :data="contractList">
        <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="contractAmount" />
        <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="projectLeader" width="180" />
        <el-table-column label="附件管理" align="center" prop="annex">
          <template>
            <span>下载</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="contractStatus" width="150">
          <template #default="scope">
            <dict-tag :options="contract_status" :value="scope.row.contractStatus" />
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleManage(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>
  </div>
</template>

<script setup name="CustomerContractInfo" lang="ts">
import {} from '@/api/customer/customerFile/customerInfo';
import { CustomerInfoQuery, CustomerInfoForm } from '@/api/customer/customerFile/customerInfo/types';
import { listContract } from '@/api/customer/customerFile/contract';
import { ContractVO, ContractQuery, ContractForm } from '@/api/customer/customerFile/contract/types';
import { listIndustryCategory } from '@/api/customer/customerCategory/industryCategory';
import { IndustryCategoryVO } from '@/api/customer/customerCategory/industryCategory/types';
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { contract_type, contract_status } = toRefs<any>(proxy?.useDict('contract_type', 'contract_status'));
const industryCategoryList = ref<IndustryCategoryVO[]>([]);
const contractList = ref<any[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);

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

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

const initFormData: CustomerInfoForm = {
  id: undefined,
  customerNo: undefined,
  belongCompanyId: undefined,
  companyName: undefined,
  customerName: undefined,
  businessCustomerName: undefined,
  shortName: undefined,
  invoiceTypeId: undefined,
  enterpriseScaleId: undefined,
  customerTypeId: undefined,
  industryCategoryId: undefined,
  customerLevelId: undefined,
  landline: undefined,
  fax: undefined,
  url: undefined,
  postCode: undefined,
  validityFromDate: undefined,
  validityToDate: undefined,
  invoiceTop: undefined,
  address: undefined,
  regProvincialNo: undefined,
  regCityNo: undefined,
  regCountyNo: undefined,
  provincialCityCounty: undefined,
  status: undefined,
  remark: undefined
};
const route = useRoute();

const data = reactive<any>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    customerId: undefined,
    customerNo: undefined,
    customerName: undefined,
    contractType: undefined,
    contractStatus: undefined,
    contractName: undefined,
    industryCategoryId: undefined,
    belongingDepartmentId: undefined
  }
}) as any;
const { queryParams, form, rules } = toRefs(data);

/** 查询维保记录列表 */
const getList = async () => {
  loading.value = true;
  const res = await listContract(queryParams.value);
  contractList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

//管理按钮
const handleManage = (row: any) => {
  router.push({
    path: '/customer/customer-file/customer-create-contract',
    query: {
      id: row.id
    }
  });
};

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

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

/** 加载行业分类列表 */
const loadIndustryCategories = async () => {
  try {
    const res = await listIndustryCategory(); // 只获取启用状态的行业
    industryCategoryList.value = res.rows;
  } catch (error) {
    console.error('加载行业分类失败:', error);
  }
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  // 重置时保留customerId
  const customerId = queryParams.value.customerId;
  queryParams.value.customerNo = undefined;
  queryParams.value.customerName = undefined;
  queryParams.value.industryCategoryId = undefined;
  queryParams.value.belongingDepartmentId = undefined;
  queryParams.value.customerId = customerId;
  handleQuery();
};

onMounted(() => {
  // 从路由获取customerId
  if (route.query.customerId) {
    queryParams.value.customerId = route.query.customerId as string | number;
  }
  getList();
  loadIndustryCategories();
});
</script>
