<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="getReducePage"
      :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>
    <reduceDrawer ref="reduceDrawerRef" @success="query" />
    <el-image-viewer :url-list="srcList" v-if="RefImage" @close="RefImage = false" />
  </div>
</template>

<script setup name="systemLog" lang="jsx">
  import { computed } from 'vue';
  import reduceDrawer from './components/reduceDrawer.vue';
  import { reactive, ref } from 'vue';
  import { getReducePage, getReduceTotal, flowStatusByIds } from '@/api/property';
  import { onMounted } from 'vue';
  import { inject } from 'vue';
  import { ElMessageBox, ElMessage, ElButton } from 'element-plus';
  import { getTenantPage } from '@/api/tenant';
  import { useDict } from '@/hooks/useDict';
  import { Download } from '@element-plus/icons-vue';
  import { getAppEnvConfig } from '@/utils/env';
  import { useAuthStore } from '@/stores/modules/auth';
  import { useRouter } from 'vue-router';
  const router = useRouter();

  const envs = getAppEnvConfig();
  const reduceDrawerRef = ref();
  const { authButtonListGet } = useAuthStore(); // 获取用户权限列表
  const { PhoneResultStatus, ReduceType, FlowStatus, FollowStatus, CaseStatus,Status } = useDict(
    'PhoneResultStatus',
    'ReduceType',
    'FlowStatus',
    'FollowStatus',
    'CaseStatus',
    'Status'
  );
  const downloadfile = inject('download');
  const ProTableRef = ref();
  const showModal = ref(false);
  const tabs = ref([]);
  const srcList = ref([]);
  const activeName = ref('pending');
  const RefImage = ref(false);
  const selectdList = ref([]);
  const onCheckboxChange = (row) => {
    selectdList.value = row.records;
  };
  const download = (item) => {
    const name = item.slice(item.lastIndexOf('/') + 1, item.length);
    downloadfile('/sys/static/' + item, {}, name);
  };
  const changeStatus = async (row) => {
    reduceDrawerRef.value.openModal(JSON.parse(JSON.stringify(row)));
  };
  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));
        getReduceTotal({ ...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 onCheckboxAll = (flag) => {
    if (flag.checked) {
      selectdList.value = flag.records;
    } else {
      selectdList.value = [];
    }
  };
  const handleClick = () => {
    setTimeout(() => {
      query();
    }, 300);
  };
  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 submitForm = async (type) => {
    const ids = selectdList.value.map((v) => v.id).join(',');
    await flowStatusByIds({
      ids: ids,
      flowStatus: type,
    });

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

    query();
  };
  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: 40, slots: { content: 'expand_content' } },
        {
          field: 'caseId',
          title: '案件ID',
          showOverflow: 'tooltip',
          search: { el: 'input', labelWidth: 90 },
          slots: {
            default: ({ row }) => {
              return <>{Array.from(new Set(row.reduceRecords.map((v, iiii) => <><span onClick={() => onCellClick(v.loan)}
                  className="text-blue-400 cursor-pointer">{v.loan.caseId}</span><span>{iiii === row.reduceRecords.length - 1 ? '':','}</span></>)))}</>;
            },
          },
          width: 120,
        },
        {
          field: 'borrower.name',
          title: '借款人名字',
          showOverflow: 'tooltip',
          search: { el: 'input', key: 'borrower', labelWidth: 90 },
          width: 90,
        },
        {
          field: 'totalReduceAmount',
          showOverflow: 'tooltip',
          title: '减免金额',
          search: { el: 'input', labelWidth: 90 },
          width: 120,
        },
        {
          field: 'totalNumber',
          showOverflow: 'tooltip',
          title: '减免案件数',
          search: { el: 'input', labelWidth: 90 },
          width: 120,
        },
        {
          field: 'remainingAmount',
          showOverflow: 'tooltip',
          title: '剩余待还金额',
          search: { el: 'input', labelWidth: 90 },
          width: 120,
        },
        {
          field: 'totalPayAmount',
          showOverflow: 'tooltip',
          title: '累计还款金额',
          search: { el: 'input', labelWidth: 90 },
          width: 120,
        },
        {
          title: '发起人',
          showOverflow: 'tooltip',
          width: 70,
          slots: {
            default: ({ row }) => {
              if (row.cpe?.username) {
                return <>{row.cpe?.username}</>;
              } else {
                return (
                  <>
                    {Array.from(new Set(row.reduceRecords.map((v) => v.loan?.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.reduceRecords.map((v) => v.loan?.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: '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: 'inEffectDate',
          title: '减免截止时间',
          showOverflow: 'tooltip',
          width: 120,
          search: {
            el: 'date-picker',
            labelWidth: 90,
            props: { type: 'datetime', valueFormat: 'YYYY-MM-DD HH:mm:ss' },
          },
        },

        {
        field: 'status',
        showOverflow: 'tooltip',
        title: '状态',
        width: 80,
        fieldNames: { label: 'label', value: 'value' },
        slots: {
          default: ({ row }) => {
            return (
              <>
                {row.status
                  ? Status.value?.find((v) => v.value === row.status)?.label
                  : ''}
              </>
            );
          },
        },
      },

        {
          field: 'code',
          title: '操作',
          width: 120,
          slots: {
            default: ({ row, rowIndex }) => {
              if (row.status==='enable' && row.flowStatus === 'pending' && authButtonListGet.includes('reduction_tenant_apply_btn')) {
                return (
                  <>
                    <ElButton type="primary" onClick={() => changeStatus(row)}>
                      调解中心审核
                    </ElButton>
                  </>
                );
              } else if (row.status==='enable' && row.flowStatus === 'in_review' && authButtonListGet.includes('reduction_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>
<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>
