<template>
  <div class="table-box">
    <div class="table-inner">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane :label="item" :name="item" v-for="(item, index) in tabs" :key="index">
          <template #label>
            <div>
              {{ item }}
            </div>
          </template>
        </el-tab-pane>
      </el-tabs>
      <ProTable
        :config="config"
        v-if="tableTrue"
        ref="caseLRef"
        :api="getCreditPage"
        :paramCallback="paramCallback"
        :selectdList="selectdList"
      >
        <template #table_top>
          <div class="style-lable" style="width: 100%">
            <div class="item_warp" style="width: 23%">
              <div class="img_warp">
                <img src="@/assets/images/caselist.svg" />
              </div>
              <div class="title_warp">
                <div class="items">案件数量</div>
                <div class="item items1">{{ statisis.caseNum }}</div>
              </div>
            </div>
            <div class="item_warp" style="width: 23%">
              <div class="img_warp">
                <img src="@/assets/images/userlist.svg" />
              </div>
              <div class="title_warp">
                <div class="items">案人人数</div>
                <div class="item items1">{{ statisis.cpeNum }}</div>
              </div>
            </div>
            <div class="item_warp" style="width: 23%">
              <div class="img_warp">
                <img src="@/assets/images/money.svg" />
              </div>
              <div class="title_warp">
                <div class="items">委案金额</div>
                <div class="item items1">￥{{ statisis.amount }}</div>
              </div>
            </div>
            <div class="item_warp" style="width: 23%">
              <div class="img_warp">
                <img src="@/assets/images/tocrash.svg" />
              </div>
              <div class="title_warp">
                <div class="items">待还金额</div>
                <div class="item items1">￥{{ statisis.unAmount }}</div>
              </div>
            </div>
          </div>
        </template>
        <template #left_buttons>
          <div class="flex rounded w-full h-11 items-center pl-2 btn-grp mb-1">
            <el-dropdown @command="(command) => (dataValue = command)">
              <span class="el-dropdown-link">
                {{ dataValue }}
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-for="item in dataOptions"
                    :key="item.value"
                    :command="item.value"
                    >{{ item.label }}</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-dropdown>
              <el-button type="primary" @click="addTag">
                <el-icon class="el-icon--left"><arrow-down /></el-icon>添加临时标签
              </el-button>
              <template #dropdown>
                <el-dropdown-menu @click="handleClick1">
                  <el-dropdown-item>导入批量添加标签</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <!-- <el-button type="primary" @click="delTag" style="margin-left: 10px">删除临时标签</el-button> -->
            <el-button type="primary" style="margin-left: 10px" @click="stayCase">留案 </el-button>
          </div>
        </template>
      </ProTable>
    </div>
    <tagModal ref="tagModalRef" @success="query"/>
  </div>
</template>

<script setup name="case-manage" lang="jsx">
  import tagModal from './components/tagModal.vue';
  import { useRouter } from 'vue-router';


  import { computed, reactive, ref, nextTick } from 'vue';
  import { getCreditPage, getCreditTotal } from '@/api/property';
  import { VxeTextEllipsis, VxeTooltip } from 'vxe-pc-ui';
  import { ElMessageBox, ElMessage } from 'element-plus';
  const caseLRef = ref();
  import dayjs from 'dayjs';
  import citydata from '../../../assets/citydata';
  import { stayLoan } from '@/api/allcation';
  import { onMounted } from 'vue';
  import { useUserStore } from '@/stores/modules/user';
  import { getPlatformPage } from '@/api/platform';
  import { getManageOrgPage } from '@/api/manageOrg';
  import { useDict } from '@/hooks/useDict';
  import { idCardEncipher } from '@/utils/jiaoyan'

  const {
    PhoneResultStatus,
    ReduceType,
    FlowStatus,
    BooleanStatus,
    RepairStatus,
    FollowStatus,
    AuditStatus,
    CaseStatus,
  } = useDict(
    'PhoneResultStatus',
    'ReduceType',
    'FlowStatus',
    'BooleanStatus',
    'RepairStatus',
    'FollowStatus',
    'AuditStatus',
    'CaseStatus'
  );
  const tagModalRef = ref();
  const { userInfo } = useUserStore();
  const router = useRouter();
  const tabs = ref(['全部', '今天待跟进', '明天待跟进', '后天待跟进']);
  const activeName = ref('全部');
  const addTag = () => {
    if (dataValue.value === '对选中项操作' && (!selectdList.value || !selectdList.value.length)) {
      return ElMessage.warning({
        message: '请先选择操作对象!',
        plain: true,
      });
    }
    if (dataValue.value === '对选中项操作') {
      tagModalRef.value?.openModal('add', JSON.parse(JSON.stringify(curParam.value)),
        JSON.parse(JSON.stringify(selectdList.value)))
    } else {
      tagModalRef.value?.openModal('add', JSON.parse(JSON.stringify(curParam.value)),
        [])
    }
    
  }
  const handleClick1 = () => {
    if (dataValue.value === '对选中项操作' && (!selectdList.value || !selectdList.value.length)) {
      return ElMessage.warning({
        message: '请先选择操作对象!',
        plain: true,
      });
    }
    if (dataValue.value === '对选中项操作') {
      tagModalRef.value?.openModal('import', JSON.parse(JSON.stringify(curParam.value)),
        JSON.parse(JSON.stringify(selectdList.value)))
    } else {
      tagModalRef.value?.openModal('import', JSON.parse(JSON.stringify(curParam.value)),
        [])
    }
  }
  const delTag = () => {
    tagModalRef.value?.openModal('del')
  }
  const selectdList = ref([]);
  const tableTrue = ref(true);
  const curParam = ref({});
  const statisis = ref({});
  const dataValue = ref('对查询结果操作');
  const dataOptions = [
    {
      label: '对查询结果操作',
      value: '对查询结果操作',
    },
    {
      label: '对选中项操作',
      value: '对选中项操作',
    },
  ];
  const getStatisis = (params) => {
    getCreditTotal(params).then((res) => {
      if (res.success) {
        statisis.value = res.result;
      }
    });
  };
  const onCheckboxChange = (row) => {
    selectdList.value = row.records;
    dataValue.value = selectdList.value.length > 0 ? '对选中项操作' : '对查询结果操作';
  };
  const onCheckboxAll = (flag) => {
    if (flag.checked) {
      selectdList.value = flag.records;
    } else {
      selectdList.value = [];
    }
    dataValue.value = selectdList.value.length > 0 ? '对选中项操作' : '对查询结果操作';
  };
  const onCellClick = (row) => {
    router.push({
      path: '/property/case-detail',
      query: { id: row.id }, //这里不能直接写成 query: JSON.stringify(item)
    });
  };
  const paramCallback = (param) => {
    const obj = JSON.parse(JSON.stringify(param));
    if (userInfo.id) {
      obj['cpe'] = userInfo.id;
    }
    if (obj.arealist && obj.arealist.length > 0) {
      obj['domicileProvince'] = obj.arealist[0];
      obj['domicileCity'] = obj.arealist.length > 1 ? obj.arealist[1] : null;
      obj['area'] = obj.arealist.length > 2 ? obj.arealist[2] : null;
      delete obj['arealist'];
    }
    if (obj['trackTime']) {
      if (obj['trackTime'][0]) obj['trackTimeBegin'] = obj['trackTime'][0];
      if (obj['trackTime'][1]) obj['trackTimeEnd'] = obj['trackTime'][1];
      delete obj['trackTime'];
    }
    if (obj['cpeDate']) {
      if (obj['cpeDate'][0]) obj['cpeDateBegin'] = obj['cpeDate'][0];
      if (obj['cpeDate'][1]) obj['cpeDateEnd'] = obj['cpeDate'][1];
      delete obj['cpeDate'];
    }
    if (activeName.value === '今天待跟进') {
      obj['nextTimeBegin'] = dayjs().format('YYYY-MM-DD 00:00:00');
      obj['nextTimeEnd'] = dayjs().format('YYYY-MM-DD 23:59:59');
    } else if (activeName.value === '明天待跟进') {
      obj['nextTimeBegin'] = dayjs().add(1, 'day').format('YYYY-MM-DD 00:00:00');
      obj['nextTimeEnd'] = dayjs().add(1, 'day').format('YYYY-MM-DD 23:59:59');
    } else if (activeName.value === '后天待跟进') {
      obj['nextTimeBegin'] = dayjs().add(2, 'day').format('YYYY-MM-DD 00:00:00');
      obj['nextTimeEnd'] = dayjs().add(2, 'day').format('YYYY-MM-DD 23:59:59');
    }
    curParam.value = obj;
    getStatisis(obj);
    return obj;
  };
  const stayCase = async () => {
    if (dataValue.value === '对选中项操作' && (!selectdList.value || !selectdList.value.length)) {
      return ElMessage.warning({
        message: '请先选择操作对象!',
        plain: true,
      });
    }
    await ElMessageBox.confirm('是否确认留案?', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    });

    const ids = selectdList.value.map((v) => v.id).join(',');
    let param = {};
    if (dataValue.value === '对选中项操作') {
      param['loanIds'] = ids;
    } else {
      param = { ...curParam.value };
    }
    await stayLoan(param);

    ElMessage({
      type: 'success',
      message: '留案成功！',
      plain: true,
    });
    query();
  };
  const config = computed( () => {
    return {
      maxHeight: 800,
      columns: [
        { type: 'checkbox', title: '', width: 60, fixed: 'left' },
        {
          field: 'caseId',
          title: '案件ID',
          search: { el: 'input', labelWidth: 90 },
          showOverflow: 'tooltip',
          width: 230,
          slots: {
            default: ({ row, rowIndex }) => {
              return (
                <>
                  <div
                    onClick={() => onCellClick(row)}
                    className=" text-blue-400 underline cursor-pointer inline-block"
                  >
                    {row.caseId}
                  </div>
                  <Tag row={row} />
                </>
              );
            },
          },
        },
        {
        field: 'arealist',
        enum: citydata,
        title: '所属区域',
        showOverflow: 'tooltip',
        width: 100,
        fieldNames: { label: 'name', value: 'name' },
        search: {
          el: 'cascader',
          props: { clearable: true, checkStrictly: true },
          labelWidth: 90,
        },
        slots: {
          default: ({ row }) => {
            return (
              <VxeTooltip
                content={
                  row.borrower.domicileProvince +
                  (row.borrower.domicileCity ? '-' + row.borrower.domicileCity : '') +
                  (row.borrower.area ? '-' + row.borrower.area : '')
                }
              >
                <VxeTextEllipsis
                  content={
                    row.borrower.domicileProvince +
                    (row.borrower.domicileCity ? '-' + row.borrower.domicileCity : '') +
                    (row.borrower.area ? '-' + row.borrower.area : '')
                  }
                ></VxeTextEllipsis>
              </VxeTooltip>
            );
          },
        },
      },
        {
          field: 'loanPlatform.name',
          showOverflow: 'tooltip',
          enum: () => getPlatformPage({ current: 1, size: 999999999, status: 'enable' }),
          search: { el: 'select', props: { filterable: true,clearable: true }, key: 'loanPlatform', labelWidth: 90 },
          fieldNames: { label: 'name', value: 'id' },
          title: '借款平台',
          width: 100,
        },
        {
          field: 'manageOrg.orgName',
          title: '资管公司',
          enum: () => getManageOrgPage({ current: 1, size: 999999999, status: 'enable' }),
          fieldNames: { label: 'orgName', value: 'id' },
          showOverflow: 'tooltip',
          width: 100,
          search: { el: 'select', props: { filterable: true,clearable: true }, key: 'manageOrg', labelWidth: 90 },
        },
        {
          field: 'batchCode',
          title: '批次号',
          showOverflow: 'tooltip',
          width: 120,
          search: {
            el: 'input',
            key: 'batchCode',
            props: { clearable: true },
            labelWidth: 90,
          },
        },
        {
          field: 'borrower.name',
          title: '借款人姓名',
          showOverflow: 'tooltip',
          width: 120,
          search: {
            el: 'input',
            key: 'borrowerName',
            props: { clearable: true },
            labelWidth: 90,
          },
        },
        {
          field: 'borrower.idCard',
          title: '身份证',
          slots: {
            default: ({ row }) => {
              return (
                <>
                  {idCardEncipher(row.borrower.idCard)}
                </>
              );
            },
          },
          showOverflow: 'tooltip',
          width: 140,
          search: {
            el: 'input',
            props: { clearable: true },
            key: 'borrowerIdCard',
            labelWidth: 90,
          },
        },
        {
          field: 'borrower.phone',
          title: '手机号',
          showOverflow: 'tooltip',
          width: 140,
          search: {
            el: 'input',
            props: { clearable: true },
            key: 'borrowerPhone',
            labelWidth: 90,
          },
        },
        {
          field: 'tag',
          title: '临时标签',
          showOverflow: 'tooltip',
          width: 140,
          search: {
            el: 'input',
            props: { clearable: true },
            key: 'queryTag',
            labelWidth: 90,
          },
        },
        {
          field: 'discount',
          title: '折扣',
          showOverflow: 'tooltip',
          width: 80,
        },
        {
          field: 'weiyuejin',
          title: '当前逾期违约金',
          showOverflow: 'tooltip',
          width: 80,
        },
        {
          field: 'faxi',
          title: '当前逾期罚息',
          showOverflow: 'tooltip',
          width: 80,
        },
        {
          field: 'commissionAmount',
          title: '委案金额',
          sortable: true,
          showOverflow: 'tooltip',
          width: 120,
          search: {
            render: ({ searchParam }) => {
              return (
                <div class="flex">
                  <el-input vModel_trim={searchParam.commissionAmountBegin} placeholder="" />
                  <span class="mr-1 ml-1">-</span>
                  <el-input vModel_trim={searchParam.commissionAmountEnd} placeholder="" />
                </div>
              );
            },
            props: { clearable: true },
            labelWidth: 90,
          },
        },
        {
          field: 'sumRepayAmount',
          title: '累计还款金额',
          showOverflow: 'tooltip',
          width: 100,
          search: { el: 'input', props: { clearable: true }, labelWidth: 90 },
        },
        {
          field: 'sumReductionAmount',
          title: '累计减免金额',
          showOverflow: 'tooltip',
          width: 100,
          search: { el: 'input', props: { clearable: true }, labelWidth: 90 },
        },
        {
          field: 'remainingAmount',
          title: '剩余待还金额',
          showOverflow: 'tooltip',
          width: 100,
          search: { el: 'input', props: { clearable: true }, labelWidth: 90 },
        },
        {
          field: 'cpe.username',
          showOverflow: 'tooltip',
          title: 'CPE',
          width: 80,
          search: { el: 'input', props: { clearable: true }, key: 'cpeName', labelWidth: 90 },
        },
        {
          field: 'cpeDate',
          title: '分派CPE日期',
          showOverflow: 'tooltip',
          width: 150,
          search: {
            el: 'date-picker',
            props: { type: 'daterange', valueFormat: 'YYYY-MM-DD' },
            labelWidth: 90,
          },
        },
        {
          field: 'trackTime',
          title: '跟进时间',
          showOverflow: 'tooltip',
          width: 150,
          search: {
            el: 'date-picker',
            props: { type: 'datetimerange', valueFormat: 'YYYY-MM-DD HH:mm:ss' },
            labelWidth: 90,
          },
        },
        {
          field: 'isfollowStatus',
          showOverflow: 'tooltip',
          title: '是否有跟进记录',
          width: 80,
          enum: BooleanStatus,
          search: activeName.value === '全部' ? { el: 'select', props: { filterable: true,clearable: true }, labelWidth: 90, defaultValue:  'N' } : null,
          fieldNames: { label: 'label', value: 'value' },
          slots: {
            default: ({ row }) => {
              return (
                <>
                  {row.isfollowStatus
                    ? BooleanStatus.value?.find((v) => v.value === row.isfollowStatus)?.label
                    : ''}
                </>
              );
            },
          },
        },
        {
          field: 'repairStatus',
          showOverflow: 'tooltip',
          title: '修复状态',
          width: 80,
          enum: RepairStatus,
          search: { el: 'select', props: { filterable: true,clearable: true }, labelWidth: 90 },
          fieldNames: { label: 'label', value: 'value' },
          slots: {
            default: ({ row }) => {
              return (
                <>
                  {row.repairStatus
                    ? RepairStatus.value?.find((v) => v.value === row.repairStatus)?.label
                    : ''}
                </>
              );
            },
          },
        },
        {
          field: 'principalBalance',
          title: '本金余额',
          showOverflow: 'tooltip',
          width: 80,
          search: { el: 'input', props: { clearable: true }, labelWidth: 90 },
        },
        {
          field: 'commission',
          showOverflow: 'tooltip',
          title: '手续费',
          width: 80,
          search: { el: 'input', props: { clearable: true }, labelWidth: 90 },
        },
        {
          field: 'followStatus',
          showOverflow: 'tooltip',
          title: '跟进结果',
          width: 80,
          enum: FollowStatus,
          search: { el: 'select', props: { filterable: true,clearable: true }, labelWidth: 90 },
          fieldNames: { label: 'label', value: 'value' },
          slots: {
            default: ({ row }) => {
              return (
                <>
                  {row.followStatus
                    ? FollowStatus.value?.find((v) => v.value === row.followStatus)?.label
                    : ''}
                </>
              );
            },
          },
        },
        {
          field: 'phoneResultStatus',
          showOverflow: 'tooltip',
          title: '跟进状态',
          width: 80,
          enum: PhoneResultStatus,
          search: { el: 'select', props: { filterable: true,clearable: true }, labelWidth: 90 },
          fieldNames: { label: 'label', value: 'value' },
          slots: {
            default: ({ row }) => {
              return (
                <>
                  {row.phoneResultStatus
                    ? PhoneResultStatus.value?.find((v) => v.value === row.phoneResultStatus)?.label
                    : ''}
                </>
              );
            },
          },
        },
        {
          field: 'lastFollowStatus',
          showOverflow: 'tooltip',
          title: '最近一次跟进结果',
          width: 80,
          enum: FollowStatus,
          search: { el: 'select', props: { filterable: true,clearable: true }, labelWidth: 90 },
          fieldNames: { label: 'label', value: 'value' },
          slots: {
            default: ({ row }) => {
              return (
                <>
                  {row.lastFollowStatus
                    ? FollowStatus.value?.find((v) => v.value === row.lastFollowStatus)?.label
                    : ''}
                </>
              );
            },
          },
        },
        {
          field: 'lastPhoneResultStatus',
          showOverflow: 'tooltip',
          title: '最近一次跟进状态',
          width: 80,
          enum: PhoneResultStatus,
          search: { el: 'select', props: { filterable: true,clearable: true }, labelWidth: 90 },
          fieldNames: { label: 'label', value: 'value' },
          slots: {
            default: ({ row }) => {
              return (
                <>
                  {row.lastPhoneResultStatus
                    ? PhoneResultStatus.value?.find((v) => v.value === row.lastPhoneResultStatus)
                        ?.label
                    : ''}
                </>
              );
            },
          },
        },
        {
          field: 'caseStatus',
          showOverflow: 'tooltip',
          title: '案件状态',
          width: 80,
          enum: CaseStatus,
          search: { el: 'select', props: { filterable: true,clearable: true }, labelWidth: 90 },
          fieldNames: { label: 'label', value: 'value' },
          slots: {
            default: ({ row }) => {
              return (
                <>
                  {row.caseStatus
                    ? CaseStatus.value?.find((v) => v.value === row.caseStatus)?.label
                    : ''}
                </>
              );
            },
          },
        },
        {
          field: 'credit.borrowingTime',
          title: '借款时间',
          showOverflow: 'tooltip',
          width: 80,
        },
        {
          field: 'credit.litigationStatus',
          title: '诉讼执行状态',
          showOverflow: 'tooltip',
          width: 80,
        },
        {
          field: 'credit.litigationCaseNo',
          title: '诉讼案号',
          showOverflow: 'tooltip',
          width: 80,
        },
        {
          field: 'credit.executeCaseNo',
          title: '执行案号',
          showOverflow: 'tooltip',
          width: 80,
        },
        {
          field: 'credit.closingStatus',
          title: '结案状态',
          showOverflow: 'tooltip',
          width: 80,
        },
        {
          field: 'credit.constantNo',
          title: '合同编号',
          showOverflow: 'tooltip',
          width: 80,
        },
        {
          field: 'credit.planAmountOrg',
          title: '资金方名称',
          showOverflow: 'tooltip',
          width: 80,
        },
        {
          field: 'credit.planAmount',
          title: '申请金额',
          showOverflow: 'tooltip',
          width: 80,
        },
        {
          field: 'credit.paymentDate',
          title: '借款日期',
          showOverflow: 'tooltip',
          width: 80,
        },
        {
          field: 'credit.overDate',
          title: '到期日期',
          showOverflow: 'tooltip',
          width: 80,
        },
        {
          field: 'credit.period',
          title: '期数',
          showOverflow: 'tooltip',
          width: 80,
        },
        {
          field: 'credit.lastPaymentDate',
          title: '最后还款日期',
          showOverflow: 'tooltip',
          width: 80,
        },
        {
          field: 'credit.yearRate',
          title: '年化利率',
          showOverflow: 'tooltip',
          width: 80,
        },
        {
          field: 'credit.paymentAmount',
          title: '订单总应还金额',
          showOverflow: 'tooltip',
          width: 80,
        },
        {
          field: 'credit.interest',
          title: '订单总应还利息',
          showOverflow: 'tooltip',
          width: 80,
        },
        {
          field: 'credit.free',
          title: '订单总应还其他费用',
          showOverflow: 'tooltip',
          width: 80,
        },
        {
          field: 'credit.overdue',
          title: '逾期日期',
          showOverflow: 'tooltip',
          width: 80,
        },
        {
          field: 'credit.overdueDays',
          title: '逾期天数',
          showOverflow: 'tooltip',
          width: 80,
        },
        {
          field: 'credit.overduePeriod',
          title: '逾期期数',
          showOverflow: 'tooltip',
          width: 80,
        },
        {
          field: 'credit.overBalance',
          title: '已还本金',
          showOverflow: 'tooltip',
          width: 80,
        },
        {
          field: 'credit.overInterest',
          title: '已还利息',
          showOverflow: 'tooltip',
          width: 80,
        },
        {
          field: 'credit.overFree',
          title: '已还其他费用',
          showOverflow: 'tooltip',
          width: 80,
        },
        {
          field: 'credit.remark',
          title: '备注',
          showOverflow: 'tooltip',
          width: 80,
        },
        {
          field: 'credit.disbursement',
          title: '垫付费用',
          showOverflow: 'tooltip',
          width: 80,
        },
      ],
      onCheckboxChange: onCheckboxChange,
      onCheckboxAll: onCheckboxAll,
    }
  });

  const query = () => caseLRef.value?.search();
  const handleClick = () => {
    tableTrue.value = false
    nextTick(() => {tableTrue.value = true})
    setTimeout(() => {
        query();
    }, 300);
  };
  onMounted(() => {
    query();
  });
</script>
<style lang="scss" scoped>
  .table-inner {
    width: 100%;
    background: #fff;
    :deep(.topgrp) {
      display: flex;
      margin-bottom: 8px;
      .topbox {
        margin-right: 10px;
        background: rgba(0, 0, 0, 0.02);
        border-radius: 16px;
        width: 146px;
        height: 97px;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 24px;
        p:nth-child(1) {
          font-size: 14px;
          color: rgba(0, 0, 0, 0.45);
        }
      }
    }
  }
</style>
