<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="caseLRef" :api="getRepairApply" :paramCallback="paramCallback">
    </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">
        是否审批通过申请人{{currentRow?.applyUser?.username}}于{{currentRow?.downloadStatus === 'pending' ?currentRow?.applyTime : currentRow?.downloadApplyTime}}时提交的{{currentRow?.downloadStatus === 'pending' ? '下载' : ''}}申请？
      </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="systemLog" lang="jsx">
  import { computed } from 'vue';
  import { onMounted } from 'vue';
  import { reactive, ref } from 'vue';
  import { getRepairApply,getRepairApplyTotal,  RepairRecordStatusByIds, applyDownloadById, downLoadApplyStatusById } from '@/api/property';
  import { ElMessageBox, ElMessage, ElButton } from 'element-plus';
  import { getTenantPage } from '@/api/tenant';
  import { useDict } from '@/hooks/useDict';
  import { inject } from 'vue';
  import citydata from '../../../assets/citydata';
  import { getPlatformPage } from '@/api/platform';
  import { VxeTextEllipsis, VxeTooltip } from 'vxe-pc-ui';
  import { useAuthStore } from '@/stores/modules/auth';
  const { PhoneResultStatus, ReduceType, FlowStatus, FollowStatus, CaseStatus, DownLoadApplyStatus } = useDict("PhoneResultStatus","ReduceType", "FlowStatus", "FollowStatus", "CaseStatus", "DownLoadApplyStatus");
  const downloadfile = inject('download');
  const { authButtonListGet } = useAuthStore(); // 获取用户权限列表

  const tabledata = ref([]);
  const showModal = ref(false);
  const tabs = ref([]);
  const activeName = ref('pending');
  const caseLRef = ref();
  const selectdList = ref([]);
  const currentRow = 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['applyTime']) {
      if (obj['applyTime'][0]) obj['applyTimeBegin'] = obj['applyTime'][0];
      if (obj['applyTime'][1]) obj['applyTimeEnd'] = obj['applyTime'][1];
      delete obj['applyTime'];
    }
    if (obj['downloadApplyTime']) {
      if (obj['downloadApplyTime'][0]) obj['downloadApplyTimeBegin'] = obj['downloadApplyTime'][0];
      if (obj['downloadApplyTime'][1]) obj['downloadApplyTimeEnd'] = obj['downloadApplyTime'][1];
      delete obj['downloadApplyTime'];
    }
    setTimeout(() => {
      const arr = JSON.parse(JSON.stringify(FlowStatus.value))
      getRepairApplyTotal({...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 changeStatus = async (row) => {
    currentRow.value = row
    showModal.value = true;
  };
  const query = () => caseLRef.value?.search();

  const download = (row) => {
    downloadfile('/RepairApply/download', {id: row.id}, '修复列表.xls');
  }
  const submitForm = async (type) => {
    const ids = currentRow.value.id
    if (currentRow.value.downloadStatus === 'pending') {
      await downLoadApplyStatusById({
        id: ids,
        downLoadApplyStatus: type
      })
    } else {
      await RepairRecordStatusByIds({
        id: ids,
        flowStatus: type,
      });
    }

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

    query();
  };
  const applyDownload = async (row) => {
    await ElMessageBox.confirm(`是否申请修复申请标题为${row.title}，申请人为${row.applyUser.username}，申请时间为${row.applyTime}的下载权限?`, '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    });

    applyDownloadById({
      id: row.id
    })
    ElMessage({
      type: 'success',
      message: '申请成功！',
      plain: true,
    });
    setTimeout(() => {
      query();
    }, 500)
  }

  const config = reactive({
    columns: [
      {
        field: 'title',
        title: '修复申请标题',
        showOverflow: 'tooltip',
        width: 120,
        // search: {
        //   el: 'input',
        //   key: 'name',
        //   props: { clearable: true },
        //   labelWidth: 105,
        // },
      },
      {
        field: 'applyUser.username',
        title: '申请人',
        showOverflow: 'tooltip',
        width: 140,
        search: {
          el: 'input',
          props: { clearable: true },
          key: 'applyUser',
          labelWidth: 105,
        },
      },
      {
        field: 'repairUser.username',
        title: '审核人',
        showOverflow: 'tooltip',
        width: 140
      },
        {
          showOverflow: 'tooltip',
          slots: {
            default: ({ row }) => {
              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: 'repairNum',
        title: '修复申请人数',
        showOverflow: 'tooltip',
        // width: 140,
        // search: {
        //   el: 'input',
        //   props: { clearable: true },
        //   key: 'newPhone',
        //   labelWidth: 105,
        // },
      },
      {
        field: 'applyTime',
        title: '申请时间',
        showOverflow: 'tooltip',
        width: 140,
        search: {
          el: 'date-picker',
          props: { type: 'daterange', valueFormat: 'YYYY-MM-DD' },
          labelWidth: 105,
        },
      },
      {
        field: 'downloadApplyTime',
        title: '下载申请时间',
        showOverflow: 'tooltip',
        width: 140,
        search: {
          el: 'date-picker',
          props: { type: 'daterange', valueFormat: 'YYYY-MM-DD' },
          labelWidth: 105,
        },
      },
      {
        field: 'repairTime',
        title: '审核时间',
        showOverflow: 'tooltip',
        width: 140,
      },
      {
        field: 'flowStatus',
        showOverflow: 'tooltip',
        title: '审核状态',
        width: 95,
        enum: FlowStatus,
        // search: { el: 'select', props: { filterable: true }, labelWidth: 105 },
        fieldNames: { label: 'label', value: 'value' },
        slots: {
          default: ({ row }) => {
            return (
              <>
                {row.flowStatus ? FlowStatus.value?.find((v) => v.value === row.flowStatus)?.label : ''}
              </>
            );
          },
        },
      },
      {
        field: 'downloadStatus',
        showOverflow: 'tooltip',
        title: '下载审批状态',
        width: 95,
        enum: DownLoadApplyStatus,
        // search: { el: 'select', props: { filterable: true }, labelWidth: 105 },
        fieldNames: { label: 'label', value: 'value' },
        slots: {
          default: ({ row }) => {
            return (
              <>
                {row.downloadStatus ? DownLoadApplyStatus.value?.find((v) => v.value === row.downloadStatus)?.label : ''}
              </>
            );
          },
        },
      },
      {
          field: 'code',
          title: '操作',
          width: 120,
          slots: {
            default: ({ row, rowIndex }) => {
              if (activeName.value === 'pending' && authButtonListGet.includes('repair_apply_btn')) {
                return (
                  <>
                    <ElButton type="primary" onClick={() => changeStatus(row)}>
                      审批
                    </ElButton>
                  </>
                );
              } else if (activeName.value === 'pass') {
                if (row.downloadStatus === 'pass') {
                  return (
                    <>
                      <ElButton type="primary" onClick={() => download(row)}>
                        下载
                      </ElButton>
                    </>
                  );
                } else {
                  if (row.downloadStatus === 'pending' && authButtonListGet.includes('repair_apply_btn')) {
                    return (
                      <>
                        <ElButton type="primary" onClick={() => changeStatus(row)}>
                          下载审批
                        </ElButton>
                      </>
                    );
                  } else {
                    return (
                      <>
                        <ElButton type="primary" onClick={() => applyDownload(row)} disabled={row.downloadStatus === 'pending'}>
                          下载申请
                        </ElButton>
                      </>
                    );
                  }
                }
              }
            },
          },
        }
    ],
    onCheckboxChange: onCheckboxChange,
    onCheckboxAll: onCheckboxAll,
  });

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