<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="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="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="customerType" label-width="100px">
              <el-select v-model="queryParams.customerType" placeholder="请选择申请类型" clearable>
                <el-option
                  v-for="dict in special_customer_type"
                  :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">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="specialList" @selection-change="handleSelectionChange">
        <el-table-column v-if="false" label="" align="center" prop="specialId" />
        <el-table-column type="index" label="序号" width="50" align="center" />
        <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="applyDate" width="100">
          <template #default="scope">
            <span>{{ parseTime(scope.row.applyDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="姓名" align="center" prop="name" />
        <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="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="birthday" width="100">
          <template #default="scope">
            <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>

        <el-table-column label="申请类型" align="center" prop="customerType" width="150">
          <template #default="scope">
            <dict-tag :options="special_customer_type" :value="scope.row.customerType" />
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看相似客户" placement="top">
              <el-button v-hasPermi="['customer:special:query']" link icon="view" type="primary" @click="handleUpdate(scope.row)"
                >查看详情</el-button
              >
            </el-tooltip>

            <!--            <el-tooltip content="审核通过" placement="top">-->
            <!--              <el-button v-hasPermi="['customer:special:edit']" link icon="check" type="primary" @click="updateAuditPassed(scope.row)"-->
            <!--                >审核通过</el-button-->
            <!--              >-->
            <!--            </el-tooltip>-->
            <!--            <el-tooltip content="审核不通过" placement="top">-->
            <!--              <el-button v-hasPermi="['customer:special:edit']" link icon="close" type="primary" @click="updateAuditFail(scope.row)"-->
            <!--                >审核不通过</el-button-->
            <!--              >-->
            <!--            </el-tooltip>-->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
      <el-row style="margin-top: 20px">
        <el-button v-hasPermi="['customer:special:export']" type="warning" plain icon="Download" @click="handleExport">下 载</el-button>
      </el-row>
    </el-card>
    <!-- 添加或修改特殊客户对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="1200px" append-to-body>
      <el-table v-loading="loading" :data="similarList" @selection-change="handleSelectionChange">
        <!--        <el-table-column type="selection" width="40" align="center" />-->
        <el-table-column v-if="false" label="" align="center" prop="specialId" />
        <el-table-column label="姓名" align="center" prop="name" />
        <el-table-column label="证件类型" align="center" prop="idType">
          <template #default="scope">
            <dict-tag :options="sys_id_type" :value="scope.row.idType" />
          </template>
        </el-table-column>
        <el-table-column label="证件号码" align="center" prop="idNo" show-overflow-tooltip />
        <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="birthday">
          <template #default="scope">
            <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="Special" lang="ts">
import {
  listSpecial,
  getSpecial,
  delSpecial,
  addSpecial,
  updateSpecial,
  updateSpecialAuditPassed,
  updateSpecialAuditFail
} from '@/api/customer/special';
import { SpecialVO, SpecialQuery, SpecialForm, Customer } from '@/api/customer/special/types';
import { parseTime } from '../../../utils/ruoyi';
import { AuthenticityVerificationVO } from '@/api/customer/authenticityVerification/types';
import { getAuthenticityVerification } from '@/api/customer/authenticityVerification';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_from_system, sys_id_type, sys_user_sex, special_customer_type } = toRefs<any>(
  proxy?.useDict('sys_from_system', 'sys_id_type', 'sys_user_sex', 'special_customer_type')
);
const specialList = ref<SpecialVO[]>([]);
const similarList = ref<Customer[]>([]);
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 specialFormRef = ref<ElFormInstance>();
const dateRangeApply = ref<[DateModelType, DateModelType]>(['', '']);

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

const initFormData: SpecialForm = {
  specialId: undefined,
  name: undefined,
  gender: undefined,
  birthday: undefined,
  system: undefined,
  identificationType: undefined,
  identificationNumber: undefined,
  customerType: undefined,
  applyDate: undefined,
  status: undefined
};
const data = reactive<PageData<SpecialForm, SpecialQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    gender: undefined,
    birthday: undefined,
    system: undefined,
    identificationType: undefined,
    identificationNumber: undefined,
    customerType: undefined,
    applyDate: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    specialId: [{ required: true, message: '不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
    gender: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
    birthday: [{ required: true, message: '出生日期不能为空', trigger: 'blur' }],
    system: [{ required: true, message: '来源系统不能为空', trigger: 'blur' }],
    identificationType: [{ required: true, message: '证件类型不能为空', trigger: 'change' }],
    identificationNumber: [{ required: true, message: '证件号码不能为空', trigger: 'blur' }],
    customerType: [{ required: true, message: '客户类型不能为空', trigger: 'change' }],
    applyDate: [{ required: true, message: '申请时间不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '审核状态不能为空', trigger: 'change' }]
  }
});

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

/** 查询特殊客户列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value = proxy?.addDateRange(queryParams.value, dateRangeApply.value, 'Apply');
  const res = await listSpecial(queryParams.value);
  specialList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

/** 表单重置 */
const reset = () => {
  dateRangeApply.value = ['', ''];
  form.value = { ...initFormData };
  specialFormRef.value?.resetFields();
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  dateRangeApply.value = ['', ''];
  total.value = 0;
  specialList.value = '';
  //handleQuery();
};

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加特殊客户';
};

const updateAuditPassed = async (row?: SpecialVO) => {
  reset();
  const _specialId = row?.specialId || ids.value[0];
  await updateSpecialAuditPassed(_specialId);
  proxy?.$modal.msgSuccess('操作成功');
  await getList();
};

const updateAuditFail = async (row?: SpecialVO) => {
  reset();
  const _specialId = row?.specialId || ids.value[0];
  await updateSpecialAuditFail(_specialId);
  proxy?.$modal.msgSuccess('操作成功');
  await getList();
};

const handleUpdate = async (row?: SpecialVO) => {
  reset();
  const res = await getSpecial(row);
  similarList.value = res.data;
  // total.value = res.total;
  // Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '查看相似客户';
};

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

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

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'customer/special/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>
