<template>
  <div class="card table-box">
    <div class="h-full w-full flex flex-col">
      <div class="mt-2">
        <el-button type="primary" @click="repair">修复申请</el-button>
        <el-button type="primary" @click="reduce">减免申请</el-button>
        <el-button type="primary" @click="split">分期申请</el-button>
      </div>
      <div class="detail-steps" style="display: none">
        <el-steps :active="activeStep">
          <el-step
            :title="item.title"
            :description="item.desc"
            :class="{ current: index + 1 === activeStep }"
            v-for="(item, index) in stepList"
            :key="item.title"
          />
        </el-steps>
      </div>
      <div id="baseinfo">
        <div class="box-title">案人基本信息</div>
        <div class="box-content">
          <table>
            <tbody>
              <tr>
                <td class="label">姓名</td>
                <td>{{ detail?.borrower?.name }}</td>
                <td class="label">电话</td>
                <td>{{ detail?.borrower?.phone }}</td>
                <td class="label">户籍区域</td>
                <td>{{
                  detail?.borrower?.domicileCity + ',' + detail?.borrower?.domicileProvince
                }}</td>
              </tr>
              <tr>
                <td class="label">证件号</td>
                <td>{{ detail?.borrower?.idCard }}</td>
                <td class="label">户籍地址</td>
                <td colspan="3">{{ detail?.borrower?.address }}</td>
              </tr>
            </tbody>
            <!-- Add more rows as needed -->
          </table>
        </div>
      </div>
      <div id="caserelation">
        <div class="box-title">案件联系人</div>
        <div class="box-content">
          <ProTable
            :config="relationConfig"
            :data="guarantorData"
            :showPagination="false"
            :showToolBar="false"
          />
        </div>
      </div>
      <div id="casedetail">
        <div class="box-title" style="line-height: 43px;"
          >案件明细
          <el-button type="primary" @click="foldCaseTree">展开/折叠 </el-button>
        </div>
        <div class="box-content">
          <div class="flex mb-2">
            <div class="mr-4"
              >委案金额：<span class="text-blue-500">{{ sumCase.commissionAmount }}</span
              >元</div
            >
            <div class="mr-4"
              >累计减免金额：<span class="text-blue-500">{{ sumCase.sumReductionAmount }}</span
              >元</div
            >
            <div class="mr-4"
              >累计还款金额：<span class="text-blue-500">{{ sumCase.sumRepayAmount }}</span
              >元</div
            >
            <div class="mr-4"
              >剩余待还金额：<span class="text-blue-500">{{ sumCase.remainingAmount }}</span
              >元</div
            >
          </div>
          <vxe-grid
            v-bind="caseDetailConfig"
            ref="caseDetailRef"
            @cell-click="onCellCase"
          >
            <template #expand_content="{ row }">
              <div class="expand-box">
                <div>案件明细</div>
                <div class="expand-table">
                  <table
                    ><tbody>
                      <tr>
                        <td class="label">案件ID</td>
                        <td>{{ row?.caseId }}</td>
                        <td class="label">借款机构</td>
                        <td>{{ row?.loanPlatform?.name }}</td>
                        <td class="label">资管公司</td>
                        <td>{{ row?.manageOrg.orgName }}</td>
                      </tr>
                      <tr>
                        <td class="label">身份证</td>
                        <td>{{ row?.borrower?.idCard }}</td>
                        <td class="label">手机号</td>
                        <td>{{ row?.borrower?.phone }}</td>
                        <td class="label">折扣</td>
                        <td>{{ row?.discount }}</td>
                        <td class="label">委案金额</td>
                        <td>{{ row?.commissionAmount }}</td>
                      </tr>
                      <tr>
                        <td class="label">累计还款金额</td>
                        <td>{{ row?.sumRepayAmount }}</td>
                        <td class="label">累计减免金额</td>
                        <td>{{ row?.sumReductionAmount }}</td>
                        <td class="label">剩余待还金额</td>
                        <td>{{ row?.remainingAmount }}</td>
                        <td class="label">折扣后金额</td>
                        <td>{{ (row?.remainingAmount && row?.discount) ? (Decimal(row?.remainingAmount).mul(Decimal(row?.discount))) : row?.remainingAmount }}</td>
                      </tr>
                      <tr>
                        <td class="label">CPE</td>
                        <td>{{ row?.cpe?.username }}</td>
                        <td class="label">分派CPE日期</td>
                        <td>{{ row?.cpeDate }}</td>
                        <td class="label">本金余额</td>
                        <td>{{ row?.principalBalance }}</td>
                        <td class="label">案件状态</td>
                        <td>
                          {{
                            row?.caseStatus
                              ? caseStatusOpt.find((v) => v.value === row?.caseStatus).label
                              : ''
                          }}</td
                        >
                      </tr>
                      <tr>
                        <td class="label">欠息额</td>
                        <td>{{ row?.debitInterest }}</td>
                        <td class="label">手续费</td>
                        <td>{{ row?.commission }}</td>
                        <td class="label">跟进结果</td>
                        <td>{{
                          row?.followStatus
                            ? followStatusOpt.find((v) => v.value === row?.followStatus).label
                            : ''
                        }}</td>
                        <td class="label">跟进状态</td>
                        <td>{{
                          row?.phoneResultStatus
                            ? phoneResultStatusOpt.find((v) => v.value === row?.phoneResultStatus)
                                .label
                            : ''
                        }}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </template>
          </vxe-grid>
        </div>
      </div>
      <vxe-tabs v-model="selectTab" type="border-card" :height="140" class="flex-1 mt-3">
        <vxe-tab-pane title="跟进记录" name="4">
          <div id="callrecord">
            <div class="box-title"
              >跟进记录
              <!-- <el-select v-model="form.relation" placeholder="请选择">
                      <el-option
                      v-for="item in caseDetailConfig.data"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                      />
                  </el-select> -->
            </div>
            <div class="box-content">
              <ProTable
                :config="recordConfig"
                :data="recordData"
                :showPagination="false"
                :showToolBar="false"
              />
            </div>
          </div>
        </vxe-tab-pane>
        <vxe-tab-pane title="减免记录" name="5">
          <div id="reducerecord">
            <div class="box-title">减免记录</div>
            <div class="box-content">
              <ProTable
                :config="reduceConfig"
                :data="reduceData"
                :showPagination="false"
                :showToolBar="false"
              />
            </div>
          </div>
        </vxe-tab-pane>
        <vxe-tab-pane title="分期记录" name="6">
          <div id="splitrecord">
            <div class="box-title">分期记录</div>
            <div class="box-content flex">
              <!-- <table style="margin-bottom: 10px">
              <tbody>
                <tr>
                  <td class="label">分期申请ID</td>
                  <td>John Doe</td>
                  <td class="label">还款总额</td>
                  <td>30</td>
                  <td class="label">分期申请时间</td>
                  <td>30</td>
                </tr>
                <tr>
                  <td class="label">还款期数</td>
                  <td>johndoe@example.com</td>
                  <td class="label">首期还款日</td>
                  <td>johndoe@example.com</td>
                  <td class="label">分期生效时间</td>
                  <td>johndoe@example.com</td>
                </tr>
              </tbody>
            </table> -->
              <div class="w-2/3">
                <ProTable
                  :config="splitConfig"
                  ref="splitRef"
                  :data="splitData"
                  :showPagination="false"
                  :showToolBar="false"
                />
              </div>
              <div class="w-1/3 pl-3">
                <ProTable
                  :config="splitDeConfig"
                  :data="splitDeData"
                  :showPagination="false"
                  :showToolBar="false"
                />
              </div>
            </div>
          </div>
        </vxe-tab-pane>
        <vxe-tab-pane title="还款记录" name="7">
          <div id="returnrecord">
            <div class="box-title">还款记录</div>
            <div class="box-content">
              <ProTable
                :config="returnConfig"
                :data="returnData"
                :showPagination="false"
                :showToolBar="false"
              />
            </div>
          </div>
        </vxe-tab-pane>
      </vxe-tabs>
    </div>
    <repairModal ref="repairModalRef"></repairModal>
    <returnModal ref="returnModalRef" @success="query('还款')"></returnModal>
    <reduceDrawer ref="reduceDrawerRef" @success="query('减免')"></reduceDrawer>
    <splitDrawer ref="splitDrawerRef" @success="query('分期')"></splitDrawer>
    <callDrawer ref="callDrawerRef" @success="query('跟进')"></callDrawer>
    <el-image-viewer :url-list="srcList" v-if="RefImage" @close="RefImage = false" />
  </div>
</template>

<script setup lang="jsx" name="caseDetail">
  import { useRoute } from 'vue-router';
  import { reactive, ref, onBeforeMount, onMounted } from 'vue';
  import { ElButton } from 'element-plus';
  import repairModal from './components/repairModal.vue';
  import returnModal from './components/returnModal.vue';
  import reduceDrawer from './components/reduceDrawer.vue';
  import splitDrawer from './components/splitDrawer.vue';
  import callDrawer from './components/callDrawer.vue';
  import { getAppEnvConfig } from '@/utils/env';
  import {
    getCredit,
    getTrackRecordPage,
    getReduces,
    getByStages,
    listByBorrower,
    getRepayRecords,
    getGuarantors,
  } from '@/api/property';
  import { Download } from '@element-plus/icons-vue';
  import { saveAudit } from '@/api/audit';
  import Decimal from 'decimal.js';

  import { inject } from 'vue';
  const envs = getAppEnvConfig();
  const selectTab = ref('1');
  const returnData = ref([]);
  const recordData = ref([]);
  const guarantorData = ref([]);
  const reduceData = ref([]);
  const splitData = ref([]);
  const srcList = ref([]);
  const RefImage = ref(false);
  const splitDeData = ref([]);
  const detail = ref({
    borrower: {
      guarantors: [],
    },
  });
  const sumCase = ref({
    commissionAmount: 0,
    sumReductionAmount: 0,
    sumRepayAmount: 0,
    remainingAmount: 0
  });
  const downloadfile = inject('download');
  const splitRef = ref();
  const caseDetailRef = ref();
  const returnModalRef = ref();
  const repairModalRef = ref();
  const reduceTRef = ref();
  const splitDrawerRef = ref();
  const callDrawerRef = ref();
  const reduceDrawerRef = ref();
  const route = useRoute();
  const borrowerPara = reactive({
    borrowerId: 'sss',
  });
  const activeStep = ref(2);
  const stepList = ref([
    { title: '已分派', desc: 'sadas' },
    { title: '跟进中', desc: 'sadas1' },
    { title: '还款中', desc: 'sadas1' },
  ]);
  const callTelephone = (row) => {
    callDrawerRef.value.openModal(
      JSON.parse(JSON.stringify(row)),
      JSON.parse(JSON.stringify(detail.value)),
      JSON.parse(JSON.stringify(caseDetailConfig.data))
    );
  };
  const options = [
    {
      value: 'repay',
      label: '直接还款',
    },
    {
      value: 'by_stages',
      label: '分期还款',
    },
    {
      value: 'settle',
      label: '结清减免还款',
    },
  ];
  const preview = (item, type) => {
    const list = [];
    item[type].forEach((v) => {
      list.push(envs.VITE_GLOB_API_URL_PREFIX + '/sys/static/' + v);
    });
    RefImage.value = true;
    srcList.value = list;
  };
  const download = (item) => {
    const name = item.slice(item.lastIndexOf('/') + 1, item.length);
    downloadfile(envs.VITE_GLOB_API_URL_PREFIX + '/sys/static/' + item, {}, name);
  };
  const followStatusOpt = [
    { label: '接通后挂断', value: 'hang_up' },
    { label: '接通有实质进展', value: 'progress' },
    { label: '接通有效转告', value: 'pass_on' },
    { label: '接通拒绝转告', value: 'no_pass' },
    { label: '接听后挂断', value: 'Hang_up_after_answering' },
    { label: '接通无应答', value: 'No_response_when_connected' },
    { label: '称与债人无关', value: 'Claims_unrelated_to_creditors' },
    { label: '称非本人', value: 'Claiming_not_to_be_myself' },
    { label: '无人接听', value: 'no_answer' },
    { label: '关机', value: 'Shutdown' },
    { label: '空号', value: 'dead_number' },
    { label: '占线/忙音/正在通话中', value: 'Busy' },
    { label: '停机', value: 'closing_down' },
    { label: '机器人回复', value: 'Robot_reply' },
    { label: '微信', value: 'WeChat' },
    { label: '短信', value: 'short_message' },
    { label: 'QQ', value: 'QQ' },
    { label: '飞书', value: 'fly' },
    { label: '钉钉', value: 'DING' },
  ];
  const phoneResultStatusOpt = [
    { label: '后续再跟进', value: 'later' },
    { label: '承诺还款', value: 'Promise_Repayment' },
    { label: '暂无还款意愿', value: 'No_Repay' },
    { label: '要求停催', value: 'Stop_Urging' },
    { label: '情绪激动抗拒', value: 'resistance' },
    { label: '拒绝还款', value: 'Refuse_Repayment' },
    { label: '已还款', value: 'Repaired' },
    { label: '代履行还款', value: 'repayment_others' },
  ];
  const caseStatusOpt = [
    { label: '正常', value: 'normal' },
    { label: '撤案', value: 'withdraw' },
    { label: '留案', value: 'stay' },
  ];
  const returnConfig = reactive({
    columns: [
      {
        field: 'id',
        title: '还款记录ID',
        showOverflow: 'tooltip',
      },
      {
        field: 'realRepayAmount',
        title: '实际还款金额',
        showOverflow: 'tooltip',
      },
      {
        field: 'realRepayTime',
        title: '实际还款时间',
        showOverflow: 'tooltip',
      },
      {
        field: 'repayType',
        showOverflow: 'tooltip',
        title: '还款方式',
        slots: {
          default: ({ row }) => {
            return (
              <>
                {row.repayType
                  ? options.find((v) => v.value === row.repayType).label
                  : ''}
              </>
            );
          },
        },
      },
      {
        field: 'reduce.id',
        title: '关联减免ID',
        showOverflow: 'tooltip',
      },
      {
        field: 'stages.id',
        title: '关联分期ID',
        showOverflow: 'tooltip',
      },
      {
        field: 'stages.totalPeriod',
        title: '关联分期期次',
        showOverflow: 'tooltip',
      },
      {
        field: 'repayAmount',
        title: '应还金额',
        showOverflow: 'tooltip',
      },
      {
        field: 'loanPlatform',
        title: '借款机构',
        showOverflow: 'tooltip',
      },
    ],
    toolbarConfig: { enabled: false },
  });

  const recordConfig = reactive({
    columns: [
      {
        field: 'id',
        title: '跟进记录ID',
        showOverflow: 'tooltip',
      },
      {
        field: 'trackTime',
        title: '跟进日期',
        showOverflow: 'tooltip',
      },
      {
        field: 'nextTime',
        title: '下次跟进时间',
        showOverflow: 'tooltip',
      },
      {
        field: 'guarantor.name',
        title: '联系人姓名',
        showOverflow: 'tooltip',
      },
      {
        field: 'guarantor.phone',
        title: '联系人号码',
        showOverflow: 'tooltip',
      },
      {
        field: 'followStatus',
        title: '拨打跟进结果',
        showOverflow: 'tooltip',
        slots: {
          default: ({ row }) => {
            return (
              <>
                {row.followStatus
                  ? followStatusOpt.find((v) => v.value === row.followStatus).label
                  : ''}
              </>
            );
          },
        },
      },
      {
        field: 'phoneResultStatus',
        title: '拨打处置状态',
        showOverflow: 'tooltip',
        slots: {
          default: ({ row }) => {
            return (
              <>
                {row.phoneResultStatus
                  ? phoneResultStatusOpt.find((v) => v.value === row.phoneResultStatus).label
                  : ''}
              </>
            );
          },
        },
      },
      {
        field: 'remark',
        title: '备注',
        showOverflow: 'tooltip',
      },
      {
        field: 'voices',
        title: '通话录音',
        showOverflow: 'tooltip',
        slots: {
          default: ({ row, rowIndex }) => {
            if (row.voices && row.voices.length > 0) {
              return (
                <>
                  {row.voices.map((item, index) => (
                    <el-icon>
                      <Download onClick={() => download(item)} />
                    </el-icon>
                  ))}
                </>
              );
            }
          },
        },
      },
      {
        field: 'code',
        title: '微信图片附件',
        slots: {
          default: ({ row, rowIndex }) => {
            if (row.images && row.images.length > 0) {
              return (
                <>
                  <div className="flex justify-center">
                    <ElButton onClick={() => preview(row, 'images')} link type="primary">
                      查看
                    </ElButton>
                  </div>
                </>
              );
            }
          },
        },
      },
      {
        field: 'code',
        title: '短信图片附件',
        slots: {
          default: ({ row, rowIndex }) => {
            if (row.notes && row.notes.length > 0) {
              return (
                <>
                  <div className="flex justify-center">
                    <ElButton onClick={() => preview(row, 'notes')} link type="primary">
                      查看
                    </ElButton>
                  </div>
                </>
              );
            }
          },
        },
      },
      {
        field: 'code',
        title: '其他图片附件',
        slots: {
          default: ({ row, rowIndex }) => {
            if (row.others && row.others.length > 0) {
              return (
                <>
                  <div className="flex justify-center">
                    <ElButton onClick={() => preview(row, 'others')} link type="primary">
                      查看
                    </ElButton>
                  </div>
                </>
              );
            }
          },
        },
      },
    ],
    toolbarConfig: { enabled: false },
  });
  const relationConfig = reactive({
    columns: [
      { type: 'seq', width: 70 },
      {
        field: 'name',
        title: '联系人姓名',
        showOverflow: 'tooltip',
      },
      {
        field: 'kinship',
        title: '与债权人关系',
        showOverflow: 'tooltip',
      },
      {
        field: 'phone',
        title: '号码',
        showOverflow: 'tooltip',
        slots: {
          default: ({ row }) => {
            return <>{row.phone + ' ' + (row.status === 'Y' ? '有效' : '无效')}</>;
          },
        },
      },
      {
        field: 'code',
        title: '',
        fixed: 'right',
        slots: {
          default: ({ row, rowIndex }) => {
            return (
              <>
                <ElButton
                  type="primary"
                  onClick={() => callTelephone(row)}
                  disabled={row.status !== 'Y'}
                >
                  {/* <ElButton type="primary" onClick={() => callTelephone(row)}> */}
                  拨打跟进
                </ElButton>
              </>
            );
          },
        },
      },
    ],
    toolbarConfig: { enabled: false },
  });
  const returnCrash = (row, type) => {
    if (type === '分期还款') {
      const current = splitRef.value.element.getCurrentRecord();
      console.log('current', current);
      returnModalRef.value.openModal(
        JSON.parse(JSON.stringify(row)),
        JSON.parse(JSON.stringify(current)),
        type
      );
    } else {
      returnModalRef.value.openModal(
        JSON.parse(JSON.stringify(row)),
        JSON.parse(JSON.stringify(detail.value)),
        type
      );
    }
  };
  const repair = () => {
    repairModalRef.value.openModal(JSON.parse(JSON.stringify(detail.value)));
  };
  const reduce = () => {
    reduceDrawerRef.value.openModal(
      JSON.parse(JSON.stringify(detail.value)),
      JSON.parse(JSON.stringify(caseDetailConfig.data))
    );
  };
  const split = () => {
    splitDrawerRef.value.openModal(
      JSON.parse(JSON.stringify(detail.value)),
      JSON.parse(JSON.stringify(caseDetailConfig.data))
    );
  };
  const caseDetailConfig = reactive({
    columns: [
      { type: 'expand', width: 80, slots: { content: 'expand_content' } },
      {
        field: 'caseId',
        title: '案件ID',
        showOverflow: 'tooltip',
      },
      {
        field: 'product',
        title: '产品',
        showOverflow: 'tooltip',
      },
      {
        field: 'loanPlatform.name',
        title: '借款机构',
        showOverflow: 'tooltip',
      },
      {
        field: 'commissionAmount',
        title: '委案金额',
        showOverflow: 'tooltip',
      },
      {
        field: 'sumReductionAmount',
        title: '累计减免金额',
        showOverflow: 'tooltip',
      },
      {
        field: 'sumRepayAmount',
        title: '累计还款金额',
        showOverflow: 'tooltip',
      },
      {
        field: 'remainingAmount',
        title: '剩余待还金额',
        showOverflow: 'tooltip',
      },
      {
        field: 'code',
        fixed: 'right',
        title: '',
        slots: {
          default: ({ row, rowIndex }) => {
            return (
              <>
                <ElButton type="primary" onClick={() => returnCrash(row, '直接还款')}>
                  还款
                </ElButton>
              </>
            );
          },
        },
      },
    ],
    data: [],
    toolbarConfig: { enabled: false },
  });
  const onCellClick = ({ row, rowIndex }) => {
    splitDeData.value = row.byStagesRecords;
  };
  const add = (a, b) => {
    return (parseFloat(a) + parseFloat(b)).toFixed(2);
  };

  const splitConfig = reactive({
    columns: [
      {
        field: 'caseId',
        title: '案件ID',
        showOverflow: 'tooltip',
        width: 80,
        slots: {
          default: ({ row }) => {
            return <>{Array.from(new Set(row.loans.map((v) => v.caseId))).join(',')}</>;
          },
        },
      },
      {
        showOverflow: 'tooltip',
        title: '借款机构',
        slots: {
          default: ({ row }) => {
            return <>{Array.from(new Set(row.loans.map((v) => v.loanPlatform.name))).join(',')}</>;
          },
        },
      },
      {
        field: 'totalRepayAmount',
        showOverflow: 'tooltip',
        title: '还款总额',
        width: 80,
      },
      {
        field: 'applyDate',
        title: '分期申请时间',
        showOverflow: 'tooltip',
        width: 115,
      },
      {
        field: 'effectiveTime',
        title: '分期生效时间',
        showOverflow: 'tooltip',
        width: 115,
      },
      {
        field: 'totalPeriod',
        showOverflow: 'tooltip',
        title: '还款期数',
        width: 80,
      },
      {
        field: 'firstApplyDate',
        title: '首期还款日',
        showOverflow: 'tooltip',
        width: 100,
      },
      {
        field: 'remainingAmount',
        title: '剩余待还金额',
        showOverflow: 'tooltip',
        width: 110,
      },
    ],
    onCellClick: onCellClick,
    toolbarConfig: { enabled: false },
  });
  const splitDeConfig = reactive({
    columns: [
      {
        field: 'period',
        title: '期次',
        showOverflow: 'tooltip',
      },
      {
        field: 'playApplyDate',
        title: '到期日',
        showOverflow: 'tooltip',
      },
      {
        field: 'repayStatus',
        title: '状态',
        showOverflow: 'tooltip',
        slots: {
          default: ({ row }) => {
            return <>{row.repayStatus ? (row.repayStatus === 'over' ? '已还款' : '待还款') : ''}</>;
          },
        },
      },
      {
        field: 'applyAmount',
        title: '金额',
        showOverflow: 'tooltip',
      },
      {
        field: 'code',
        title: '操作',
        fixed: 'right',
        slots: {
          default: ({ row, rowIndex }) => {
            return (
              <>
                <ElButton
                  type="primary"
                  onClick={() => returnCrash(row, '分期还款')}
                  disabled={row.repayStatus === 'over'}
                >
                  还款
                </ElButton>
              </>
            );
          },
        },
      },
    ],
    toolbarConfig: { enabled: false },
  });
  const getTrackRecordList = (borrowerId) => {
    getTrackRecordPage(borrowerId).then((res) => {
      if (res.result && res.result) {
        recordData.value = res.result;
      }
    });
  };
  const getGuarantorsList = (borrowerId) => {
    getGuarantors(borrowerId).then((res) => {
      if (res.result && res.result) {
        guarantorData.value = res.result;
      }
    });
  };

  const onCellCase = ({ row, rowIndex }) => {
    console.log('row.borrower.id', row);
    getTrackRecordList(row.borrower.id);
  };
  const anchor = (type) => {
    document.querySelector(`#${type}`).scrollIntoView(true);
  };
  const foldCaseTree = () => {
    if (caseDetailRef.value?.getRowExpandRecords().length === caseDetailConfig.data.length) {
      caseDetailRef.value?.setAllRowExpand(false);
    } else {
      caseDetailRef.value?.setAllRowExpand(true);
    }
  };
  const audit = (row) => {
    saveAudit({
      trackRecord: {
        id: row.id,
      },
    }).then((res) => {});
  };
  const reduceConfig = reactive({
    columns: [
      {
        field: 'caseId',
        title: '案件ID',
        showOverflow: 'tooltip',
        slots: {
          default: ({ row }) => {
            return <>{Array.from(new Set(row.reduceRecords.map((v) => v.loan.caseId))).join(',')}</>;
          },
        },
      },
      {
        field: 'reduceAmount',
        title: '减免金额',
        showOverflow: 'tooltip',
        slots: {
          default: ({ row }) => {
            return <>{Array.from(new Set(row.reduceRecords.map((v) => v.reduceAmount))).join(',')}</>;
          },
        },
      },
      {
        field: 'totalReduceAmount',
        title: '减免金额(总计)',
        showOverflow: 'tooltip',
      },
      {
        field: 'totalNumber',
        title: '减免案件数',
        showOverflow: 'tooltip',
      },
      {
        field: 'remainingAmount',
        title: '剩余待还金额',
        showOverflow: 'tooltip',
      },
      {
        field: 'totalPayAmount',
        title: '累计还款金额',
        showOverflow: 'tooltip',
      },
      {
        field: 'reduceType',
        title: '减免类型',
        showOverflow: 'tooltip',
        slots: {
          default: ({ row }) => {
            return (
              <>{row.reduceType ? (row.reduceType === 'settle' ? '结清减免' : '分期减免') : ''}</>
            );
          },
        },
      },
      {
        field: 'id',
        showOverflow: 'tooltip',
        title: '减免申请ID',
      },
      {
        field: 'applyDate',
        showOverflow: 'tooltip',
        title: '减免截止时间',
      },
      {
        field: 'inEffectDate',
        showOverflow: 'tooltip',
        title: '减免生效时间',
      },
      {
        field: 'code',
        title: '操作',
        fixed: 'right',
        slots: {
          default: ({ row, rowIndex }) => {
            return (
              <>
                <ElButton type="primary" onClick={() => returnCrash(row, '结清减免还款')}>
                  还款
                </ElButton>
              </>
            );
          },
        },
      },
    ],
    toolbarConfig: { enabled: false },
  });
  const query = async (type) => {
    const id = JSON.parse(route.query.id);
    const { result } = await getCredit(id);
    detail.value = result;
    if (detail.value?.borrower?.id) {
      if (type === '跟进') {
        getTrackRecordList(detail.value?.borrower?.id);
      } else if (type === '减免') {
        getReduces(detail.value?.borrower?.id).then((res) => {
          if (res.result && res.result) {
            reduceData.value = res.result;
          }
        });
      } else if (type === '分期') {
        getByStages(detail.value?.borrower?.id).then((res) => {
          if (res.result && res.result) {
            splitData.value = res.result;
          }
        });
      } else if (type === '还款') {
        getRepayRecords(detail.value?.borrower?.id).then((res) => {
          if (res.result && res.result) {
            returnData.value = res.result;
          }
        });
        getByStages(detail.value?.borrower?.id).then((res) => {
          if (res.result && res.result) {
            splitData.value = res.result;
          }
        });
        getReduces(detail.value?.borrower?.id).then((res) => {
          if (res.result && res.result) {
            reduceData.value = res.result;
          }
        });
        listByBorrower(detail.value?.borrower?.id).then((res) => {
          if (res.result && res.result) {
            caseDetailConfig.data = res.result;
            const sum = {
              commissionAmount: 0,
              sumReductionAmount: 0,
              sumRepayAmount: 0,
              remainingAmount: 0
            }
            res.result.forEach((column) => {
              sum['commissionAmount'] = Decimal(sum['commissionAmount']).add(
                Decimal(Number(column.commissionAmount) || 0))
              sum['sumReductionAmount'] = Decimal(sum['sumReductionAmount']).add(
                Decimal(Number(column.sumReductionAmount) || 0))
              sum['sumRepayAmount'] = Decimal(sum['sumRepayAmount']).add(
                Decimal(Number(column.sumRepayAmount) || 0))
              sum['remainingAmount'] = Decimal(sum['remainingAmount']).add(
                Decimal(Number(column.remainingAmount) || 0))
            })
            sumCase.value = sum
          }
        });
      }
    }
  };
  onBeforeMount(async () => {
    const id = JSON.parse(route.query.id);
    const { result } = await getCredit(id);
    console.log('result', result);
    detail.value = result;
    if (detail.value?.borrower?.id) {
      getGuarantorsList(detail.value?.borrower?.id);
      getTrackRecordList(detail.value?.borrower?.id);
      listByBorrower(detail.value?.borrower?.id).then((res) => {
        if (res.result && res.result) {
          caseDetailConfig.data = res.result;
          const sum = {
            commissionAmount: 0,
            sumReductionAmount: 0,
            sumRepayAmount: 0,
            remainingAmount: 0
          }
          res.result.forEach((column) => {
            sum['commissionAmount'] = Decimal(sum['commissionAmount']).add(
              Decimal(Number(column.commissionAmount) || 0))
            sum['sumReductionAmount'] = Decimal(sum['sumReductionAmount']).add(
              Decimal(Number(column.sumReductionAmount) || 0))
            sum['sumRepayAmount'] = Decimal(sum['sumRepayAmount']).add(
              Decimal(Number(column.sumRepayAmount) || 0))
            sum['remainingAmount'] = Decimal(sum['remainingAmount']).add(
              Decimal(Number(column.remainingAmount) || 0))
          })
          sumCase.value = sum
        }
      });
      getReduces(detail.value?.borrower?.id).then((res) => {
        if (res.result && res.result) {
          reduceData.value = res.result;
        }
      });
      getByStages(detail.value?.borrower?.id).then((res) => {
        if (res.result && res.result) {
          splitData.value = res.result;
        }
      });
      getRepayRecords(detail.value?.borrower?.id).then((res) => {
        if (res.result && res.result) {
          returnData.value = res.result;
        }
      });
    }
  });
</script>

<style lang="scss" scoped>
  .table-box {
    .navigation-box {
      color: rgba(0, 0, 0, 0.88);
      .anchor-item {
        position: relative;
        padding-bottom: 20px;
        cursor: pointer;
        &::before {
          display: block;
          content: '';
          position: absolute;
          width: 10px;
          height: 10px;
          border-radius: 100%;
          border: 3px solid rgba(22, 119, 255, 1);
          left: -30px;
          top: 7px;
        }
        &::after {
          position: absolute;
          height: 100%;
          width: 1px;
          background: rgba(0, 0, 0, 0.06);
          display: block;
          top: 10px;
          content: '';
          left: -25px;
        }
        &:last-child::after {
          display: none;
        }
      }
    }
  }
  .detail-steps {
    margin-top: 20px;
    margin-left: 10px;
    :deep(.el-step__icon) {
      height: 8px;
      border: none;
      width: 8px;
      overflow: hidden;
      background: #1677ff;
      .el-step__icon-inner {
        display: none;
      }
    }
    :deep(.is-process),
    :deep(.is-wait) {
      .el-step__icon {
        background: rgba(0, 0, 0, 0.45);
      }
    }
    :deep(.el-step__title.is-finish) {
      color: #000;
      font-weight: 400;
    }
    :deep(.el-step__title.is-process),
    :deep(.el-step__title.is-process) {
      color: rgba(0, 0, 0, 0.45);
      font-weight: 400;
    }
    :deep(.el-step__head) {
      left: 20px;
      .el-step__line {
        left: 14px;
        top: 13px;
        height: 1px;
        right: 8px;
      }
    }
    :deep(.el-step__description) {
      color: rgba(0, 0, 0, 0.45);
    }
    .el-step.current {
      :deep(.el-step__icon) {
        height: 10px;
        width: 10px;
      }
      :deep(.el-step__title.is-finish) {
        color: #000;
        font-weight: 600;
      }
      :deep(.el-step__description) {
        color: #000;
      }
    }
  }
  .box-title {
    font-weight: 600;
    font-size: 14px;
    color: #000000;
    line-height: 34px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.06);
    margin-bottom: 8px;
    margin-left: 10px;
  }
  .box-content {
    padding-right: 40px;
    :deep(.card) {
      padding: 0;
      border: none;
    }
  }
  #baseinfo,
  #reducerecord,
  #splitrecord {
    table {
      width: 100%;
      border-collapse: collapse;
    }
    td {
      border: 1px solid rgba(5, 5, 5, 0.06);
      background: #fff;
      padding: 8px;
      width: 240px;
      &.label {
        width: 125px;
        background: var(--el-color-primary-light-9);
      }
    }
  }

  .expand-box {
    background: #fff;
    padding: 20px;
    .expand-table {
      color: #000;
      table {
        width: 100%;
        margin-top: 10px;
        border-collapse: collapse;
      }
      td {
        border: 1px solid rgba(5, 5, 5, 0.06);
        background: #fff;
        padding: 8px;
        width: 240px;
        &.label {
          background: var(--el-color-primary-light-9);
        }
      }
    }
  }
</style>
