<template>
  <div class="table-box">
    <div>
      <ProTable :config="config" ref="caseLRef" :api="getLoanpage" :paramCallback="paramCallback">
        <template #table_top>
          <div class="flex">
            <div class="mr-2"
              >未分配案件数：<span class="text-blue-500 mr-1">{{ statisis.caseNum }}</span
              >件</div
            >
            <div class="mr-2"
              >未分配CPE数：<span class="text-blue-500 mr-1">{{ statisis.cpeNum }}</span
              >件</div
            >
            <div class="mr-2"
              >未分配总金额数：<span class="text-blue-500 mr-1">{{ statisis.amount }}</span
              >元</div
            >
          </div>
        </template>
        <!-- 表格 header 按钮 -->
        <template #left_buttons>
          <el-button
            type="primary"
            :disabled="!selectdList || selectdList.length !== 1"
            @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';
  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 paramCallback = (param) => {
    const obj = JSON.parse(JSON.stringify(param));
    if (obj.arealist && obj.arealist.length > 0) {
      obj['province'] = obj.arealist[0];
      obj['city'] = obj.arealist.length > 1 ? obj.arealist[1] : null;
      obj['district'] = obj.arealist.length > 2 ? obj.arealist[2] : null;
      delete obj['arealist'];
    }
    curParam.value = obj;
    getStatisis(obj);
    return obj;
  };
  const distributeStatusOpt = [
    { label: '未分配', value: 'undistributed' },
    { label: '分配到调解中心', value: 'tenant' },
    { label: '分配到CPE', value: 'CPE' },
  ];
  console.log('citydatacitydata', citydata);
  const config = reactive({
    columns: [
      { type: 'checkbox', title: '', width: '40px' },
      { field: 'caseId', title: '案件ID/案件号', search: { el: 'input' } },
      {
        field: 'arealist',
        enum: citydata,
        title: '所属区域',
        fieldNames: { label: 'label', value: 'value' },
        search: { el: 'cascader', props: { clearable: true } },
        slots: {
          default: ({ row }) => {
            return (
              <div>
                {row.manageOrg.province}
                {row.manageOrg.city ? '-' + row.manageOrg.city : ''}
                {row.manageOrg.district ? '-' + row.manageOrg.district : ''}
              </div>
            );
          },
        },
      },
      {
        field: 'payOrg',
        title: '借款机构',
        search: { el: 'input', props: { clearable: true } },
      },
      {
        field: 'distributeStatus',
        title: '分配状态',
        enum: distributeStatusOpt,
        search: { el: 'select', props: { filterable: true }, span: 1 },
        fieldNames: { label: 'label', value: 'value' },
        slots: {
          default: ({ row }) => {
            return (
              <>
                {row.distributeStatus
                  ? distributeStatusOpt.find((v) => v.value === row.distributeStatus).label
                  : ''}
              </>
            );
          },
        },
      },
      {
        field: 'tenant.name',
        title: '调解中心',
        search: { el: 'input', props: { clearable: true } },
      },
      {
        field: 'manageOrg.orgName',
        title: '资管公司',
        search: { el: 'input', props: { clearable: true } },
      },
      {
        field: 'cpe.name',
        title: 'CPE',
        search: { el: 'input', props: { clearable: true }, key: 'cpeName' },
      },
      {
        field: 'tenantTime',
        title: '分配中心日期',
        search: { el: 'date-picker', props: { type: 'date', valueFormat: 'YYYY-MM-DD' } },
      },
      {
        field: 'commissionAmount',
        title: '债权总额',
        search: { el: 'input', props: { clearable: true } },
      },
      {
        field: 'cpeDate',
        title: '分配CPE日期',
        search: { el: 'date-picker', props: { type: 'date', valueFormat: 'YYYY-MM-DD' } },
      },
      {
        field: 'borrower.name',
        title: '借款人姓名',
        search: { el: 'input', key: 'borrowerName', props: { clearable: true } },
      },
      {
        field: 'sumRepayAmount',
        title: '已还总额',
        search: { el: 'input', props: { clearable: true } },
      },
      {
        field: 'borrower.idCard',
        title: '身份证',
        search: { el: 'input', props: { clearable: true }, key: 'idCard' },
      },
      {
        field: 'borrower.phone',
        key: 'borrowerPhone',
        title: '手机',
        search: { el: 'input', props: { clearable: true } },
      },
      {
        field: 'principalBalance',
        title: '剩余本金',
      },
      {
        field: 'remaininginterest',
        title: '剩余利息',
      },
      {
        field: 'commission',
        title: '违约金',
      },
    ],
    onCheckboxChange: onCheckboxChange,
  });

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

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