<template>
  <div class="card table-box">
    <div class="public-header font-bold mb-1 flex" style="font-size: 15px; line-height: 20px">
      {{ detail?.caseId }}
      <Tag :row="detail" />
    </div>
    <div class="h-full w-full flex flex-col">
      <div class="mt-2">
        <!-- <el-button type="primary" @click="repair" 
        v-permission="'repair_apply'"
        >修复申请</el-button> -->
        <el-button
          type="primary"
          @click="reduce"
          :disabled="detail && detail.repayStatus && detail.repayStatus === 'over'"
          v-permission="'case_handle'"
          >减免申请</el-button
        >
        <el-button
          type="primary"
          @click="split"
          v-permission="'case_handle'"
          :disabled="detail && detail.repayStatus && detail.repayStatus === 'over'"
          >分期申请</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 class="flex">
        <div class="w-1/2">
          <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>
                  </tr>
                  <tr>
                    <td class="label">性别</td>
                    <td>{{ detail?.borrower?.sex === 'M' ? '男' : detail?.borrower?.sex === 'W' ? '女' : '' }}</td>
                    <td class="label">年龄</td>
                    <td>{{ detail?.borrower?.age }}</td>
                  </tr>
                  <tr>
                    <td class="label">出生日期</td>
                    <td>{{ detail?.borrower?.birthday }}</td>
                    <td class="label">教育程度</td>
                    <td>{{ detail?.borrower?.educationLevel }}</td>
                  </tr>
                  <tr>
                    <td class="label">借款人所属行业</td>
                    <td>{{ detail?.borrower?.industry }}</td>
                    <td class="label">有效邮箱</td>
                    <td>{{ detail?.borrower?.email }}</td>
                  </tr>
                  <tr>
                    <td class="label">户籍区域</td>
                    <td>{{
                      detail?.borrower?.domicileCity + ',' + detail?.borrower?.domicileProvince
                    }}</td>
                    <td class="label">证件号</td>
                    <td>{{ detail?.borrower?.idCard }}</td>
                  </tr>
                  <tr>
                    <td class="label">联系地址</td>
                    <td colspan="3">{{ detail?.borrower?.address }}</td>
                  </tr>
                  <tr>
                    <td class="label">户籍地址</td>
                    <td colspan="3">{{ detail?.borrower?.domicileAddress }}</td>
                  </tr>
                  
                  <tr>
                    <td class="label">案件还款状态</td>
                    <td colspan="3">{{ detail.repayStatus == 'over' ? '已还款' : '待还款' }}</td>
                  </tr>
                </tbody>
                <!-- Add more rows as needed -->
              </table>
            </div>
          </div>
        </div>
        <div class="w-1/2">
          <div id="caserelation">
            <div class="box-title">案件联系人</div>
            <div class="box-content">
              <ProTable
                :config="relationConfig"
                :data="guarantorData"
                :showPagination="false"
                :showToolBar="false"
              />
            </div>
          </div>
        </div>
      </div>
      <vxe-tabs v-model="selectTab" :height="140" class="flex-1 mt-3">
        <vxe-tab-pane title="案件明细" name="3">
          <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="style-lable" style="width: 100%">
                <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">￥{{ sumCase.commissionAmount }}</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">￥{{ sumCase.sumReductionAmount }}</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">￥{{ sumCase.sumRepayAmount }}</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">￥{{ sumCase.remainingAmount }}</div>
                  </div>
                </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?.batchCode }}</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?.commissionAmount && row?.discount
                                ? Decimal(row?.commissionAmount).mul(Decimal(row?.discount)).div(Decimal(10))
                                : row?.commissionAmount
                            }}</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 && row?.sumRepayAmount ? Decimal(row?.principalBalance).sub(Decimal(row?.sumRepayAmount)) : row?.principalBalance }}</td>
                            <td class="label">本金余额折扣值</td>
                            <td>{{
                              row?.principalBalance && row?.discount
                                ? Decimal(row?.principalBalance).mul(Decimal(row?.discount)).div(Decimal(10))
                                : row?.principalBalance
                            }}</td>
                          </tr>
                          <tr>
                            <td class="label">手续费</td>
                            <td>{{ row?.commission }}</td>
                            <td class="label">跟进结果</td>
                            <td>{{
                              row?.followStatus
                                ? FollowStatus?.find((v) => v.value === row?.followStatus)?.label
                                : ''
                            }}</td>
                            <td class="label">跟进状态</td>
                            <td>{{
                              row?.phoneResultStatus
                                ? PhoneResultStatus.find((v) => v.value === row?.phoneResultStatus)
                                    ?.label
                                : ''
                            }}</td>
                            <td class="label">案件状态</td>
                            <td>
                              {{
                                row?.caseStatus
                                  ? CaseStatus.find((v) => v.value === row?.caseStatus)?.label
                                  : ''
                              }}</td
                            >
                          </tr>
                          <tr>
                            <td class="label">借款时间</td>
                            <td>{{ row?.credit?.borrowingTime }}</td>
                            <td class="label">诉讼执行状态</td>
                            <td>{{ row?.credit?.litigationStatus }}</td>
                            <td class="label">诉讼案号</td>
                            <td>{{ row?.credit?.litigationCaseNo }}</td>
                            <td class="label">执行案号</td>
                            <td>{{ row?.credit?.executeCaseNo }}</td>
                          </tr>
                          <tr>
                            <td class="label">结案状态</td>
                            <td>{{ row?.credit?.closingStatus }}</td>
                            <td class="label">合同编号</td>
                            <td>{{ row?.credit?.constantNo }}</td>
                            <td class="label">资金方名称</td>
                            <td>{{ row?.credit?.planAmountOrg }}</td>
                            <td class="label">申请金额</td>
                            <td>{{ row?.credit?.planAmount }}</td>
                          </tr>
                          <tr>
                            <td class="label">借款日期</td>
                            <td>{{ row?.credit?.paymentDate }}</td>
                            <td class="label">到期日期</td>
                            <td>{{ row?.credit?.overDate }}</td>
                            <td class="label">期数</td>
                            <td>{{ row?.credit?.period }}</td>
                            <td class="label">最后还款日期</td>
                            <td>{{ row?.credit?.lastPaymentDate }}</td>
                          </tr>
                          <tr>
                            <td class="label">年化利率</td>
                            <td>{{ row?.credit?.yearRate }}</td>
                            <td class="label">订单总应还金额</td>
                            <td>{{ row?.credit?.paymentAmount }}</td>
                            <td class="label">订单总应还利息</td>
                            <td>{{ row?.credit?.interest }}</td>
                            <td class="label">订单总应还其他费用</td>
                            <td>{{ row?.credit?.free }}</td>
                          </tr>
                          <tr>
                            <td class="label">逾期日期</td>
                            <td>{{ row?.credit?.overdue }}</td>
                            <td class="label">逾期天数</td>
                            <td>{{ row?.credit?.overdueDays }}</td>
                            <td class="label">逾期期数</td>
                            <td>{{ row?.credit?.overduePeriod }}</td>
                            <td class="label">已还本金</td>
                            <td>{{ row?.credit?.overBalance }}</td>
                          </tr>
                          <tr>
                            <td class="label">已还利息</td>
                            <td>{{ row?.credit?.overInterest }}</td>
                            <td class="label">已还其他费用</td>
                            <td>{{ row?.credit?.overFree }}</td>
                            <td class="label">备注</td>
                            <td>{{ row?.credit?.remark }}</td>
                            <td class="label">垫付费用</td>
                            <td>{{ row?.credit?.disbursement }}</td>
                          </tr>
                          <tr>
                            <td class="label">当前逾期违约金</td>
                            <td>{{ row?.weiyuejin }}</td>
                            <td class="label">当前逾期罚息</td>
                            <td>{{ row?.faxi }}</td>
                          </tr>
                        </tbody>
                      </table>
                    </div>
                  </div>
                </template>
              </vxe-grid>
            </div>
          </div>
        </vxe-tab-pane>
        <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"
              >
                <template #expand_content="{ row }">
                  <div class="expand-box">
                    <div>案件明细</div>
                    <div class="expand-table">
                      <div v-for="(item, index) in row.reduceRecords" :key="index">
                        <div class="public-header">
                          {{ item?.loan?.caseId }}
                        </div>
                        <table
                          ><tbody>
                            <tr>
                              <td class="label">案件ID</td>
                              <td>{{ item?.loan?.caseId }}</td>
                              <td class="label">借款平台</td>
                              <td>{{ item?.loan?.loanPlatform?.name }}</td>
                              <td class="label">资管公司</td>
                              <td>{{ item?.loan?.manageOrg.orgName }}</td>
                            </tr>
                            <tr>
                              <td class="label">身份证</td>
                              <td>{{ item?.loan?.borrower?.idCard }}</td>
                              <td class="label">手机号</td>
                              <td>{{ item?.loan?.borrower?.phone }}</td>
                              <td class="label">折扣</td>
                              <td>{{ item?.loan?.discount }}</td>
                              <td class="label">委案金额</td>
                              <td>{{ item?.loan?.commissionAmount }}</td>
                            </tr>
                            <tr>
                              <td class="label">累计还款金额</td>
                              <td>{{ item?.loan?.sumRepayAmount }}</td>
                              <td class="label">累计减免金额</td>
                              <td>{{ item?.loan?.sumReductionAmount }}</td>
                              <td class="label">减免金额</td>
                              <td>{{ item?.reduceAmount }}</td>
                              <td class="label">剩余待还金额</td>
                              <td>{{ item?.loan?.remainingAmount }}</td>
                            </tr>
                            <tr>
                              <td class="label">CPE</td>
                              <td>{{ item?.loan?.cpe?.username }}</td>
                              <td class="label">分派CPE日期</td>
                              <td>{{ item?.loan?.cpeDate }}</td>
                              <td class="label">本金余额</td>
                              <td>{{ item?.loan?.principalBalance }}</td>
                              <td class="label">案件状态</td>
                              <td>
                                {{
                                  item?.loan?.caseStatus
                                    ? CaseStatus.find((v) => v.value === item?.loan?.caseStatus)
                                        .label
                                    : ''
                                }}</td
                              >
                            </tr>
                            <tr>
                              <td class="label">手续费</td>
                              <td>{{ item?.loan?.commission }}</td>
                              <td class="label">跟进结果</td>
                              <td>{{
                                item?.loan?.followStatus
                                  ? FollowStatus?.find((v) => v.value === item?.loan?.followStatus)
                                      ?.label
                                  : ''
                              }}</td>
                              <td class="label">跟进状态</td>
                              <td>{{
                                item?.loan?.phoneResultStatus
                                  ? PhoneResultStatus.find(
                                      (v) => v.value === item?.loan?.phoneResultStatus
                                    )?.label
                                  : ''
                              }}</td>
                            </tr>
                          </tbody>
                        </table>
                      </div>
                    </div>
                  </div>
                </template>
              </ProTable>
            </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-3/4 pr-3">
                <ProTable
                  :config="splitConfig"
                  ref="splitRef"
                  :data="splitData"
                  :showPagination="false"
                  :showToolBar="false"
                >
                  <template #expand_content="{ row }">
                    <div class="expand-box">
                      <div class="flex">
                        <div class="w-full pr-2">
                          <div>案件明细</div>
                          <div class="expand-table">
                            <div v-for="(item, index) in row.loans" :key="index">
                              <div class="public-header">
                                {{ item?.caseId }}
                              </div>
                              <table
                                ><tbody>
                                  <tr>
                                    <td class="label">案件ID</td>
                                    <td>{{ item?.caseId }}</td>
                                    <td class="label">借款平台</td>
                                    <td>{{ item?.loanPlatform?.name }}</td>
                                  </tr>
                                  <tr>
                                    <td class="label">资管公司</td>
                                    <td>{{ item?.manageOrg.orgName }}</td>
                                    <td class="label">身份证</td>
                                    <td>{{ item?.borrower?.idCard }}</td>
                                  </tr>
                                  <tr>
                                    <td class="label">手机号</td>
                                    <td>{{ item?.borrower?.phone }}</td>
                                    <td class="label">折扣</td>
                                    <td>{{ item?.discount }}</td>
                                  </tr>
                                  <tr>
                                    <td class="label">累计还款金额</td>
                                    <td>{{ item?.sumRepayAmount }}</td>
                                    <td class="label">累计减免金额</td>
                                    <td>{{ item?.sumReductionAmount }}</td>
                                  </tr>
                                  <tr>
                                    <td class="label">剩余待还金额</td>
                                    <td>{{ item?.remainingAmount }}</td>
                                    <td class="label">CPE</td>
                                    <td>{{ item?.cpe?.username }}</td>
                                  </tr>
                                  <tr>
                                    <td class="label">分派CPE日期</td>
                                    <td>{{ item?.cpeDate }}</td>
                                    <td class="label">本金余额</td>
                                    <td>{{ item?.principalBalance }}</td>
                                  </tr>
                                  <tr>
                                    <td class="label">手续费</td>
                                    <td>{{ item?.commission }}</td>
                                  </tr>
                                  <tr>
                                    <td class="label">委案金额</td>
                                    <td>{{ item?.commissionAmount }}</td>
                                    <td class="label">案件状态</td>
                                    <td>
                                      {{
                                        item?.caseStatus
                                          ? CaseStatus.find((v) => v.value === item?.caseStatus)
                                              .label
                                          : ''
                                      }}</td
                                    >
                                  </tr>
                                  <tr>
                                    <td class="label">跟进结果</td>
                                    <td>{{
                                      item?.followStatus
                                        ? FollowStatus?.find((v) => v.value === item?.followStatus)
                                            ?.label
                                        : ''
                                    }}</td>
                                    <td class="label">跟进状态</td>
                                    <td>{{
                                      item?.phoneResultStatus
                                        ? PhoneResultStatus.find(
                                            (v) => v.value === item?.phoneResultStatus
                                          )?.label
                                        : ''
                                    }}</td>
                                  </tr>
                                </tbody>
                              </table>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </template>
                </ProTable>
              </div>
              <div class="w-1/4">
                <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" />
    <returnModal
      ref="returnModalRef"
      :returnConfig="returnConfig"
      :returnData="returnData"
      @success="query('还款')"
      :mergerCase="detail?.mergerCase"
    />
    <reduceDrawer ref="reduceDrawerRef" @success="query('减免')" :mergerCase="detail?.mergerCase" />
    <splitDrawer ref="splitDrawerRef" @success="query('分期')" :mergerCase="detail?.mergerCase" />
    <callDrawer ref="callDrawerRef" @success="query('跟进')" :mergerCase="detail?.mergerCase" />
    <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, nextTick } from 'vue';
  import { ElButton, ElTag, ElMessage } 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, Phone } from '@element-plus/icons-vue';
  import { saveAudit } from '@/api/audit';
  import Decimal from 'decimal.js';
  import { useDict } from '@/hooks/useDict';
  const { PhoneResultStatus, RepayType, FlowStatus, FollowStatus, AuditStatus, CaseStatus ,Status} =
    useDict(
      'PhoneResultStatus',
      'RepayType',
      'FlowStatus',
      'FollowStatus',
      'AuditStatus',
      'CaseStatus',
      'Status'
    );
  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 splitCurrent = ref({
    flowStatus: '',
    status:''
  });
  const splitCanIndex = ref(0)
  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 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('/sys/static/' + item, {}, name);
  };
  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
                  ? RepayType.value?.find((v) => v.value === row.repayType)?.label
                  : ''}
              </>
            );
          },
        },
      },
      {
        field: 'reduce.id',
        title: '关联减免ID',
        showOverflow: 'tooltip',
      },
      {
        field: 'flowStatus',
        title: '审核状态',
        showOverflow: 'tooltip',
        width: 80,
        fieldNames: { label: 'label', value: 'value' },
        slots: {
          default: ({ row }) => {
            return (
              <>
                {row.flowStatus
                  ? FlowStatus.value?.find((v) => v.value === row.flowStatus)?.label
                  : ''}
              </>
            );
          },
        },
      },
      {
        field: 'stages.id',
        title: '关联分期ID',
        showOverflow: 'tooltip',
      },
      {
        field: 'byStagesRecord.period',
        title: '关联分期期次',
        showOverflow: 'tooltip',
      },
      {
        field: 'repayAmount',
        title: '应还金额',
        showOverflow: 'tooltip',
      },
      {
        field: 'loanPlatform',
        title: '借款平台',
        showOverflow: 'tooltip',
      },
      {
        field: 'status',
        title: '状态',
        showOverflow: 'tooltip',
        width: 80,
        fieldNames: { label: 'label', value: 'value' },
        slots: {
          default: ({ row }) => {
            return (
              <>
                {row.status
                  ? Status.value?.find((v) => v.value === row.status)?.label
                  : ''}
              </>
            );
          },
        },
      },
    ],
    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: 'cpe.username',
        title: 'CPE',
        showOverflow: 'tooltip',
      },
      {
        field: 'followStatus',
        title: '拨打跟进结果',
        showOverflow: 'tooltip',
        slots: {
          default: ({ row }) => {
            return (
              <>
                {row.followStatus
                  ? FollowStatus.value?.find((v) => v.value === row.followStatus)?.label
                  : ''}
              </>
            );
          },
        },
      },
      {
        field: 'phoneResultStatus',
        title: '拨打处置状态',
        showOverflow: 'tooltip',
        slots: {
          default: ({ row }) => {
            return (
              <>
                {row.phoneResultStatus
                  ? PhoneResultStatus.value?.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({
    minHeight: 320,
    height: 320,
    columns: [
      { type: 'seq', width: 60, title: '序号' },
      {
        field: 'name',
        width: 100,
        title: '联系人姓名',
        showOverflow: 'tooltip',
      },
      {
        field: 'kinship',
        width: 110,
        title: '与债权人关系',
        showOverflow: 'tooltip',
      },
      {
        field: 'phone',
        title: '号码',
        showOverflow: 'tooltip',
        slots: {
          default: ({ row }) => {
            return (
              <>
                <div className="flex items-center ">
                  <div className="mr-1">{row.phone}</div>
                  <ElTag type={row.status === 'Y' ? 'primary' : 'danger'}>
                    {row.status === 'Y' ? '有效' : '无效'}
                  </ElTag>
                  <ElButton
                    type="primary"
                    onClick={() => callTelephone(row)}
                    disabled={
                      detail.value &&
                      detail.value.repayStatus &&
                      detail.value.repayStatus === 'over'
                    }
                    v-permission={'case_handle'}
                    icon={Phone}
                    link
                  ></ElButton>
                </div>
              </>
            );
          },
        },
      },
    ],
    toolbarConfig: { enabled: false },
  });
  const returnCrash = (row, type) => {
    if (!recordData.value || recordData.value.length === 0) {
      return ElMessage.warning({
        message: '要先跟进后才可以还款',
        plain: true,
      });
    }
    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 = () => {
    if (!recordData.value || recordData.value.length === 0) {
      return ElMessage.warning({
        message: '要先跟进后才可以申请减免',
        plain: true,
      });
    }
    reduceDrawerRef.value.openModal(
      JSON.parse(JSON.stringify(detail.value)),
      JSON.parse(JSON.stringify(caseDetailConfig.data))
    );
  };
  const split = () => {
    if (!recordData.value || recordData.value.length === 0) {
      return ElMessage.warning({
        message: '要先跟进后才可以申请分期',
        plain: true,
      });
    }
    splitDrawerRef.value.openModal(
      JSON.parse(JSON.stringify(detail.value)),
      JSON.parse(JSON.stringify(caseDetailConfig.data))
    );
  };
  const caseDetailConfig = reactive({
    rowConfig: {
      height: 40,
    },
    cellConfig: {
      height: 40,
    },
    columns: [
      { type: 'expand', width: 80, slots: { content: 'expand_content' } },
      {
        field: 'caseId',
        width: 230,
        slots: {
          default: ({ row, rowIndex }) => {
            return (
              <>
                <div className="inline-block">{row.caseId}</div>
                <Tag row={row} />
              </>
            );
          },
        },
        title: '案件ID',
        showOverflow: 'tooltip',
      },
      {
        field: 'loanPlatform.name',
        title: '借款平台',
        showOverflow: 'tooltip',
      },
      {
        field: 'commissionAmount',
        title: '委案金额',
        showOverflow: 'tooltip',
      },
      {
        field: 'sumReductionAmount',
        title: '累计减免金额',
        showOverflow: 'tooltip',
      },
      {
        field: 'sumRepayAmount',
        title: '累计还款金额',
        showOverflow: 'tooltip',
      },
      {
        field: 'repayStatus',
        title: '还款状态',
        showOverflow: 'tooltip',
        width: 80,
        slots: {
          default: ({ row }) => {
            return <div>{row.repayStatus == 'over' ? '已还款' : '待还款'}</div>;
          },
        },
      },
      {
        field: 'remainingAmount',
        title: '剩余待还金额',
        showOverflow: 'tooltip',
      },
      {
        field: 'code',
        fixed: 'right',
        title: '操作',
        slots: {
          default: ({ row, rowIndex }) => {
            return (
              <>
                <ElButton
                  type="primary"
                  onClick={() => returnCrash(row, '直接还款')}
                  v-permission={'case_handle'}
                  disabled={row.repayStatus == 'over'}
                >
                  还款
                </ElButton>
              </>
            );
          },
        },
      },
    ],
    data: [],
    toolbarConfig: { enabled: false },
  });
  const onCellClick = ({ row, rowIndex }) => {
    splitDeData.value = row.byStagesRecords;
    splitCanIndex.value = row.byStagesRecords.findIndex(v => v.repayStatus == 'pending')
    console.log('splitCanIndexsplitCanIndex', splitCanIndex.value)
    splitCurrent.value = row;
    console.log('splitCurrent', splitCurrent);
  };
  const add = (a, b) => {
    return (parseFloat(a) + parseFloat(b)).toFixed(2);
  };

  const splitConfig = reactive({
    columns: [
      { type: 'expand', width: 40, slots: { content: 'expand_content' } },
      {
        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: 70,
      },
      {
        field: 'applyTime',
        title: '分期申请时间',
        showOverflow: 'tooltip',
        width: 100,
      },
      {
        field: 'effectiveTime',
        title: '分期生效时间',
        showOverflow: 'tooltip',
        width: 100,
      },
      {
        field: 'totalPeriod',
        showOverflow: 'tooltip',
        title: '还款期数',
        width: 80,
      },
      {
        field: 'firstApplyDate',
        title: '首期还款日',
        showOverflow: 'tooltip',
        width: 100,
      },
      {
        field: 'flowStatus',
        title: '审核状态',
        showOverflow: 'tooltip',
        width: 80,
        fieldNames: { label: 'label', value: 'value' },
        slots: {
          default: ({ row }) => {
            return (
              <>
                {row.flowStatus
                  ? FlowStatus.value?.find((v) => v.value === row.flowStatus)?.label
                  : ''}
              </>
            );
          },
        },
      },

      {
        field: 'status',
        title: '状态',
        showOverflow: 'tooltip',
        width: 80,
        fieldNames: { label: 'label', value: 'value' },
        slots: {
          default: ({ row }) => {
            return (
              <>
                {row.status
                  ? Status.value?.find((v) => v.value === row.status)?.label
                  : ''}
              </>
            );
          },
        },
      },

      {
        field: 'remainingAmount',
        title: '剩余待还金额',
        showOverflow: 'tooltip',
        width: 110,
      },
      {
        field: 'code',
        title: '附件',
        width: 55,
        slots: {
          default: ({ row, rowIndex }) => {
            if (row.images && row.images.length > 0) {
              return (
                <>
                  {row.images.map((item, index) => (
                    <el-icon>
                      <Download onClick={() => download(item)} />
                    </el-icon>
                  ))}
                </>
              );
            }
          },
        },
      },
    ],
    onCellClick: onCellClick,
    toolbarConfig: { enabled: false },
  });

  const splitDeConfig = reactive({
    columns: [
      {
        field: 'period',
        title: '期次',
        width: 48,
        showOverflow: 'tooltip',
      },
      {
        field: 'playApplyDate',
        title: '到期日',
        showOverflow: 'tooltip',
      },
      {
        field: 'repayStatus',
        title: '状态',
        width: 60,
        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' ||
                    splitCurrent.value.status ==='disable' ||
                    splitCurrent.value.flowStatus !== 'pass' ||
                    rowIndex !== splitCanIndex.value ||
                    (detail.value.repayStatus && detail.value.repayStatus === 'over')
                  }
                  v-permission={'case_handle'}
                >
                  还款
                </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: [
      { type: 'expand', width: 40, slots: { content: 'expand_content' } },
      {
        field: 'caseId',
        title: '案件ID',
        showOverflow: 'tooltip',
        slots: {
          default: ({ row }) => {
            return (
              <>{Array.from(new Set(row.reduceRecords.map((v) => v.loan.caseId))).join(',')}</>
            );
          },
        },
      },
      {
        field: 'remainingAmount',
        title: '剩余待还金额',
        showOverflow: 'tooltip',
      },
      {
        field: 'totalReduceAmount',
        title: '减免金额',
        width: 110,
        showOverflow: 'tooltip',
      },
      {
        title: '应还金额',
        width: 110,
        slots: {
          default: ({ row }) => {
            return (
              <>{Decimal(row.remainingAmount).sub(row.totalReduceAmount)}</>
            );
          },
        },
        showOverflow: 'tooltip',
      },
      {
        field: 'totalNumber',
        title: '减免案件数',
        showOverflow: 'tooltip',
      },
      
      {
        field: 'totalPayAmount',
        title: '累计还款金额',
        showOverflow: 'tooltip',
      },
      {
        field: 'id',
        showOverflow: 'tooltip',
        title: '减免申请ID',
      },
      {
        field: 'inEffectDate',
        showOverflow: 'tooltip',
        title: '减免截止时间',
      },
      {
        field: 'flowStatus',
        title: '审核状态',
        showOverflow: 'tooltip',
        width: 80,
        fieldNames: { label: 'label', value: 'value' },
        slots: {
          default: ({ row }) => {
            return (
              <>
                {row.flowStatus
                  ? FlowStatus.value?.find((v) => v.value === row.flowStatus)?.label
                  : ''}
              </>
            );
          },
        },
      },
      {
        field: 'inEffectDate',
        showOverflow: 'tooltip',
        title: '减免生效时间',
      },

      {
        field: 'status',
        showOverflow: 'tooltip',
        title: '状态',
        fieldNames: { label: 'label', value: 'value' },
        slots: {
          default: ({ row }) => {
            return (
              <>
                {row.status
                  ? Status.value?.find((v) => v.value === row.status)?.label
                  : ''}
              </>
            );
          },
        },
      },

      {
        field: 'code',
        title: '附件',
        width: 60,
        slots: {
          default: ({ row, rowIndex }) => {
            if (row.images && row.images.length > 0) {
              return (
                <>
                  {row.images.map((item, index) => (
                    <el-icon>
                      <Download onClick={() => download(item)} />
                    </el-icon>
                  ))}
                </>
              );
            }
          },
        },
      },
      {
        field: 'code',
        title: '操作',
        fixed: 'right',
        slots: {
          default: ({ row, rowIndex }) => {
            return (
              <>
                <ElButton
                  type="primary"
                  onClick={() => returnCrash(row, '结清减免还款')}
                  disabled={
                    row.status === 'disable' ||
                    row.repayStatus === 'over'  ||
                    row.flowStatus !== 'pass'  ||
                    (detail.value.repayStatus && detail.value.repayStatus === 'over')
                  }
                  v-permission={'case_handle'}
                >
                  还款
                </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 === '跟进') {
        getGuarantorsList(detail.value?.borrower?.id);
        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;
            if (res.result.length === 1) {
              foldCaseTree();
            }
          }
        });
      }
    }
  };
  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;
          if (res.result.length === 1) {
            nextTick(() => {
              foldCaseTree();
            });
          }
        }
      });
      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;
      color: #606268;
      line-height: 11px;
      width: 240px;
      height: 40px;
      padding-left: 5px;
      font-size: 13px;
      &.label {
        width: 150px;
        text-align: center;
        background: #f6f8ff;
        color: #909399;
      }
    }
  }

  .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;
        color: #606268;
        width: 240px;
        line-height: 11px;
        height: 40px;
        font-size: 14px;
        padding-left: 5px;
        &.label {
          text-align: center;
          background: #f6f8ff;
          color: #909399;
        }
      }
    }
  }
</style>
