<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="customerNo" label-width="100px">
              <el-input v-model="queryParams.customerNo" placeholder="请输入客户号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="子客户号" prop="subCustomerNo" label-width="100px">
              <el-input v-model="queryParams.subCustomerNo" placeholder="请输入子客户号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!--            <el-form-item label="业务号码" prop="businessNo">-->
            <!--              <el-input v-model="queryParams.businessNo" placeholder="请输入业务号码" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <el-form-item label="客户姓名" prop="name" label-width="100px">
              <el-input v-model="queryParams.name" placeholder="请输入客户姓名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="证件类型" prop="identificationType" label-width="100px">
              <el-select v-model="queryParams.identificationType" placeholder="请选择证件类型" clearable>
                <el-option
                  v-for="dict in sys_id_type.filter((item) => item.value !== 'd' && item.value !== 'f')"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="证件号码" prop="identificationNumber" label-width="100px">
              <el-input v-model="queryParams.identificationNumber" placeholder="请输入证件号码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="验真时间" label-width="100px">
              <el-date-picker
                v-model="dateRangeApply"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 240px"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="服务商" prop="serviceProvider" label-width="100px">
              <el-select v-model="queryParams.serviceProvider" placeholder="请选择服务商" clearable>
                <el-option v-for="dict in verification_isp" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="请求系统" prop="system" label-width="100px">
              <el-select v-model="queryParams.system" placeholder="请选择请求系统" clearable>
                <el-option
                  v-for="dict in sys_from_system.filter((item) => item.value !== 'CMS' && item.value !== 'Shared')"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="验真结果" prop="system" label-width="100px">
              <el-select v-model="queryParams.verificationResult" placeholder="请选择验真结果" clearable>
                <el-option v-for="dict in verification_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-row>
              <el-form-item>
                <el-button type="primary" icon="Search" style="margin-left: 40px" @click="handleQuery">查询</el-button>
                <el-button icon="Refresh" style="margin-left: 50px" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-row>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">

      <el-table v-loading="loading" :data="authenticityVerificationList" @selection-change="handleSelectionChange">
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column v-if="false" label="验真记录ID" align="center" prop="verificationId" />
        <el-table-column label="验真时间" align="center" prop="verificationTime" width="200">
          <template #default="scope">
            <span>{{ parseTime(scope.row.verificationTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="请求系统" align="center" prop="system">
          <template #default="scope">
            <dict-tag :options="sys_from_system" :value="scope.row.system" />
          </template>
        </el-table-column>
        <!--        <el-table-column label="业务号码" align="center" prop="businessNo" />-->
        <el-table-column label="客户号" align="center" prop="customerNo" width="200" />
        <el-table-column label="客户姓名" align="center" prop="name" show-overflow-tooltip />
        <el-table-column label="证件类型" align="center" prop="identificationType">
          <template #default="scope">
            <dict-tag :options="sys_id_type" :value="scope.row.identificationType" />
          </template>
        </el-table-column>
        <el-table-column label="证件号码" align="center" prop="identificationNumber" width="200" />

        <el-table-column label="出生日期" align="center" prop="birthday" width="200">
          <template #default="scope">
            <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>

        <el-table-column label="性别" align="center" prop="gender">
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.gender" />
          </template>
        </el-table-column>
        <el-table-column label="服务商" align="center" prop="serviceProvider" width="200">
          <template #default="scope">
            <dict-tag :options="verification_isp" :value="scope.row.serviceProvider" />
          </template>
        </el-table-column>
        <el-table-column label="验真结果" align="center" prop="verificationResult">
          <template #default="scope">
            <dict-tag :options="verification_status" :value="scope.row.verificationResult" />
          </template>
        </el-table-column>
        <el-table-column label="验证结果说明" align="center" prop="verificationDetails" width="180" />
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
      <el-button v-hasPermi="['customer:authenticityVerification:export']" type="warning" plain icon="Download" @click="handleExport">下载</el-button>
    </el-card>
    <!-- 添加或修改客户真实性验真记录对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="authenticityVerificationFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户号" prop="customerNo">
          <el-input v-model="form.customerNo" placeholder="请输入客户号" />
        </el-form-item>
        <el-form-item label="子客户号" prop="subCustomerNo">
          <el-input v-model="form.subCustomerNo" placeholder="请输入子客户号" />
        </el-form-item>
        <!--        <el-form-item label="业务号码" prop="businessNo">-->
        <!--          <el-input v-model="form.businessNo" placeholder="请输入业务号码" />-->
        <!--        </el-form-item>-->
        <el-form-item label="客户姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入客户姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-input v-model="form.gender" placeholder="请输入性别" />
        </el-form-item>
        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker v-model="form.birthday" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择出生日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="证件类型" prop="identificationType">
          <el-select v-model="form.identificationType" placeholder="请选择证件类型">
            <el-option v-for="dict in sys_id_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="证件号码" prop="identificationNumber">
          <el-input v-model="form.identificationNumber" placeholder="请输入证件号码" />
        </el-form-item>
        <el-form-item label="验真方式" prop="verificationMethod">
          <el-input v-model="form.verificationMethod" placeholder="请输入验真方式" />
        </el-form-item>
        <el-form-item label="验真结果" prop="verificationResult">
          <el-input v-model="form.verificationResult" placeholder="请输入验真结果" />
        </el-form-item>
        <el-form-item label="验真详情" prop="verificationDetails">
          <el-input v-model="form.verificationDetails" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="验真时间" prop="verificationTime">
          <el-date-picker v-model="form.verificationTime" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择验真时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="验真操作员" prop="verifiedBy">
          <el-input v-model="form.verifiedBy" placeholder="请输入验真操作员" />
        </el-form-item>
        <el-form-item label="服务商" prop="serviceProvider">
          <el-select v-model="form.serviceProvider" placeholder="请选择服务商" clearable>
            <el-option v-for="dict in verification_isp" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="请求系统" prop="system">
          <el-select v-model="form.system" placeholder="请选择请求系统">
            <el-option
              v-for="dict in sys_from_system.filter((item) => item.value !== 'CMS' && item.value !== 'Shared')"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AuthenticityVerification" lang="ts">
import {
  listAuthenticityVerification,
  getAuthenticityVerification,
  delAuthenticityVerification,
  addAuthenticityVerification,
  updateAuthenticityVerification
} from '@/api/customer/authenticityVerification';
import {
  AuthenticityVerificationVO,
  AuthenticityVerificationQuery,
  AuthenticityVerificationForm
} from '@/api/customer/authenticityVerification/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_id_type, sys_from_system, sys_user_sex, verification_status, verification_isp } = toRefs<any>(
  proxy?.useDict('sys_id_type', 'sys_from_system', 'sys_user_sex', 'verification_status', 'verification_isp')
);

const authenticityVerificationList = ref<AuthenticityVerificationVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(false);
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 authenticityVerificationFormRef = ref<ElFormInstance>();
const dateRangeApply = ref<[DateModelType, DateModelType]>(['', '']);


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

const initFormData: AuthenticityVerificationForm = {
  verificationId: undefined,
  customerNo: undefined,
  subCustomerNo: undefined,
  businessNo: undefined,
  name: undefined,
  gender: undefined,
  birthday: undefined,
  identificationType: undefined,
  identificationNumber: undefined,
  verificationMethod: undefined,
  verificationResult: undefined,
  verificationDetails: undefined,
  verificationTime: undefined,
  verifiedBy: undefined,
  serviceProvider: undefined,
  system: undefined,
  remarks: undefined
};
const data = reactive<PageData<AuthenticityVerificationForm, AuthenticityVerificationQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    customerNo: undefined,
    subCustomerNo: undefined,
    businessNo: undefined,
    name: undefined,
    gender: undefined,
    birthday: undefined,
    identificationType: undefined,
    identificationNumber: undefined,
    verificationMethod: undefined,
    verificationResult: undefined,
    verificationDetails: undefined,
    verificationTime: undefined,
    verifiedBy: undefined,
    serviceProvider: undefined,
    system: undefined,
    remarks: undefined,
    params: {}
  },
  rules: {
    verificationId: [{ required: true, message: '验真记录ID不能为空', trigger: 'blur' }],
    customerNo: [{ required: true, message: '客户号不能为空', trigger: 'blur' }],
    subCustomerNo: [{ required: true, message: '子客户号不能为空', trigger: 'blur' }],
    businessNo: [{ required: true, message: '业务号码不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '客户姓名不能为空', trigger: 'blur' }],
    gender: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
    birthday: [{ required: true, message: '出生日期不能为空', trigger: 'blur' }],
    identificationType: [{ required: true, message: '证件类型不能为空', trigger: 'change' }],
    identificationNumber: [{ required: true, message: '证件号码不能为空', trigger: 'blur' }],
    verificationMethod: [{ required: true, message: '验真方式不能为空', trigger: 'blur' }],
    verificationResult: [{ required: true, message: '验真结果不能为空', trigger: 'blur' }],
    verificationDetails: [{ required: true, message: '验真详情不能为空', trigger: 'blur' }],
    verificationTime: [{ required: true, message: '验真时间不能为空', trigger: 'blur' }],
    verifiedBy: [{ required: true, message: '验真操作员不能为空', trigger: 'blur' }],
    serviceProvider: [{ required: true, message: '服务商不能为空', trigger: 'blur' }],
    system: [{ required: true, message: '请求系统不能为空', trigger: 'change' }],
    remarks: [{ required: true, message: '备注不能为空', trigger: 'blur' }]
  }
});

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

/** 查询客户真实性验真记录列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value = proxy?.addDateRange(queryParams.value, dateRangeApply.value, 'verificationDate');
  const res = await listAuthenticityVerification(queryParams.value);
  authenticityVerificationList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    customerNo: undefined,
    subCustomerNo: undefined,
    businessNo: undefined,
    name: undefined,
    gender: undefined,
    birthday: undefined,
    identificationType: undefined,
    identificationNumber: undefined,
    verificationMethod: undefined,
    verificationResult: undefined,
    verificationDetails: undefined,
    verificationTime: undefined,
    verifiedBy: undefined,
    serviceProvider: undefined,
    system: undefined,
    remarks: undefined,
    params: {}
  };
  dateRangeApply.value = ['', ''];
  authenticityVerificationList.value = '';
  total.value = 0;
};

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加客户真实性验真记录';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: AuthenticityVerificationVO) => {
  reset();
  const _verificationId = row?.verificationId || ids.value[0];
  const res = await getAuthenticityVerification(_verificationId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改客户真实性验真记录';
};

/** 提交按钮 */
const submitForm = () => {
  authenticityVerificationFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.verificationId) {
        await updateAuthenticityVerification(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addAuthenticityVerification(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: AuthenticityVerificationVO) => {
  const _verificationIds = row?.verificationId || ids.value;
  await proxy?.$modal.confirm('是否确认删除客户真实性验真记录编号为"' + _verificationIds + '"的数据项？').finally(() => (loading.value = false));
  await delAuthenticityVerification(_verificationIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};
// 检查是否至少有一个查询条件被填写
const hasQueryCondition = () => {
  // 检查 queryParams 中的字段（排除分页参数和空值）
  const hasQueryParams = Object.keys(queryParams.value).some(
    (key) => key !== 'pageNum' && key !== 'pageSize' && key !== 'params' && queryParams.value[key] !== undefined && queryParams.value[key] !== ''
  );

  // 检查 dateRangeApply 是否有效（非空数组且两个日期都有值）
  const hasDateRange = dateRangeApply.value && dateRangeApply.value.length === 2 && dateRangeApply.value.every((date) => date);

  // 只要 queryParams 或 dateRangeApply 有值，就返回 true
  return hasQueryParams || hasDateRange;
};

/** 导出按钮操作 */
const handleExport = () => {
  if (!hasQueryCondition) {
    proxy?.$modal.alert('请至少录入一项查询条件');
    return;
  }
  proxy?.download(
    'customer/authenticityVerification/export',
    {
      ...queryParams.value
    },
    `客户有验真清单_${new Date().toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      fractionalSecondDigits: 3,
      hour12: false
    })}.xlsx`
  );
};

// onMounted(() => {
//   getList();
// });
</script>
