<template>
  <div class="table-box">
    <div>
      <ProTable :config="config" ref="caseLRef" :api="getLoanpage" :paramCallback="paramCallback">
        <!-- 表格 header 按钮 -->
        <template #left_buttons>
          <el-button type="primary" @click="backCase">回收 </el-button>
        </template>
      </ProTable>
    </div>
    <vxe-modal
      resize
      v-model="showModal"
      title="提示"
      height="242"
      width="450"
      show-footer
      esc-closable
    >
      <div class="w-full px-3 h-full overflow-auto flex-col flex mytable">
        ⚠️回收处理后可重新分派<br />
        回收：只回收未留案的案件<br />
        强制回收：所有案件都会回收，留案案件会被强制回收<br />
      </div>
      <template #footer>
        <el-button type="default" @click="showModal = false">取消</el-button>
        <el-button type="primary" @click="submitForm('withdraw')">回收</el-button>
        <el-button type="danger" @click="submitForm('fullWithdraw')">强制回收</el-button>
      </template>
    </vxe-modal>
  </div>
</template>

<script setup name="case-allocation" lang="jsx">
  import { getLoantotal, getLoanpage, back, fullBack } from '@/api/allcation';
  import { reactive, ref } from 'vue';
  import { ElMessageBox, ElMessage } from 'element-plus';
  import { VxeTextEllipsis, VxeTooltip } from 'vxe-pc-ui';
  import citydata from '../../../assets/citydata';
  import { onMounted } from 'vue';
  import { getPlatformPage } from '@/api/platform';
  import { getManageOrgPage } from '@/api/manageOrg';
  import { getTenantPage } from '@/api/tenant';
  import { useDict } from '@/hooks/useDict';
  const { PhoneResultStatus, ReduceType, FlowStatus, FollowStatus, DistributeStatus, CaseStatus } = useDict("PhoneResultStatus","ReduceType", "FlowStatus", "FollowStatus","DistributeStatus", "CaseStatus");
  const caseLRef = ref();
  const selectdList = ref([]);
  const curParam = ref({});
  const showModal = ref(false);
  const onCheckboxChange = (row) => {
    selectdList.value = row.records;
  };
  const statisis = ref({});
  const getStatisis = (params) => {
    getLoantotal(params).then((res) => {
      if (res.success) {
        statisis.value = res.result;
      }
    });
  };
  const backCase = async () => {
    // 勾选的情况
    // if (selectdList.value && selectdList.value.length) {
    //   const arr = selectdList.value.filter(v => v.caseStatus === 'stay')
    //   if (arr.length > 0) {
    //     showModal.value = true
    //   } else {
    //     submitForm('withdraw')
    //   }
    // } else {
    //   const param = {...curParam.value, caseStatus: 'stay'}
    //   getLoanpage(param).then(res=>{
    //     if(res.success && res.result && res.result.content && res.result.content.length) {
    //       showModal.value = true
    //     } else {
    //       submitForm('withdraw')
    //     }
    //   })
    // }
    showModal.value = true;
  };
  const submitForm = async (type) => {
    const ids = selectdList.value.map((v) => v.id).join(',');
    let param = {};
    if (ids.length > 0) {
      param['loanIds'] = ids;
    } else {
      param = { ...curParam.value };
    }
    if (type === 'withdraw') {
      await back(param);
      ElMessage({
        type: 'success',
        message: '回收成功！',
        plain: true,
      });
    } else {
      await fullBack(param);
      ElMessage({
        type: 'success',
        message: '强制回收成功！',
        plain: true,
      });
    }
    query();
    showModal.value = false;
  };
  const paramCallback = (param) => {
    const obj = JSON.parse(JSON.stringify(param));
    if (obj.arealist && obj.arealist.length > 0) {
      obj['domicileProvince'] = obj.arealist[0];
      obj['domicileCity'] = obj.arealist.length > 1 ? obj.arealist[1] : null;
      obj['area'] = obj.arealist.length > 2 ? obj.arealist[2] : null;
      delete obj['arealist'];
    }
    if (obj['cpeDate']) {
      if (obj['cpeDate'][0]) obj['cpeDateBegin'] = obj['cpeDate'][0];
      if (obj['cpeDate'][1]) obj['cpeDateEnd'] = obj['cpeDate'][1];
      delete obj['cpeDate'];
    }
    if (obj['tenantTime']) {
      if (obj['tenantTime'][0]) obj['tenantTimeBegin'] = obj['tenantTime'][0];
      if (obj['tenantTime'][1]) obj['tenantTimeEnd'] = obj['tenantTime'][1];
      delete obj['tenantTime'];
    }
    curParam.value = obj;
    // getStatisis(obj);
    return obj;
  };
  const onCheckboxAll = (flag) => {
    if (flag.checked) {
      selectdList.value = flag.records;
    } else {
      selectdList.value = [];
    }
  };

  console.log('citydatacitydata', citydata);
  const config = reactive({
    columns: [
      { type: 'checkbox', title: '', width: 40 },
      {
        field: 'caseId',
        title: '案件ID',
        showOverflow: 'tooltip',
        search: { el: 'input', labelWidth: 78 },
        width: 100,
      },
      {
        field: 'arealist',
        enum: citydata,
        title: '所属区域',
        showOverflow: 'tooltip',
        width: 100,
        fieldNames: { label: 'label', value: 'value' },
        search: { el: 'cascader', props: { clearable: true, checkStrictly: true }, labelWidth: 78 },
        slots: {
          default: ({ row }) => {
            return (
              <VxeTooltip
                content={
                  row.borrower.domicileProvince +
                  (row.borrower.domicileCity ? '-' + row.borrower.domicileCity : '') +
                  (row.borrower.area ? '-' + row.borrower.area : '')
                }
              >
                <VxeTextEllipsis
                  content={
                    row.borrower.domicileProvince +
                    (row.borrower.domicileCity ? '-' + row.borrower.domicileCity : '') +
                    (row.borrower.area ? '-' + row.borrower.area : '')
                  }
                ></VxeTextEllipsis>
              </VxeTooltip>
            );
          },
        },
      },
      {
        field: 'loanPlatform.name',
        showOverflow: 'tooltip',
        enum: () => getPlatformPage({ current: 1, size: 999999999, status: 'enable' }),
        search: {
          el: 'select',
          props: { filterable: true },
          key: 'loanPlatformId',
          labelWidth: 78,
        },
        fieldNames: { label: 'name', value: 'id' },
        title: '借款机构',
        width: 100,
      },
      {
        field: 'manageOrg.orgName',
        title: '资管公司',
        enum: () => getManageOrgPage({ current: 1, size: 999999999, status: 'enable' }),
        fieldNames: { label: 'orgName', value: 'id' },
        showOverflow: 'tooltip',
        width: 100,
        search: { el: 'select', props: { clearable: true }, key: 'manageOrgId', labelWidth: 78 },
      },
      {
        field: 'batchCode',
        title: '导入批次',
        showOverflow: 'tooltip',
        width: 100,
        search: { el: 'input', props: { clearable: true }, key: 'batchCode', labelWidth: 78 },
      },
      {
        field: 'distributeStatus',
        title: '分派状态',
        showOverflow: 'tooltip',
        width: 80,
        enum: DistributeStatus,
        search: { el: 'select', props: { filterable: true }, labelWidth: 78 },
        fieldNames: { label: 'label', value: 'value' },
        slots: {
          default: ({ row }) => {
            return (
              <>
                {row.distributeStatus
                  ? DistributeStatus.value?.find((v) => v.value === row.distributeStatus)?.label
                  : ''}
              </>
            );
          },
        },
      },
      {
        field: 'tenant.name',
        showOverflow: 'tooltip',
        enum: () => getTenantPage({ current: 1, size: 999999999, status: 'enable' }),
        search: { el: 'select', props: { filterable: true }, key: 'tenantId', labelWidth: 78 },
        fieldNames: { label: 'name', value: 'id' },
        title: '调解中心',
        width: 100,
      },
      {
        field: 'discount',
        title: '折扣',
        showOverflow: 'tooltip',
        width: 80,
      },
      {
        field: 'cpe.username',
        title: 'CPE',
        showOverflow: 'tooltip',
        width: 60,
        search: { el: 'input', props: { clearable: true }, key: 'cpeName', labelWidth: 78 },
      },
      {
        field: 'tenantTime',
        title: '分派中心日期',
        showOverflow: 'tooltip',
        width: 130,
        search: {
          el: 'date-picker',
          props: { type: 'daterange', valueFormat: 'YYYY-MM-DD' },
          labelWidth: 78,
        },
      },
      {
        field: 'commissionAmount',
        title: '债权总额',
        showOverflow: 'tooltip',
        width: 80,
        search: { el: 'input', props: { clearable: true }, labelWidth: 78 },
      },
      {
        field: 'cpeDate',
        title: '分派CPE日期',
        showOverflow: 'tooltip',
        width: 130,
        search: {
          el: 'date-picker',
          props: { type: 'daterange', valueFormat: 'YYYY-MM-DD' },
          labelWidth: 78,
        },
      },
      {
        field: 'borrower.name',
        title: '借款人姓名',
        showOverflow: 'tooltip',
        width: 100,
        search: { el: 'input', key: 'borrowerName', props: { clearable: true }, labelWidth: 78 },
      },
      {
        field: 'sumRepayAmount',
        title: '已还总额',
        showOverflow: 'tooltip',
        width: 80,
        // search: { el: 'input', props: { clearable: true }, labelWidth: 78 },
      },
      {
        field: 'borrower.idCard',
        title: '身份证',
        showOverflow: 'tooltip',
        width: 140,
        search: { el: 'input', props: { clearable: true }, key: 'idCard', labelWidth: 78 },
      },
      {
        field: 'borrower.phone',
        showOverflow: 'tooltip',
        title: '手机',
        width: 100,
        search: { el: 'input', key: 'borrowerPhone', props: { clearable: true }, labelWidth: 78 },
      },
      {
        field: 'principalBalance',
        title: '剩余本金',
        showOverflow: 'tooltip',
        width: 80,
      },
      {
        field: 'remaininginterest',
        title: '剩余利息',
        showOverflow: 'tooltip',
        width: 80,
      },
      {
        field: 'commission',
        title: '违约金',
        showOverflow: 'tooltip',
        width: 80,
      },
      {
        field: 'caseStatus',
        title: '案件状态',
        showOverflow: 'tooltip',
        width: 80,
        enum: CaseStatus,
        // search: { el: 'select', props: { filterable: true }, labelWidth: 80 },
        fieldNames: { label: 'label', value: 'value' },
        slots: {
          default: ({ row }) => {
            return (
              <>
                {row.caseStatus ? CaseStatus.value?.find((v) => v.value === row.caseStatus)?.label : ''}
              </>
            );
          },
        },
      },
      {
        field: 'credit?.borrowingTime',
        title: '借款时间',
        showOverflow: 'tooltip',
        width: 80
      },
      {
        field: 'credit?.litigationStatus',
        title: '诉讼执行状态',
        showOverflow: 'tooltip',
        width: 80
      },
      {
        field: 'credit?.litigationCaseNo',
        title: '诉讼案号',
        showOverflow: 'tooltip',
        width: 80
      },
      {
        field: 'credit?.executeCaseNo',
        title: '执行案号',
        showOverflow: 'tooltip',
        width: 80
      },
      {
        field: 'credit?.closingStatus',
        title: '结案状态',
        showOverflow: 'tooltip',
        width: 80
      },
      {
        field: 'credit?.constantNo',
        title: '合同编号',
        showOverflow: 'tooltip',
        width: 80
      },
      {
        field: 'credit?.planAmountOrg',
        title: '资金方名称',
        showOverflow: 'tooltip',
        width: 80
      },
      {
        field: 'credit?.planAmount',
        title: '申请金额',
        showOverflow: 'tooltip',
        width: 80
      },
      {
        field: 'credit?.paymentDate',
        title: '借款日期',
        showOverflow: 'tooltip',
        width: 80
      },
      {
        field: 'credit?.overDate',
        title: '到期日期',
        showOverflow: 'tooltip',
        width: 80
      },
      {
        field: 'credit?.period',
        title: '期数',
        showOverflow: 'tooltip',
        width: 80
      },
      {
        field: 'credit?.lastPaymentDate',
        title: '最后还款日期',
        showOverflow: 'tooltip',
        width: 80
      },
      {
        field: 'credit?.yearRate',
        title: '年化利率',
        showOverflow: 'tooltip',
        width: 80
      },
      {
        field: 'credit?.paymentAmount',
        title: '订单总应还金额',
        showOverflow: 'tooltip',
        width: 80
      },
      {
        field: 'credit?.interest',
        title: '订单总应还利息',
        showOverflow: 'tooltip',
        width: 80
      },
      {
        field: 'credit?.free',
        title: '订单总应还其他费用',
        showOverflow: 'tooltip',
        width: 80
      },
      {
        field: 'credit?.overdue',
        title: '逾期日期',
        showOverflow: 'tooltip',
        width: 80
      },
      {
        field: 'credit?.overdueDays',
        title: '逾期天数',
        showOverflow: 'tooltip',
        width: 80
      },
      {
        field: 'credit?.overduePeriod',
        title: '逾期期数',
        showOverflow: 'tooltip',
        width: 80
      },
      {
        field: 'credit?.overBalance',
        title: '已还本金',
        showOverflow: 'tooltip',
        width: 80
      },
      {
        field: 'credit?.overInterest',
        title: '已还利息',
        showOverflow: 'tooltip',
        width: 80
      },
      {
        field: 'credit?.overFree',
        title: '已还其他费用',
        showOverflow: 'tooltip',
        width: 80
      },
      {
        field: 'credit?.remark',
        title: '备注',
        showOverflow: 'tooltip',
        width: 80
      },
      {
        field: 'credit?.disbursement',
        title: '垫付费用',
        showOverflow: 'tooltip',
        width: 80
      },
    ],
    onCheckboxChange: onCheckboxChange,
    onCheckboxAll: onCheckboxAll,
  });

  const query = () => caseLRef.value?.search();

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