<template>
  <div class="table-box">
    <div>
      <ProTable :config="config" ref="caseLRef" :api="getLoanpage" :paramCallback="paramCallback">
        <template #table_top>
          <div class="flex">
            <div class="mr-4"
              >未分派案件数：<span class="text-blue-500">{{ statisis.caseNum }}</span
              >件</div
            >
            <div class="mr-4"
              >未分派CPE数：<span class="text-blue-500">{{ statisis.cpeNum }}</span
              >件</div
            >
            <div class="mr-4"
              >未分派总金额数：<span class="text-blue-500">{{ statisis.amount }}</span
              >元</div
            >
          </div>
        </template>
        <!-- 表格 header 按钮 -->
        <template #left_buttons>
          <el-button type="primary" @click="allocation">分派 </el-button>
          <!-- <el-button
            type="primary"
            :disabled="!selectdList || selectdList.length < 1"
            @click="backCase"
            >撤回
          </el-button>
          <el-button type="primary" :disabled="!selectdList || selectdList.length < 1"
            >撤案
          </el-button> -->
        </template>
      </ProTable>
    </div>
    <allocationModal ref="allocationModalRef" @success="query" />
  </div>
</template>

<script setup name="case-allocation" lang="jsx">
  import allocationModal from './components/allocationModal.vue';
  import { getLoantotal, getLoanpage, backDistribute } from '@/api/allcation';
  import { reactive, ref } from 'vue';
  import { ElMessageBox, ElMessage } from 'element-plus';
  import citydata from '../../../assets/citydata';
  import { onMounted } from 'vue';
  import {VxeTextEllipsis, VxeTooltip} from 'vxe-pc-ui'
  import { getPlatformPage } from '@/api/platform';
  import { getManageOrgPage } from '@/api/manageOrg';
  import { getTenantPage } from '@/api/tenant';

  const allocationModalRef = ref();
  const caseLRef = ref();
  const selectdList = ref([]);
  const curParam = ref({});
  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 () => {
    await ElMessageBox.confirm('是否确认撤回选中案件?', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    });

    const ids = selectdList.value.map((v) => v.id).join(',');
    await backDistribute(ids);

    ElMessage({
      type: 'success',
      message: '撤回成功！',
      plain: true,
    });
    query();
  };
  const caseStatusOpt = [
    { label: '正常', value: 'normal' },
    { label: '撤案', value: 'withdraw' },
    { label: '留案', value: 'stay' },
  ];
  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 distributeStatusOpt = [
    { label: '未分派', value: 'undistributed' },
    { label: '分派到调解中心', value: 'tenant' },
    { label: '分派到CPE', value: 'CPE' },
  ];
  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: 160,
        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: distributeStatusOpt,
        search: { el: 'select', props: { filterable: true }, labelWidth: 78 },
        fieldNames: { label: 'label', value: 'value' },
        slots: {
          default: ({ row }) => {
            return (
              <>
                {row.distributeStatus
                  ? distributeStatusOpt.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',
        showOverflow: 'tooltip',
        title: '身份证',
        width: 140,
        search: { el: 'input', props: { clearable: true }, key: 'idCard', labelWidth: 78 },
      },
      {
        field: 'borrower.phone',
        
        showOverflow: 'tooltip',
        title: '手机',
        width: 100,
        search: { el: 'input', props: { clearable: true }, labelWidth: 78, key: 'borrowerPhone'},
      },
      {
        field: 'principalBalance',
        title: '剩余本金',
        showOverflow: 'tooltip',
        width: 80,
      },
      {
        field: 'remaininginterest',
        title: '剩余利息',
        showOverflow: 'tooltip',
        width: 80,
      },
      {
        field: 'commission',
        showOverflow: 'tooltip',
        title: '违约金',
        width: 80,
      },
      {
        field: 'caseStatus',
        title: '案件状态',
        showOverflow: 'tooltip',
        width: 80,
        enum: caseStatusOpt,
        // search: { el: 'select', props: { filterable: true }, labelWidth: 80 },
        fieldNames: { label: 'label', value: 'value' },
        slots: {
          default: ({ row }) => {
            return (
              <>
                {row.caseStatus ? caseStatusOpt.find((v) => v.value === row.caseStatus).label : ''}
              </>
            );
          },
        },
      }
    ],
    onCheckboxChange: onCheckboxChange,
    onCheckboxAll: onCheckboxAll
  });

  const allocation = (row) => {
    allocationModalRef.value.openModal(JSON.parse(JSON.stringify(curParam.value)), JSON.parse(JSON.stringify(selectdList.value)));
  };
  const query = () => caseLRef.value?.search();

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