<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="getByStagesPage"
      :paramCallback="paramCallback"
    />
    <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">
        是否审批通过选中的数据？
      </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>
    <splitDrawer ref="splitDrawerRef" @success="query" />
    <el-image-viewer :url-list="srcList" v-if="RefImage" @close="RefImage = false" />
  </div>
</template>

<script setup name="systemLog" lang="jsx">
  import splitDrawer from './components/splitDrawer.vue';
  import { computed } from 'vue';
  import { inject } from 'vue';
  import { reactive, ref } from 'vue';
  import { getByStagesPage, getByStagesTotal, byStagesflowStatusByIds } from '@/api/property';
  import { onMounted } from 'vue';
  import { ElMessageBox, ElMessage, ElButton } from 'element-plus';
  import { Download } from '@element-plus/icons-vue';
  import { getTenantPage } from '@/api/tenant';
  import { useRouter } from 'vue-router';
  import { useDict } from '@/hooks/useDict';
  import { getAppEnvConfig } from '@/utils/env';
  import { useAuthStore } from '@/stores/modules/auth';
  const { authButtonListGet } = useAuthStore(); // 获取用户权限列表
  const envs = getAppEnvConfig();
  const srcList = ref([]);
  const RefImage = ref(false);
  const { PhoneResultStatus, ReduceType, FlowStatus, FollowStatus, CaseStatus,Status } = useDict(
    'PhoneResultStatus',
    'ReduceType',
    'FlowStatus',
    'FollowStatus',
    'CaseStatus',
    'Status'
  );
  const downloadfile = inject('download');
  const activeName = ref('pending');
  const tabs = ref([]);
  const router = useRouter();

  const ProTableRef = ref();
  const showModal = ref(false);
  const selectdList = ref([]);
  const onCheckboxChange = (row) => {
    console.log('row', row);
    selectdList.value = row.records;
  };
  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));
        getByStagesTotal({ ...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;
          });
      },
      FlowStatus.value && FlowStatus.value.length ? 100 : 1000
    );
    return obj;
  };
  const handleClick = () => {
    setTimeout(() => {
      query();
    }, 300);
  };
  const download = (item) => {
    const name = item.slice(item.lastIndexOf('/') + 1, item.length);
    downloadfile('/sys/static/' + item, {}, name);
  };
  const splitDrawerRef = ref();
  const onCheckboxAll = (flag) => {
    if (flag.checked) {
      selectdList.value = flag.records;
    } else {
      selectdList.value = [];
    }
  };
  const splitDeConfig = reactive({
    columns: [
      {
        field: 'period',
        title: '期次',
        showOverflow: 'tooltip',
      },
      {
        field: 'playApplyDate',
        title: '到期日',
        showOverflow: 'tooltip',
      },
      {
        field: 'repayStatus',
        title: '状态',
        showOverflow: 'tooltip',
        slots: {
          default: ({ row }) => {
            return <>{row.repayStatus ? (row.repayStatus === 'over' ? '已还款' : '待还款') : ''}</>;
          },
        },
      },
      {
        field: 'applyAmount',
        title: '期次应还金额',
        showOverflow: 'tooltip',
      },
    ],
    toolbarConfig: { enabled: false },
  });
  const changeStatus = async (row, cancel) => {
    splitDrawerRef.value.openModal(JSON.parse(JSON.stringify(row)), cancel);
  };
  const submitForm = async (type) => {
    const ids = selectdList.value.map((v) => v.id).join(',');
    await byStagesflowStatusByIds({
      ids: ids,
      flowStatus: type,
    });

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

    query();
  };
  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 onCellClick = (row) => {
    router.push({
      path: '/property/case-detail',
      query: { id: row.id }, //这里不能直接写成 query: JSON.stringify(item)
    });
  };
  const config = computed(() => {
    return {
      columns: [
        // { type: 'checkbox', width: 60, fixed: 'left' },
        // { type: 'expand', width: 80, slots: { content: 'expand_content' } },
        {
          field: 'caseId',
          title: '案件ID',
          showOverflow: 'tooltip',
          search: { el: 'input', labelWidth: 90 },
          slots: {
            default: ({ row }) => {
              return <>{Array.from(new Set(row.loans.map((v, iiii) => <><span onClick={() => onCellClick(v)}
                  className="text-blue-400 cursor-pointer">{v.caseId}</span><span>{iiii === row.loans.length - 1 ? '':','}</span></>)))}</>;
            },
          },
          width: 80,
        },
        {
          field: 'loanPlatform.name',
          showOverflow: 'tooltip',
          title: '借款平台',
          slots: {
            default: ({ row }) => {
              return (
                <>{Array.from(new Set(row.loans.map((v) => v.loanPlatform.name))).join(',')}</>
              );
            },
          },
          // search: { el: 'input', labelWidth: 90 },
        },
        {
          field: 'borrower.name',
          showOverflow: 'tooltip',
          title: '借款人名字',
          search: { el: 'input', key: 'borrower', labelWidth: 90 },
          width: 90,
        },
        {
          title: '发起人',
          showOverflow: 'tooltip',
          width: 60,
          slots: {
            default: ({ row }) => {
              if (row.cpe?.username) {
                return <>{row.cpe?.username}</>;
              } else {
                return <>{Array.from(new Set(row.loans.map((v) => v?.cpe?.username))).join(',')}</>;
              }
            },
          },
          search: { el: 'input', props: { clearable: true }, key: 'cpeName', labelWidth: 105 },
        },
        {
          showOverflow: 'tooltip',
          slots: {
            default: ({ row }) => {
              if (row.tenant?.name) {
                return <>{row.tenant?.name}</>;
              } else {
                return <>{Array.from(new Set(row.loans.map((v) => v?.tenant?.name))).join(',')}</>;
              }
            },
          },
          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: 'totalRepayAmount',
          showOverflow: 'tooltip',
          title: '还款总额',
          search: { el: 'input', labelWidth: 90 },
          width: 80,
        },
        {
          field: 'applyTime',
          title: '分期申请时间',
          showOverflow: 'tooltip',
          search: {
            el: 'date-picker',
            labelWidth: 90,
            props: { type: 'datetime', valueFormat: 'YYYY-MM-DD HH:mm:ss' },
          },
          width: 115,
        },
        {
          field: 'effectiveTime',
          showOverflow: 'tooltip',
          title: '分期生效时间',
          search: {
            el: 'date-picker',
            labelWidth: 90,
            props: { type: 'datetime', valueFormat: 'YYYY-MM-DD HH:mm:ss' },
          },
          width: 115,
        },

        {
        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: 'totalPeriod',
          showOverflow: 'tooltip',
          title: '还款期数',
          search: {
            el: 'input',
            props: { filterable: true, type: 'number' },
            span: 1,
            labelWidth: 90,
          },
          fieldNames: { label: 'label', value: 'value' },
          width: 80,
        },
        {
          field: 'firstApplyDate',
          showOverflow: 'tooltip',
          title: '首期还款日',
          search: {
            el: 'date-picker',
            props: { type: 'date', valueFormat: 'YYYY-MM-DD' },
            labelWidth: 90,
          },
          width: 100,
        },
        {
          field: 'remainingAmount',
          showOverflow: 'tooltip',
          title: '剩余待还金额',
          search: { el: 'input', labelWidth: 90 },
          width: 110,
        },
        {
          field: 'code',
          title: '附件',
          showOverflow: 'tooltip',
          width: 70,
          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: '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: '操作',
          width: 120,
          slots: {
            default: ({ row, rowIndex }) => {
              if (row.status === 'enable' && row.flowStatus === 'pending' && authButtonListGet.includes('stages_tenant_apply_btn')) {
                return (
                  <>
                    <ElButton type="primary" onClick={() => changeStatus(row)}>
                      调解中心审核
                    </ElButton>
                  </>
                );
              } else if (row.status === 'enable' && row.flowStatus === 'in_review' && authButtonListGet.includes('stages_apply_btn')) {
                return (
                  <>
                    <ElButton type="primary" onClick={() => changeStatus(row)}>
                      平台审核
                    </ElButton>
                  </>
                );
              } else if (row.status === 'enable' && row.flowStatus === 'pass' && authButtonListGet.includes('stages_cancel_btn')) {
                return (
                  <>
                    <ElButton type="primary" onClick={() => changeStatus(row, true)}>
                      作废
                    </ElButton>
                    <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>
<style lang="scss" scoped>
  .expand-box {
    background: #fff;
    padding: 10px;
    .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;
        line-height: 11px;
        width: 240px;
        height: 40px;
        padding-left: 5px;
        font-size: 14px;
        &.label {
          background: #f6f8ff;
          color: #909399;
        }
      }
    }
  }
</style>
