<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" :selectdList="selectdList">
      <template #left_buttons>
        <!-- <el-button type="primary">下载申请 </el-button> -->
        <el-button
          type="primary"
          @click="changeStatus"
          v-if="activeName==='pending'"
          v-permission="'repayment_apply_btn'"
          :disabled="!selectdList || !selectdList.length"
          >审批
        </el-button>
        <!-- <el-button type="primary">下载 </el-button>
        <el-button type="primary">批量修复上传 </el-button> -->
      </template>
    </ProTable>
    <vxe-modal
      resize
      v-model="showModal"
      title="审批提示"
      height="282"
      width="450"
      show-footer
      esc-closable
    >
      <div class="w-full px-3 h-full overflow-auto flex-col flex mytable">
        <template v-if="currentRow">
          是否审批通过{{currentRow ? `借款人${currentRow?.borrower?.name}, 还款金额${currentRow?.realRepayAmount}，实际还款时间${currentRow?.realRepayTime}`: ''}}的数据？
        </template>
        <template v-else>
          是否审批通过以下数据：<br>
          <div v-for="(item,index) in selectdList" :key="index">
            {{`借款人${item?.borrower?.name}, 还款金额${item?.realRepayAmount}，实际还款时间${item?.realRepayTime}`}}
          </div>
        </template>
      </div>
      <template #footer>
        <el-button type="default" @click="showModal = false">取消</el-button>
        <el-button type="danger" @click="submitForm('fail')">不通过</el-button>
        <el-button type="primary" @click="submitForm('pass')">通过</el-button>
      </template>
    </vxe-modal>
  </div>
</template>

<script setup name="repaymentApprove" lang="jsx">
  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 { 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 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) => {
    if (row.id) {
      currentRow.value = row
    } else {
      currentRow.value = null
    }
    showModal.value = true;
  };
  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) => v.loan.caseId))).join(
                      ','
                    )}
                  </>
                );
              } else if (row.stages && row.stages.loans) {
                return <>{Array.from(new Set(row.stages.loans.map((v) => v.caseId))).join(',')}</>;
              } else {
                return <>{row.loan?.caseId}</>;
              }
            },
          },
          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 }) => {
              if (row.reduce && row.reduce.reduceRecords) {
                return (
                  <>
                    {Array.from(new Set(row.reduce.reduceRecords.map((v) => v.loan?.cpe?.username))).join(
                      ','
                    )}
                  </>
                );
              } else if (row.stages && row.stages.loans) {
                return <>{Array.from(new Set(row.stages.loans.map((v) => v?.cpe?.username))).join(',')}</>;
              } else {
                return <>{row.cpe?.username}</>;
              }
            },
          },
          search: { el: 'input', props: { clearable: true }, key: 'cpeName', labelWidth: 105 },
        },
        {
          showOverflow: 'tooltip',
          slots: {
            default: ({ row }) => {
              if (row.reduce && row.reduce.reduceRecords) {
                return (
                  <>
                    {Array.from(new Set(row.reduce.reduceRecords.map((v) => v.loan?.tenant?.name))).join(
                      ','
                    )}
                  </>
                );
              } else if (row.stages && row.stages.loans) {
                return <>{Array.from(new Set(row.stages.loans.map((v) => v?.tenant?.name))).join(',')}</>;
              } else {
                return <>{row.tenant?.name}</>;
              }
            },
          },
          enum: () => getTenantPage({ current: 1, size: 999999999, status: 'enable' }),
          search: { el: 'select', props: { filterable: 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: 'reduce.totalPayAmount',
          showOverflow: 'tooltip',
          title: '应还金额',
          search: { el: 'input', key: 'reduce.totalPayAmount', labelWidth: 90 },
          width: 115,
        },
        {
          field: 'repayType',
          showOverflow: 'tooltip',
          title: '还款方式',
          enum: RepayType,
          search: { el: 'select', props: { filterable: 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: '操作',
          visible: activeName.value === 'pending' && authButtonListGet.includes('repair_apply_btn') ? true : false,
          slots: {
              default: ({ row, rowIndex }) => {
                return (
                  <>
                    <ElButton type="primary" onClick={() => changeStatus(row)}>
                      审批
                    </ElButton>
                  </>
                );
              }
          },
        }
      ],
      onCheckboxChange: onCheckboxChange,
      onCheckboxAll: onCheckboxAll,
    };
  });
  const query = () => ProTableRef.value?.search();

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