<template>
  <div class="table-box">
    <div class="bg-white pt-2 pl-2">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <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
      :config="config"
      ref="ProTableRef"
      :api="getRepayRecordPage"
      :paramCallback="paramCallback"
    >
      <!-- <template #left_buttons>
        <el-button
          type="primary"
          @click="changeStatus"
          v-if="activeName === 'pending'"
          v-permission="'repayment_apply_btn'"
          :disabled="!selectdList || !selectdList.length"
          >审批
        </el-button>
      </template> -->
    </ProTable>
    <returnModal
      ref="returnModalRef"
      @submitForm="submitForm"
      :mergerCase="detail?.mergerCase"
    />
  </div>
</template>

<script setup name="repaymentApprove" lang="jsx">
  import returnModal from './components/returnModal.vue';
  import { computed } from 'vue';
  import { reactive, ref } from 'vue';
  import {
    getRepayRecordPage,
    getRepayRecordTotal,
    repayRecordFlowStatusByIds,
  } from '@/api/property';
  import { onMounted } from 'vue';
  import { ElMessageBox, ElMessage, ElButton } from 'element-plus';
  import { useDict } from '@/hooks/useDict';
  import { getTenantPage } from '@/api/tenant';
  import { useAuthStore } from '@/stores/modules/auth';
  const { authButtonListGet } = useAuthStore(); // 获取用户权限列表
  const returnModalRef = ref();
  import { useRouter } from 'vue-router';
  const router = useRouter();

  const { RepayType, FlowStatus } = useDict('RepayType', 'FlowStatus');
  const ProTableRef = ref();
  const showModal = ref(false);
  const currentRow = ref(null);
  const activeName = ref('pending');
  const tabs = ref([]);
  const selectdList = ref([]);
  const onCheckboxChange = (row) => {
    console.log('row', row);
    selectdList.value = row.records;
  };
  const onCheckboxAll = (flag) => {
    if (flag.checked) {
      selectdList.value = flag.records;
    } else {
      selectdList.value = [];
    }
  };
  const onCellClick = (row) => {
    router.push({
      path: '/property/case-detail',
      query: { id: row.id }, //这里不能直接写成 query: JSON.stringify(item)
    });
  };
  const handleClick = () => {
    setTimeout(() => {
      query();
    }, 300);
  };
  const paramCallback = (param) => {
    const obj = JSON.parse(JSON.stringify(param));
    obj['flowStatus'] = activeName.value;
    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['nextTime']) {
      if (obj['nextTime'][0]) obj['nextTrackTimeBegin'] = obj['nextTime'][0];
      if (obj['nextTime'][1]) obj['nextTrackTimeEnd'] = obj['nextTime'][1];
      delete obj['nextTime'];
    }
    setTimeout(() => {
      const arr = JSON.parse(JSON.stringify(FlowStatus.value));
      getRepayRecordTotal({ ...obj, flowStatus: 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;
        });
    }, 500);
    return obj;
  };
  const changeStatus = async (row) => {
    currentRow.value = row
    const type = RepayType.value?.find((v) => v.value === row.repayType)?.label
    if (type === '分期还款') {
      returnModalRef.value.openModal(
        JSON.parse(JSON.stringify(row.byStagesRecord)),
        JSON.parse(JSON.stringify(row)),
        type
      );
    } else if (type === '直接还款') {
      returnModalRef.value.openModal(
        JSON.parse(JSON.stringify(row.loan)),
        JSON.parse(JSON.stringify(row)),
        type
      );
    } else {
      {
      returnModalRef.value.openModal(
        JSON.parse(JSON.stringify(row.reduce)),
        JSON.parse(JSON.stringify(row)),
        type
      );
    }
    }
  };
  const submitForm = async (type) => {
    const ids = selectdList.value.map((v) => v.id).join(',');
    await repayRecordFlowStatusByIds({
      ids: currentRow.value && currentRow.value.id ? currentRow.value.id : ids,
      flowStatus: type,
    });

    ElMessage.success({
      message: '审核成功',
      plain: true,
    });
    showModal.value = false;

    query();
  };
  const config = computed(() => {
    return {
      columns: [
        // { type: 'checkbox', width: 60, fixed: 'left' },
        {
          field: 'caseId',
          showOverflow: 'tooltip',
          title: '案件ID',
          search: { el: 'input', labelWidth: 90 },
          slots: {
            default: ({ row }) => {
              if (row.reduce && row.reduce.reduceRecords) {
                return <>{Array.from(new Set(row.reduce.reduceRecords.map((v, iiii) => <><span onClick={() => onCellClick(v.loan)}
                  className="text-blue-400 cursor-pointer">{v.loan.caseId}</span><span>{iiii === row.reduce.reduceRecords.length - 1 ? '':','}</span></>)))}</>;
              } else if (row.stages && row.stages.loans) {
                return <>{Array.from(new Set(row.stages.loans.map((v, iiii) => <><span onClick={() => onCellClick(v)}
                  className="text-blue-400 cursor-pointer">{v.caseId}</span><span>{iiii === row.stages.loans.length - 1 ? '':','}</span></>)))}</>;
              } else {
                return <><span onClick={() => onCellClick(row.loan)}
                  className="text-blue-400 cursor-pointer">{row.loan?.caseId}</span></>;
              }
            },
          },
          width: 180,
        },
        {
          field: 'borrower.name',
          title: '借款人名字',
          showOverflow: 'tooltip',
          search: { el: 'input', key: 'borrower', labelWidth: 90 },
          width: 90,
        },
        {
          title: 'CPE',
          showOverflow: 'tooltip',
          width: 80,
          slots: {
            default: ({ row }) => {
              return <>{row.cpe?.username}</>;
            },
          },
          search: { el: 'input', props: { clearable: true }, key: 'cpeName', labelWidth: 105 },
        },
        {
          showOverflow: 'tooltip',
          slots: {
            default: ({ row }) => {
              return <>{row.tenant?.name}</>;
            },
          },
          enum: () => getTenantPage({ current: 1, size: 999999999, status: 'enable' }),
          search: { el: 'select', props: { filterable: true, clearable: true }, key: 'tenantId', labelWidth: 105 },
          fieldNames: { label: 'name', value: 'id' },
          title: '调解中心',
          width: 100,
        },
        {
          field: 'realRepayAmount',
          title: '实际还款金额',
          width: 140,
          showOverflow: 'tooltip',
          search: { el: 'input', labelWidth: 90 },
        },
        {
          field: 'realRepayTime',
          showOverflow: 'tooltip',
          title: '实际还款时间',
          search: {
            el: 'date-picker',
            labelWidth: 90,
            props: { type: 'datetime', valueFormat: 'YYYY-MM-DD HH:mm:ss' },
          },
          width: 140,
        },
        {
          field: 'repayAmount',
          showOverflow: 'tooltip',
          title: '应还金额',
          search: { el: 'input', key: 'repayAmount', labelWidth: 90 },
          width: 115,
        },
        {
          field: 'repayType',
          showOverflow: 'tooltip',
          title: '还款方式',
          enum: RepayType,
          search: { el: 'select', props: { filterable: true,clearable: true }, span: 1, labelWidth: 90 },
          fieldNames: { label: 'label', value: 'value' },
          slots: {
            default: ({ row }) => {
              return (
                <>
                  {row.repayType
                    ? RepayType.value?.find((v) => v.value === row.repayType)?.label
                    : ''}
                </>
              );
            },
          },
          width: 100,
        },
        {
          field: 'loanPlatform',
          title: '借款平台',
          showOverflow: 'tooltip',
        },
        {
          field: 'flowStatus',
          title: '审核状态',
          showOverflow: 'tooltip',
          width: 80,
          enum: FlowStatus,
          // search: { el: 'select', props: { filterable: true }, span: 1, labelWidth: 90 },
          fieldNames: { label: 'label', value: 'value' },
          slots: {
            default: ({ row }) => {
              return (
                <>
                  {row.flowStatus
                    ? FlowStatus.value?.find((v) => v.value === row.flowStatus)?.label
                    : ''}
                </>
              );
            },
          },
        },
        {
          field: 'code',
          title: '操作',
          slots: {
            default: ({ row, rowIndex }) => {
              if (row.flowStatus === 'pending' && authButtonListGet.includes('repayment_tenant_apply_btn')) {
                return (
                  <>
                    <ElButton type="primary" onClick={() => changeStatus(row)}>
                      调解中心审核
                    </ElButton>
                  </>
                );
              } else if (row.flowStatus === 'in_review' && authButtonListGet.includes('repayment_apply_btn')) {
                return (
                  <>
                    <ElButton type="primary" onClick={() => changeStatus(row)}>
                      平台审核
                    </ElButton>
                  </>
                );
              } else {
                return (
                  <>
                    <ElButton type="primary" onClick={() => changeStatus(row)}>
                      查看
                    </ElButton>
                  </>
                );
              }
            },
          },
        },
      ],
      onCheckboxChange: onCheckboxChange,
      onCheckboxAll: onCheckboxAll,
    };
  });
  const query = () => ProTableRef.value?.search();

  onMounted(() => {
    query();
  });
</script>
