<template>
  <div class="table-box">
    <div>
      <ProTable
        :config="config"
        ref="caseLRef"
        :api="getLoanBackpage"
        :paramCallback="paramCallback"
        :selectdList="selectdList"
      >
        <template #table_top>
          <div class="style-lable" style="width: 100%">
            <div class="item_warp" style="width: 23%">
              <div class="img_warp">
                <img src="@/assets/images/caselist.svg" />
              </div>
              <div class="title_warp">
                <div class="items">在派案件数量</div>
                <div class="item items1">{{ statisis.caseNum }}</div>
              </div>
            </div>
            <div class="item_warp" style="width: 23%">
              <div class="img_warp">
                <img src="@/assets/images/userlist.svg" />
              </div>
              <div class="title_warp">
                <div class="items">在派案人人数</div>
                <div class="item items1">{{ statisis.cpeNum }}</div>
              </div>
            </div>
            <div class="item_warp" style="width: 23%">
              <div class="img_warp">
                <img src="@/assets/images/money.svg" />
              </div>
              <div class="title_warp">
                <div class="items">在派委案金额</div>
                <div class="item items1">￥{{ statisis.amount }}</div>
              </div>
            </div>
            <div class="item_warp" style="width: 23%">
              <div class="img_warp">
                <img src="@/assets/images/tocrash.svg" />
              </div>
              <div class="title_warp">
                <div class="items">待还金额</div>
                <div class="item items1">￥{{ statisis.amount }}</div>
              </div>
            </div>
          </div>
        </template>
        <!-- 表格 header 按钮 -->
        <template #left_buttons>
          <div class="flex rounded w-full h-11 items-center pl-2 btn-grp mb-1">
            <el-dropdown @command="(command) => (dataValue = command)">
              <span class="el-dropdown-link">
                {{ dataValue }}
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-for="item in dataOptions"
                    :key="item.value"
                    :command="item.value"
                    >{{ item.label }}</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button type="primary" @click="backCase">撤案</el-button>
          </div>
        </template>
      </ProTable>
    </div>
    <vxe-modal
      resize
      v-model="showModal"
      title="案件撤案"
      height="342"
      width="560"
      show-footer
      esc-closable
    >
      <div class="top px-3">
        <div class="number-box">
          <div class="number-left">
            <div class="icon-wrapper">
              <img src="@/assets/images/userlist.svg" />
            </div>
          </div>
          <div class="number-right">
            <p>收回客户数量</p>
            <p>{{ statisis1.unCustomerNum }}</p>
          </div>
        </div>
        <div class="number-box">
          <div class="number-left">
            <div class="icon-wrapper">
              <img src="@/assets/images/caselist.svg" />
            </div>
          </div>
          <div class="number-right">
            <p>收回案件数</p>
            <p>{{ statisis1.unCaseNum }}</p>
          </div>
        </div>
        <div class="number-box">
          <div class="number-left">
            <div class="icon-wrapper">
              <img src="@/assets/images/money.svg" />
            </div>
          </div>
          <div class="number-right">
            <p>预计收回金额</p>
            <p>￥{{ statisis1.unAmount }}</p>
          </div>
        </div>
      </div>
      <div class="w-full mt-6 px-3 overflow-hidden flex mytable items-center">
        <div class="font-bold pr-6">撤案案件:</div>
        <el-radio-group v-model="form.option">
          <!-- works when >=2.6.0, recommended ✔️ not work when <2.6.0 ❌ -->
          <el-radio value="withdraw">撤案</el-radio>
          <!-- works when <2.6.0, deprecated act as value when >=3.0.0 -->
          <el-radio label="fullWithdraw">强制撤案</el-radio>
        </el-radio-group>
      </div>
      <template #footer>
        <el-button type="default" @click="showModal = false">取消</el-button>
        <el-button type="primary" @click="submitForm1">确认</el-button>
      </template>
    </vxe-modal>
  </div>
</template>

<script setup name="case-allocation" lang="jsx">
  import {
    getLoanBacktotal,
    getLoanBackpage,
    getLoanBack,
    backDistribute,
    fullWithdraw,
  } from '@/api/allcation';
  import { idCardEncipher } from '@/utils/jiaoyan'
  import { reactive, ref } from 'vue';
  import { ElMessageBox, ElMessage } from 'element-plus';
  import citydata from '../../../assets/citydata';
  import { useRouter } from 'vue-router';
  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';
  import { useDict } from '@/hooks/useDict';
  import { ArrowDown } from '@element-plus/icons-vue';
  const { PhoneResultStatus, ReduceType,RepayStatus, FlowStatus, FollowStatus, DistributeStatus, CaseStatus } =
    useDict(
      'PhoneResultStatus',
      'ReduceType',
      'RepayStatus',
      'FlowStatus',
      'FollowStatus',
      'DistributeStatus',
      'CaseStatus'
    );
  const caseLRef = ref();
  const router = useRouter();
  const selectdList = ref([]);
  const curParam = ref({});
  const showModal = ref(false);
  const dataValue = ref('对查询结果操作');
  const form = reactive({
    option: 'withdraw',
  });
  const dataOptions = [
    {
      label: '对查询结果操作',
      value: '对查询结果操作',
    },
    {
      label: '对选中项操作',
      value: '对选中项操作',
    },
  ];
  const onCheckboxChange = (row) => {
    selectdList.value = row.records;
    dataValue.value = selectdList.value.length > 0 ? '对选中项操作' : '对查询结果操作';
  };
  const statisis = ref({});
  const statisis1 = ref({});
  const getStatisis = (params) => {
    getLoanBacktotal(params).then((res) => {
      if (res.success) {
        statisis.value = res.result;
      }
    });
  };
  const submitForm = async (type) => {
    const ids = selectdList.value.map((v) => v.id).join(',');
    let param = {};
    if (dataValue.value === '对选中项操作') {
      param['loanIds'] = ids;
    } else {
      param = { ...curParam.value };
      delete param['current'];
      delete param['size'];
    }
    if (type === 'withdraw') {
      await backDistribute(param);
      ElMessage({
        type: 'success',
        message: '撤案成功！',
        plain: true,
      });
    } else {
      await fullWithdraw(param);
      ElMessage({
        type: 'success',
        message: '强制撤案成功！',
        plain: true,
      });
    }
    query();
    showModal.value = false;
  };
  const paramCallback = (param) => {
    const obj = JSON.parse(JSON.stringify(param));
    obj['tenant'] = 0;
    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 getStatisis1 = (params, id) => {
    const p = JSON.parse(JSON.stringify(params));
    if (id) {
      p['tenantId'] = id;
    }
    delete p['current'];
    delete p['size'];
    getLoanBack(p).then((res) => {
      if (res.success) {
        statisis1.value = res.result;
      }
    });
  };
  const backCase = async () => {
    if (dataValue.value === '对选中项操作' && (!selectdList.value || !selectdList.value.length)) {
      return ElMessage.warning({
        message: '请先选择操作对象!',
        plain: true,
      });
    }
    let p = {};
    if (dataValue.value === '对选中项操作') {
      p['loanIds'] = selectdList.value.map((v) => v.id);
    } else {
      p = curParam.value;
    }
    getStatisis1(p);
    form.option = 'withdraw';
    showModal.value = true;
  };
  const onCheckboxAll = (flag) => {
    if (flag.checked) {
      selectdList.value = flag.records;
    } else {
      selectdList.value = [];
    }
    dataValue.value = selectdList.value.length > 0 ? '对选中项操作' : '对查询结果操作';
  };
  const onCellClick = (row) => {
    router.push({
      path: '/property/case-detail',
      query: { id: row.id }, //这里不能直接写成 query: JSON.stringify(item)
    });
  };
  const config = reactive({
    maxHeight: 800,
    columns: [
      { type: 'checkbox', title: '', width: 60, fixed: 'left' },
      {
        field: 'caseId',
        title: '案件ID',
        showOverflow: 'tooltip',
        search: { el: 'input', labelWidth: 105 },
        width: 230,
        slots: {
          default: ({ row, rowIndex }) => {
            return (
              <div className="flex">
                <VxeTooltip content={row.caseId} className="inline-block">
                  <VxeTextEllipsis
                    content={row.caseId}
                    status="primary"
                    style="cursor: pointer;"
                    onClick={() => onCellClick(row)}
                  ></VxeTextEllipsis>
                </VxeTooltip>
                <Tag row={row} />
              </div>
            );
          },
        },
      },
      {
        field: 'arealist',
        enum: citydata,
        title: '所属区域',
        showOverflow: 'tooltip',
        width: 100,
        fieldNames: { label: 'name', value: 'name' },
        search: {
          el: 'cascader',
          props: { clearable: true, checkStrictly: true },
          labelWidth: 105,
        },
        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, clearable: true },
          key: 'loanPlatformId',
          labelWidth: 105,
        },
        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,clearable: true }, key: 'manageOrgId', labelWidth: 105 },
      },
      {
        field: 'batchCode',
        title: '导入批次',
        showOverflow: 'tooltip',
        width: 100,
        search: { el: 'input', props: { clearable: true }, key: 'batchCode', labelWidth: 105 },
      },
      {
        field: 'distributeStatus',
        title: '分派状态',
        showOverflow: 'tooltip',
        width: 80,
        enum: DistributeStatus,
        search: { el: 'select', props: { filterable: true,clearable: true }, labelWidth: 105 },
        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,clearable: true }, key: 'tenantId', labelWidth: 105 },
        fieldNames: { label: 'name', value: 'id' },
        title: '调解中心',
        width: 100,
      },
      {
        field: 'tag',
        title: '临时标签',
        showOverflow: 'tooltip',
        width: 140,
        search: {
          el: 'input',
          props: { clearable: true },
          key: 'queryTag',
          labelWidth: 105,
        },
      },
      {
        field: 'repayStatus',
        title: '还款状态',
        showOverflow: 'tooltip',
        width: 80,
        slots: {
          default: ({ row }) => {
            return <div>{row.repayStatus == 'over' ? '已还款' : '待还款'}</div>;
          },
        },
        enum: RepayStatus,
        search: { el: 'select', props: { filterable: true,clearable: true }, labelWidth: 105 },
        fieldNames: { label: 'label', value: 'value' },
      },
      {
        field: 'discount',
        title: '折扣',
        showOverflow: 'tooltip',
        width: 80,
      },
      {
        field: 'weiyuejin',
        title: '当前逾期违约金',
        showOverflow: 'tooltip',
        width: 80,
      },
      {
        field: 'faxi',
        title: '当前逾期罚息',
        showOverflow: 'tooltip',
        width: 80,
      },
      {
        field: 'cpe.username',
        title: 'CPE',
        showOverflow: 'tooltip',
        width: 60,
        search: { el: 'input', props: { clearable: true }, key: 'cpeName', labelWidth: 105 },
      },
      {
        field: 'tenantTime',
        title: '分派中心日期',
        showOverflow: 'tooltip',
        width: 130,
        search: {
          el: 'date-picker',
          props: { type: 'daterange', valueFormat: 'YYYY-MM-DD' },
          labelWidth: 105,
        },
      },
      {
        field: 'commissionAmount',
        title: '债权总额',
        showOverflow: 'tooltip',
        width: 80,
        search: { el: 'input', props: { clearable: true }, labelWidth: 105 },
      },
      {
        field: 'cpeDate',
        title: '分派CPE日期',
        showOverflow: 'tooltip',
        width: 130,
        search: {
          el: 'date-picker',
          props: { type: 'daterange', valueFormat: 'YYYY-MM-DD' },
          labelWidth: 105,
        },
      },
      {
        field: 'borrower.name',
        title: '借款人姓名',
        showOverflow: 'tooltip',
        width: 100,
        search: { el: 'input', key: 'borrowerName', props: { clearable: true }, labelWidth: 105 },
      },
      {
        field: 'sumRepayAmount',
        title: '已还总额',
        showOverflow: 'tooltip',
        width: 80,
        // search: { el: 'input', props: { clearable: true }, labelWidth: 105 },
      },
      {
        field: 'borrower.idCard',
        title: '身份证',
        showOverflow: 'tooltip',
        width: 140,
        slots: {
            default: ({ row }) => {
              return (
                <>
                  {idCardEncipher(row.borrower.idCard)}
                </>
              );
            },
          },
        search: { el: 'input', props: { clearable: true }, key: 'idCard', labelWidth: 105 },
      },
      {
        field: 'borrower.phone',
        showOverflow: 'tooltip',
        title: '手机',
        width: 100,
        search: { el: 'input', key: 'borrowerPhone', props: { clearable: true }, labelWidth: 105 },
      },
      {
        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,clearable: true }, labelWidth: 105 },
        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: '合同编号',
        search: { el: 'input', props: { clearable: true }, labelWidth: 105,key: 'constantNo' },
        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 submitForm1 = () => {
    submitForm(form.option);
  };

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

  onMounted(() => {
    query();
  });
</script>
<style lang="scss" scoped>
  .top {
    display: flex;
    .number-box {
      font-size: 15px;
      width: 235px;
      padding: 5px 0 5px 15px;
      border: 1px solid rgba(0, 0, 0, 0.1);
      height: 50px;
      display: flex;
      margin-right: 10px;
      margin-top: 10px;
    }
    .icon-wrapper {
      width: 40px;
      height: 40px;
      text-align: center;
      line-height: 40px;
      color: #bbc3ca;
      margin-right: 10px;
      font-size: 37px;
    }
  }
  .number-right {
    p:nth-child(1) {
      color: #aaa;
      font-size: 13px;
    }
  }
</style>
