<template>
  <div class="table-box">
    <div class=" bg-white pt-2 pl-2">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick" v-if="roleType !== 'view'">
        <el-tab-pane
            :label="item.label"
            :name="item.value"
            v-for="(item, index) in tabs"
            :key="index"
          >
          <template #label>
            <div>
              {{item.label}}
            <span style="font-size: 20px; font-weight: bold;">{{item.msg}}</span>
            </div>
          </template>
        </el-tab-pane>
      </el-tabs>
    </div>
    <ProTable ref="proTable" :config="config" :api="func" :paramCallback="paramCallback">
    </ProTable>
  </div>
</template>

<script setup lang="jsx" name="platformManage">
  import { ref, reactive, onMounted, computed } from 'vue';
  import { Plus, Delete, Edit, Setting } from '@element-plus/icons-vue';
  import { getcustomerReportPage, getriskPage, getlegalPage, riskFlowStatusTotal, legalFlowStatusTotal } from '@/api/customer';
  import { ElMessageBox, ElMessage, ElButton, ElTag } from 'element-plus';
  import { useRouter } from 'vue-router';
  import { useRoute } from 'vue-router';

  const tabs = ref([]);
  import { useDict } from '@/hooks/useDict';
  const { PhoneResultStatus, ReduceType, FlowStatus, FollowStatus, AuditStatus, CaseStatus } = useDict("PhoneResultStatus","ReduceType", "FlowStatus", "FollowStatus","AuditStatus", "CaseStatus");
  const route = useRoute();

  const proTable = ref(null);
  const paramObj = ref();
  const selectdList = ref([]);
  const onCheckboxChange = (row) => {
    selectdList.value = row.records;
  };
  const roleType = computed(() => {
    if (route.fullPath.includes('infoGather/dangerReport')) {
        return 'view'
    } else if (route.fullPath.includes('/business-approval/riskManager')) {
        return 'risk'
    }else if (route.fullPath.includes('/business-approval/legalManager')) {
        return 'legal'
    }
  });
  const router = useRouter();
  const func = () => {
    if (route.fullPath.includes('infoGather/dangerReport')) {
      return getcustomerReportPage(paramObj.value)
    } else if (route.fullPath.includes('/business-approval/riskManager')) {
      return getriskPage(paramObj.value)
    } else if (route.fullPath.includes('/business-approval/legalManager')) {
      return getlegalPage(paramObj.value)
    }
  }
  const activeName = ref('pending');
  const paramCallback = (param) => {
    const obj = JSON.parse(JSON.stringify(param));
    if (obj['createTime']) {
      if (obj['createTime'][0]) obj['createTimeBegin'] = obj['createTime'][0];
      if (obj['createTime'][1]) obj['createTimeEnd'] = obj['createTime'][1];
      delete obj['createTime'];
    }
    if (roleType.value === 'risk') {
      obj['riskControlStatus'] = activeName.value;
    } else if (roleType.value === 'legal') {
      obj['legalAffairStatus'] = activeName.value;
    }
    if (roleType.value === 'risk' || roleType.value === 'legal') {
      let totalFunc = roleType.value === 'risk' ? riskFlowStatusTotal : legalFlowStatusTotal
      setTimeout(() => {
        const arr = JSON.parse(JSON.stringify(FlowStatus.value))
        totalFunc({...obj, riskControlStatus: null, legalAffairStatus: null}).then(res => {
          if (res.success) {
            arr.forEach(item => {
              const tt = res.result.find(v => v.flowStatus === item.value)
              if (tt) {
                item['msg'] = tt.number
              } else {
                item['msg'] = 0
              }
            })
            tabs.value = arr
          } else {
            tabs.value = arr
          }
        }).catch(e => {
          tabs.value = arr
        })
      }, (FlowStatus.value && FlowStatus.value.length) ? 100 : 1000)
    }
    paramObj.value = obj
    return obj;
  };
  const onCheckboxAll = (flag) => {
    if (flag.checked) {
      selectdList.value = flag.records;
    } else {
      selectdList.value = [];
    }
  };
  const pushCustomer = (row) => {
    router.push({
      path: '/infoGather/dangerReport/dangerReportDetail',
      query: row ? { id: row.id }: {}, //这里不能直接写成 query: JSON.stringify(item)
    });
  };
  const onCellClick = ({ row, rowIndex }) => {
    if (route.fullPath.includes('infoGather/dangerReport')) {
      router.push({
        name: 'dangerReportDetail',
        query: row ? { id: row.id }: {}
      });
    } else if (route.fullPath.includes('/business-approval/riskManager')) {
      router.push({
        name: 'riskReportDetail',
        query: row ? { id: row.id }: {}
      });
    } else if (route.fullPath.includes('/business-approval/legalManager')) {
      router.push({
        name: 'legalReportDetail',
        query: row ? { id: row.id }: {}
      });
    }
  }
  const config = reactive({
    onCheckboxChange: onCheckboxChange,
    onCheckboxAll: onCheckboxAll,
    onCellClick: onCellClick,
    columns: [
      { field: 'customer.name', title: '客户名称', search: { labelWidth: 85, el: 'input' }, key: 'customer' },
      {
        field: 'customer.createTime',
        title: '创建日期',
        // search: {
        //   el: 'date-picker',
        //   labelWidth: 85, 
        //   props: { type: 'daterange', valueFormat: 'YYYY-MM-DD' },
        // },
      },
      {
        field: 'customer.inputUserName',
        title: '创建人',
        // search: { el: 'input',labelWidth: 85,  props: { clearable: true } },
      },
      { field: 'customer.idCard', title: '身份证号', search: { labelWidth: 85, el: 'input', key: 'idCard' } },
      { field: 'customer.phone', title: '手机', search: { labelWidth: 85, el: 'input', key: 'phone' } },
      { field: 'legalAffairsUser.username', title: '法务人员', search: { labelWidth: 85, el: 'input', key: 'legalAffairsUserName' } },
      { field: 'riskControlUser.username', title: '风控人员', search: { labelWidth: 85, el: 'input', key: 'riskControlUserName' } },
      { field: 'customer.email', title: '电子邮箱' },
      { field: 'maxStagesNum', title: '信用卡数量', slots: {
            default: ({ row, rowIndex }) => {
              return (
                <>
                  {row.customer?.creditCard.length}
                </>
              );
            },
          }, },
      { field: 'maxStagesNum', title: '网贷&信用贷数量', slots: {
            default: ({ row, rowIndex }) => {
              return (
                <>
                  {row.customer?.lending.length}
                </>
              );
            },
          }, },
      { field: 'remark', title: '欠款总额', slots: {
            default: ({ row, rowIndex }) => {
              return (
                <>
                  {[...row.customer?.creditCard, ...row.customer?.lending].reduce((pre, cur) => pre + Number(cur.debt),0)}
                </>
              );
            },
          }, },
      { field: 'legalAffairRemark', title: '备注' },
      { field: 'riskControlStatus', slots: {
            default: ({ row }) => {
              return (
                <>
                  {row.riskControlStatus
                    ? FlowStatus.value?.find((v) => v.value === row.riskControlStatus)?.label
                    : ''}
                </>
              );
            },
          },title: '风控审核状态'},
      { field: 'legalAffairStatus', slots: {
            default: ({ row }) => {
              return (
                <>
                  {row.legalAffairStatus
                    ? FlowStatus.value?.find((v) => v.value === row.legalAffairStatus)?.label
                    : ''}
                </>
              );
            },
          },title: '法务审核状态'},
    ],
  });

  const query = () => proTable.value?.search();
  const handleClick = () => {
    setTimeout(() => {
      query();
    }, 300);
  };
  onMounted(() => {
    query();
  });
</script>
