<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?.applyTime}}时提交的申请？
      </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 } 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 } = useDict("PhoneResultStatus","ReduceType", "FlowStatus", "FollowStatus", "CaseStatus");
  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'];
    }
    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 download = (row) => {
    downloadfile('/RepairApply/download', {id: row.id}, '修复列表.xls');
  }
  const submitForm = async (type) => {
    const ids = currentRow.value.id
    await RepairRecordStatusByIds({
      id: ids,
      flowStatus: type,
    });

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

    query();
  };

  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: '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: 'code',
          title: '操作',
          width: 120,
          slots: {
            default: ({ row, rowIndex }) => {
              if (activeName.value === 'pending' && authButtonListGet.includes('allcation_for_tenant')) {
                return (
                  <>
                    <ElButton type="primary" onClick={() => changeStatus(row)}>
                      审批
                    </ElButton>
                  </>
                );
              } else if (activeName.value === 'pass') {
                return (
                  <>
                    <ElButton type="primary" onClick={() => download(row)}>
                      下载
                    </ElButton>
                  </>
                );
              }
            },
          },
        }
    ],
    onCheckboxChange: onCheckboxChange,
    onCheckboxAll: onCheckboxAll,
  });
  const query = () => caseLRef.value?.search();

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