<!-- 状态管理公共列表组件 -->
<script lang="ts" setup>
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { TableRow } from './status-interface'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'
import {
  cancelStatus,
  deleteStatus,
  exportStatus,
  getStatusList,
  submitStatus,
} from '@/api/device/stateManage'
import { getDictByCode } from '@/api/system/dict'
import { printJSON } from '@/utils/printUtils'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { SCHEDULE } from '@/utils/scheduleDict'
// 选中的按钮
const props = defineProps({
  name: {
    type: String,
    default: '',
  },
  title: {
    type: String,
    default: '',
  },
  type: {
    // 当前状态
    type: String,
    default: '',
  },
  applyType: {
    // 设备申请类型
    type: String,
    default: '',
  },
}); const active = ref('0')// 审批状态字典
const approvalStatusMap: { [key: string]: string } = {
  1: '草稿箱',
  2: '待审批',
  3: '审批中',
  4: '已通过',
  5: '未通过',
  6: '已取消',
  7: '非草稿',
  8: '未通过-驳回',
}
// 审批状态字典
const approvalStatusReserveMap: { [key: string]: string } = {
  '草稿箱': '1',
  '待审批': '2',
  '审批中': '3',
  '已通过': '4',
  '未通过': '5',
  '已取消': '6',
  '非草稿': '7',
  '未通过-驳回': '8',
}

const formIdList = ref({
  设备闲置申请: 'DEVICE_UNUSED_APPROVAL',
  设备封存申请: 'DEVICE_SEALED_APPROVAL',
  设备启封申请: 'DEVICE_UNSEALED_APPROVAL',
  设备报废申请: 'DEVICE_SCRAPPED_ROVAL',
  设备处置申请: 'DEVICE_HANDLE_APPROVAL',
  设备借用申请: 'DEVICE_BORROW_APPROVAL',
})
const $router = useRouter()
const searchQuery = reactive({
  applyNo: '', // 申请编号
  applyStatus: '', // 申请状态
  applyUnit: '', // 申请单位
  approvalStatus: '0', // 审批状态
  createUser: '', // 创建人
  equipmentName: '', // 设备名称
  equipmentNo: '', // 设备编号
  ids: [] as string[],
  limit: 20,
  offset: 1,
  applyType: props.applyType, // 申请类型
  formId: SCHEDULE[formIdList.value[props.name]],
}) // 查询参数
const loadingTable = ref<boolean>(false) // 表格loading
const total = ref<number>(0) // 数据总条数
const columns = ref<TableColumn[]>([
  {
    text: '申请编号',
    value: 'applyNo',
    align: 'center',
  },
  {
    text: '申请类型',
    value: 'applyTypeName',
    align: 'center',
  },
  {
    text: '设备编号',
    value: 'equipmentNo',
    align: 'center',
  },
  {
    text: '设备名称',
    value: 'equipmentName',
    align: 'center',
  },
  {
    text: '型号',
    value: 'modelNo',
    align: 'center',
  },
  {
    text: '设备状态',
    value: 'managerStateName',
    align: 'center',
  },
  {
    text: '申请单位',
    value: 'applyUnit',
    align: 'center',
  },
  {
    text: '申请人',
    value: 'applyPerson',
    align: 'center',
  },
  {
    text: `${props.name.substring(2, 4)}时间`,
    value: 'time',
    align: 'center',
  },
  {
    text: '审批状态',
    value: 'approvalStatusName',
    align: 'center',
  },
]) // 表格
const list = ref([]) // 表格数据
const managerStateList = ref([]) // 状态数据
const approvalDialog = ref()
const dialogVisible = ref<boolean>(false) // 添加组件的显示与隐藏
const { proxy } = getCurrentInstance() as any

const clearSearch = () => {
  searchQuery.equipmentName = ''
  searchQuery.applyNo = ''
  searchQuery.applyStatus = ''
  searchQuery.applyUnit = ''
  searchQuery.approvalStatus = ''
  searchQuery.createUser = ''
  searchQuery.equipmentNo = ''
  searchQuery.ids = [] as string[]
  searchQuery.limit = 20
  searchQuery.offset = 1
  searchQuery.applyType = props.applyType
  searchQuery.formId = SCHEDULE[formIdList.value[props.name]]
}

// 获取数据列表
const getList = () => {
  loadingTable.value = true
  getDictByCode('managerState')
    .then((response) => {
      if (response.code === 200) {
        console.log(response.data, 'response') // 状态
        managerStateList.value = response.data
        // searchQuery.approvalStatus = active.value
        // 根据闲置，封存，启封等状态获取不同的列表
        getStatusList(searchQuery).then((res) => {
          if (res.code === 200) {
            list.value = res.data.rows.map((item: TableRow) => {
              return {
                ...item,
                approvalStatus: approvalStatusMap[item.approvalStatus],
              }
            })
            total.value = res.data.total
          }
          loadingTable.value = false
        })
      }
    })
    .catch((_) => {
      loadingTable.value = false
    })
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    searchQuery.limit = val.size
  }
  if (val && val.page) {
    searchQuery.offset = val.page
  }
  getList()
}
// 详情
const detail = (row: TableRow) => {
  $router.push({
    name: 'stateManageDetail',
    params: {
      type: 'detail',
      id: row.id,
    },
    query: {
      title: '详情',
      name: props.name,
      applyType: props.applyType,
    },
  })
}
// 编辑
const update = (row: TableRow) => {
  $router.push({
    name: 'stateManageDetail',
    params: {
      type: 'edit',
      id: row.id,
    },
    query: {
      title: '编辑',
      name: props.name,
      applyType: props.applyType,
    },
  })
}
// 删除
const remove = (row: TableRow) => {
  const { id } = row
  ElMessageBox.confirm(`确认删除${row.equipmentName}吗？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteStatus({ id }).then((res) => {
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        getList()
      }
    })
  })
}
// 同意
const agree = (row: TableRow) => {
  approvalDialog.value.initDialog('agree', row.processId)
}
// 驳回
const reject = (row: TableRow) => {
  approvalDialog.value.initDialog('reject', row.processId)
}
// 拒绝
const refuse = (row: TableRow) => {
  approvalDialog.value.initDialog('refuse', row.processId)
}
// 取消
const cancel = (row: TableRow) => {
  const { processId } = row
  ElMessageBox.confirm('确认取消吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    cancelStatus({ processInstanceId: processId }).then((res) => {
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '取消成功',
        })
        getList()
      }
    })
  })
}

// 提交
const submit = (row: TableRow) => {
  // 流程id为空
  const { id } = row
  ElMessageBox.confirm('确认提交吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    submitStatus({ id, formId: searchQuery.formId }).then((res) => {
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '提交成功',
        })
        getList()
      }
    })
  })
}
// 搜索
const search = () => {
  getList()
}
// 重置
const reset = () => {
  clearSearch()
  getList()
}
// 模板下载
const templateDownload = () => {}
// 标签识别
const identify = () => {}
// 新增
const add = () => {
  $router.push({
    name: 'stateManageDetail',
    params: {
      type: 'add',
    },
    query: {
      title: '新建',
      name: props.name,
      applyType: props.applyType,
    },
  })
}
// 表格被选中的行
const selectList = ref<TableRow[]>([])
// 表格多选
const multiSelect = (row: TableRow[]) => {
  selectList.value = row
}
// 打印
function printList() {
  const selectIds = selectList.value.map(item => item.id)
  const properties = columns.value.map((item) => {
    return {
      field: item.value,
      displayName: item.text,
    }
  })
  if (selectIds.length <= 0 && list.value.length > 0) {
    printJSON(list.value, properties, props.name)
  }
  else if (selectIds.length > 0) {
    const printList = list.value.filter((item: TableRow) =>
      selectIds.includes(item.id),
    )
    printJSON(printList, properties, props.name)
  }
  else {
    ElMessage('无可打印内容')
  }
}
// 导出
const exportExcelBtn = () => {
  // const params: supplierExportQuery = {
  //   approvalStatus: listQuery.value.approvalStatus,
  //   businessContent: listQuery.value.businessContent,
  //   companyArea: listQuery.value.companyArea,
  //   companyCity: listQuery.value.companyCity,
  //   companyProvince: listQuery.value.companyProvince,
  //   formId: listQuery.value.formId,
  //   supplierName: listQuery.value.supplierName,
  //   supplierNo: listQuery.value.supplierNo,
  // }
  // if (checkoutList.value.length > 0) {
  //   params.ids = checkoutList.value
  // }
  const postData = {
    applyType: searchQuery.applyType,
    approvalStatus: searchQuery.approvalStatus,
    createUser: searchQuery.createUser,
    ids: [] as number[],
  }
  postData.ids = selectList.value.map((item) => {
    return item.id
  })
  exportStatus(postData).then((res) => {

  })
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  loading.close()
}
const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  // 原生上传
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    fd.append('multipartFile', event.target.files[0])
  }
}
// 批量导入
const batchImport = () => {
  fileRef.value.click()
}
// 传给子组件的刷新事件
const refreshDta = () => {
  getList()
  dialogVisible.value = false
}
watch(
  () => props.type,
  (newValue) => {
    if (newValue === '0') {
      searchQuery.approvalStatus = ''
    }
    else {
      searchQuery.approvalStatus = newValue
    }
    getList()
  },
  {
    immediate: true,
    deep: true,
  },
)
</script>

<template>
  <div>
    <!-- 审批操作组件 -->
    <approval-dialog ref="approvalDialog" @on-success="approvalSuccess" />
    <!-- 布局 -->
    <app-container>
      <!-- 筛选条件 -->
      <search-area :need-clear="true" @search="search" @clear="reset">
        <search-item>
          <el-input
            v-model="searchQuery.applyNo"
            placeholder="申请编号"
            clearable
            class="w-50 m-2"
          />
        </search-item>
        <search-item>
          <el-input
            v-model="searchQuery.equipmentNo"
            placeholder="设备编号"
            clearable
            class="w-50 m-2"
          />
        </search-item>
        <search-item>
          <el-input
            v-model="searchQuery.equipmentName"
            placeholder="设备名称"
            clearable
            class="w-50 m-2"
          />
        </search-item>
        <search-item>
          <el-input
            v-model="searchQuery.applyUnit"
            placeholder="申请单位"
            clearable
            class="w-50 m-2"
          />
        </search-item>
        <search-item>
          <el-select
            v-model="searchQuery.applyStatus"
            placeholder="申请状态"
            clearable
          >
            <el-option
              v-for="manager of managerStateList"
              :key="manager.id"
              :label="manager.name"
              :value="manager.value"
            />
          </el-select>
        </search-item>
      </search-area>
      <table-container>
        <!-- 表头区域 -->
        <template #btns-right>
          <input
            v-show="searchQuery.limit === 0"
            ref="fileRef"
            type="file"
            multiple
            @change="onFileChange"
          >
          <icon-button icon="icon-add" title="新建" @click="add" />
          <icon-button
            icon="icon-export"
            title="导出"
            @click="exportExcelBtn"
          />
          <icon-button icon="icon-print" title="打印" @click="printList" />
        </template>
        <!-- 表格区域 -->
        <normal-table
          id="print"
          :data="list"
          :total="total"
          :columns="columns"
          :is-showmulti-select="true"
          :query="{ limit: searchQuery.limit, offset: searchQuery.offset }"
          :list-loading="loadingTable"
          :is-multi="true"
          @change="changePage"
          @multi-select="multiSelect"
        >
          <template #preColumns>
            <el-table-column label="序号" width="55" align="center">
              <template #default="scope">
                {{
                  (searchQuery.offset - 1) * searchQuery.limit
                    + scope.$index
                    + 1
                }}
              </template>
            </el-table-column>
          </template>
          <template #columns>
            <el-table-column
              label="操作"
              align="center"
              width="230"
              fixed="right"
            >
              <template #default="{ row }">
                <el-button
                  size="small"
                  type="primary"
                  link
                  @click="detail(row)"
                >
                  查看
                </el-button>
                <el-button
                  v-if="!['0', '2', '3', '4', '5'].includes(props.type)"
                  size="small"
                  type="primary"
                  link
                  @click="update(row)"
                >
                  编辑
                </el-button>
                <el-button
                  v-if="!['0', '2', '3', '4', '5'].includes(props.type)"
                  size="small"
                  type="primary"
                  link
                  @click="submit(row)"
                >
                  提交
                </el-button>
                <el-button
                  v-if="['0', '2', '3'].includes(props.type)"
                  size="small"
                  type="primary"
                  link
                  :disabled="
                    row.approvalStatus !== '待审批'
                      && row.approvalStatus !== '审批中'
                  "
                  @click="agree(row)"
                >
                  同意
                </el-button>
                <el-button
                  v-if="['0', '2', '3'].includes(props.type)"
                  size="small"
                  type="primary"
                  link
                  :disabled="
                    row.approvalStatus !== '待审批'
                      && row.approvalStatus !== '审批中'
                  "
                  @click="reject(row)"
                >
                  驳回
                </el-button>
                <el-button
                  v-if="['0', '2', '3'].includes(props.type)"
                  size="small"
                  type="danger"
                  link
                  :disabled="
                    row.approvalStatus !== '待审批'
                      && row.approvalStatus !== '审批中'
                  "
                  @click="refuse(row)"
                >
                  拒绝
                </el-button>
                <el-button
                  v-if="!['1', '2', '4', '5', '6'].includes(props.type)"
                  size="small"
                  type="text"
                  link
                  :disabled="row.approvalStatus !== '审批中'"
                  @click="cancel(row)"
                >
                  取消
                </el-button>
                <el-button
                  v-if="
                    props.type !== '4'
                      && props.type !== '5'
                  "
                  :disabled="row.approvalStatus === '未通过' || row.approvalStatus === '已通过'"
                  size="small"
                  type="danger"
                  link
                  @click="remove(row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>
    </app-container>
  </div>
</template>
