<script lang="ts" setup name="SolveList">
import { ref } from 'vue'
import type { Ref } from 'vue'
import type { DateModelType } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import ButtonBox from '@/components/buttonBox/buttonBox.vue'
import type { IlistQuery, IsolveListType, dictType } from '@/views/device/receive/receive'
import { exportFile } from '@/utils/exportUtils'
import { printJSON } from '@/utils/printUtils'
import { SCHEDULE } from '@/utils/scheduleDict'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { getDeptTreeList } from '@/api/system/dept'
import { toTreeList } from '@/utils/structure'
import type { userType } from '@/views/system/user/user-interface'
import type { deptType } from '@/views/device/standingBook/standingBook-interface'
import { getUserList } from '@/api/system/user'
import {
  delReceiveApplyList,
  exportReceiveApplyList,
  getReceiveApplyList,
  updateProcessResult,
} from '@/api/device/receive'
import { getDictByCode } from '@/api/system/dict'
import type { IMenu } from '@/components/buttonBox/buttonBox'

const useDeptList = ref<deptType[]>([]) // 部门列表
const usePersonList = ref<userType[]>([]) // 申请人列表（用户）
const usePersonOptions = ref<userType[]>([]) // 申请人列表（用户）--模糊搜索数据
const applyPersonLoading = ref(false) // 申请人模糊搜索框loading
const loadingTable = ref(false) // 表格loading
const active = ref('') // 选中的按钮
const approvalStatusMap = ref({}) as any// 审批状态字典{1：草稿箱}
const approvalStatusReserveMap = ref({}) as any// 审批状态字典{草稿箱: 1}
const menu = ref<IMenu[]>([]) // 右上角按钮
// 查询条件
const listQuery: Ref<IlistQuery> = ref({
  applyNo: '', // 申请编号
  applyName: '', // 申请名称
  applyUnit: '', // 申请部门id
  applyUnitName: '', // 申请部门名称
  applyPerson: '', // 申请人id
  applyPersonName: '', // 申请人姓名
  startTime: '', // 领用开始日期
  endTime: '', // 领用结束日期
  equipmentApplyProcessResult: active.value, // 设备申请处理结果--4待领用、5已领用
  approvalStatus: '4', // 审批状态--已通过
  processResult: active.value, // 	处置结果--4待领用、5已领用
  applyType: '1', // 申请类型 领用1
  createUser: '', // 创建人
  formId: SCHEDULE.DEVICE_CONSUMING_APPROVAL,
  offset: 1,
  limit: 20,
})
const timeRange = ref<[DateModelType, DateModelType]>(['', ''])

// 表格数据
const list = ref<IsolveListType[]>([])
const { proxy } = getCurrentInstance() as any
// 总数
const total = ref(20)
// 表头
const columns = ref<TableColumn[]>([
  { text: '申请编号', value: 'applyNo', align: 'center', width: '180' },
  { text: '申请名称', value: 'applyName', align: 'center' },
  { text: '申请部门', value: 'applyUnitName', align: 'center' },
  { text: '申请人', value: 'applyPersonName', align: 'center' },
  { text: '领用时间', value: 'time', align: 'center', width: '160' },
  { text: '申请说明', value: 'applyDesc', align: 'center' },
  { text: '审批状态', value: 'approvalStatus', align: 'center' },
])
// 选中的内容
const checkoutList = ref<string[]>([])

// 获取字典值
async function getDict() {
  // 审批状态
  const res = await getDictByCode('approvalStatus')
  // 审批状态字典 {1：草稿箱}
  res.data.forEach((item: any) => {
    approvalStatusMap.value[`${item.value}`] = item.name
  })

  // 审批状态字典 {草稿箱: 1}
  res.data.forEach((item: any) => {
    approvalStatusReserveMap.value[item.name] = `${item.value}`
  })

  // 设备申请处理结果
  const equipmentApplyProcessResultRes = await getDictByCode('equipmentApplyProcessResult')
  // 制作右上角的菜单
  equipmentApplyProcessResultRes.data.forEach((item: dictType) => {
    if (item.name === '待领用' || item.name === '已领用') {
      menu.value.push({
        name: item.name,
        id: `${item.value}`,
      })
    }
  })
}

// 重置
const clearList = () => {
  listQuery.value = {
    applyNo: '', // 申请编号
    applyName: '', // 申请名称
    applyUnit: '', // 申请部门
    applyPerson: '', // 申请人
    startTime: '', // 申请开始日期
    endTime: '', // 申请结束日期
    approvalStatus: '4', // 	审批状态--已通过
    processResult: active.value, // 	处置结果
    applyType: '1', // 申请类型 领用1
    createUser: '', // 创建人
    formId: SCHEDULE.DEVICE_CONSUMING_APPROVAL,
    equipmentApplyProcessResult: active.value, // 设备申请处理结果
    offset: 1,
    limit: 20,
  }
  timeRange.value = ['', ''] // 把时间选择框置空
  fetchData(true)
}
// 时间变更
watch(timeRange, (val) => {
  if (val) {
    listQuery.value.startTime = `${val[0]}`
    listQuery.value.endTime = `${val[1]}`
  }
  else {
    listQuery.value.startTime = ''
    listQuery.value.endTime = ''
  }
})
// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  getReceiveApplyList(listQuery.value).then((response) => {
    list.value = response.data.rows.map((item: IsolveListType) => {
      return {
        ...item,
        approvalStatus: approvalStatusMap.value[item.approvalStatus],
      }
    })
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  })
}

// 搜索
const searchList = () => {
  fetchData(true)
}

// 多选发生改变时
const handleSelectionChange = (e: any) => {
  checkoutList.value = e.map((item: { id: string }) => item.id)
}

// 导出
const exportAll = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中请稍后',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (list.value.length > 0) {
    const params = {
      applyNo: listQuery.value.applyNo, // 申请编号
      applyName: listQuery.value.applyName, // 申请名称
      applyUnit: listQuery.value.applyUnit, // 申请部门
      applyPerson: listQuery.value.applyPerson, // 申请人
      startTime: listQuery.value.startTime, // 申请开始日期
      endTime: listQuery.value.endTime, // 申请结束日期
      equipmentApplyProcessResult: listQuery.value.equipmentApplyProcessResult, // 设备申请处理结果--4待领用、5已领用
      approvalStatus: listQuery.value.approvalStatus, // 	审批状态
      processResult: listQuery.value.processResult, // 	处置结果
      applyType: listQuery.value.applyType, // 申请类型 领用1
      createUser: listQuery.value.createUser, // 创建人
      formId: SCHEDULE.DEVICE_CONSUMING_APPROVAL,
      offset: 1,
      limit: 20,
      ids: checkoutList.value,
    }
    // 调导出接口
    exportReceiveApplyList(params).then((res) => {
      const blob = new Blob([res.data])
      exportFile(blob, '设备领用处理列表.xlsx')
    })
  }
  else {
    ElMessage.warning('无数据可导出数据')
  }
  loading.close()
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    listQuery.value.limit = val.size
  }
  if (val && val.page) {
    listQuery.value.offset = val.page
  }
  fetchData(true)
}

// 打印列表
function printList() {
  // 打印列
  const properties = columns.value.map((item) => {
    return {
      field: item.value,
      displayName: item.text,
    }
  })
  if (checkoutList.value.length <= 0 && list.value.length > 0) {
    printJSON(list.value, properties, '设备领用处理列表')
  }
  else if (checkoutList.value.length > 0) {
    const printList = list.value.filter((item: IsolveListType) => checkoutList.value.includes(item.id))
    printJSON(printList, properties, '设备领用处理列表')
  }
  else {
    ElMessage.warning('无可打印内容')
  }
}

// 操作
const $router = useRouter()
const handleEdit = (row: IsolveListType, val: string) => {
  if (val === '查看') {
    $router.push({
      path: '/receive/solveDetail',
      query: {
        id: row.id,
        processId: row.processId, // 查询审批记录使用
      },
    })
  }
  else {
    ElMessageBox.confirm(
    `确认${val}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
    )
      .then(() => {
        if (val === '领用' || val === '退领') {
          const processResult = val === '领用' ? '5' : '4'
          updateProcessResult({ id: row.id, processResult }).then(() => {
            ElMessage.success(`已${val}`)
            fetchData(true)
          })
        }
        if (val === '删除') {
          delReceiveApplyList({ id: row.id, taskId: row.taskId }).then(() => {
            ElMessage.success(`已${val}`)
            fetchData(true)
          })
        }
      })
  }
}

// 右上角按钮切换
const changeCurrentButton = (val: string) => {
  active.value = val
  window.sessionStorage.setItem('receiveSolveButtonBoxActive', val)
  clearList()
}

// 标签识别
const execTag = () => {}

// 获取用户列表
const fetchUserList = () => {
  getUserList({ offset: 1, limit: 999999 }).then((res: any) => {
    usePersonList.value = res.data.rows
    usePersonOptions.value = res.data.rows
  })
}

// 获取使用部门
const fetchDeptTreeList = () => {
  getDeptTreeList().then((res: any) => {
    if (res.data) { // 将列表转树结构
      useDeptList.value = toTreeList(res.data, '0', true)
    }
  })
}

// 选择器模糊查询
const remoteMethod = (query: string) => {
  if (query) {
    applyPersonLoading.value = true
    setTimeout(() => {
      applyPersonLoading.value = false
      usePersonOptions.value = usePersonList.value.filter((item) => {
        return item.name.toLowerCase().includes(query.toLowerCase())
      })
    }, 200)
  }
  else {
    usePersonOptions.value = usePersonList.value
  }
}

onMounted(async () => {
  await getDict()
  if (window.sessionStorage.getItem('receiveSolveButtonBoxActive') !== 'undefined' && window.sessionStorage.getItem('receiveSolveButtonBoxActive') !== '' && window.sessionStorage.getItem('receiveSolveButtonBoxActive') !== 'null' && window.sessionStorage.getItem('receiveSolveButtonBoxActive') !== null) {
    active.value = window.sessionStorage.getItem('receiveSolveButtonBoxActive')!
  }
  else {
    active.value = menu.value.find(item => item.name === '待领用')!.id! // 未领用
  }
  nextTick(() => {
    // 获取表格数据
    fetchData(true)
    // 获取使用部门
    fetchDeptTreeList()
    // 获取人员列表
    fetchUserList()
  })
})
</script>

<template>
  <app-container>
    <search-area
      :need-clear="true"
      @search="searchList" @clear="clearList"
    >
      <search-item>
        <el-input
          v-model.trim="listQuery.applyNo"
          placeholder="申请编号"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.applyName"
          placeholder="申请名称"
          clearable
        />
      </search-item>
      <search-item>
        <dept-select v-model="listQuery.applyUnit" placeholder="请选择申请部门" :data="useDeptList" />
      </search-item>
      <search-item>
        <el-form-item prop="applyPerson">
          <el-select
            v-model="listQuery.applyPerson"
            placeholder="请选择申请人"
            style="width: 100%;"
            filterable
            remote
            remote-show-suffix
            :remote-method="remoteMethod"
            :loading="applyPersonLoading"
          >
            <el-option v-for="item in usePersonOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </search-item>
      <search-item>
        <el-date-picker
          v-model="timeRange"
          type="datetimerange"
          range-separator="到"
          format="YYYY-MM-DD hh:mm"
          value-format="YYYY-MM-DD hh:mm"
          start-placeholder="领用开始时间"
          end-placeholder="领用结束时间"
        />
      </search-item>
    </search-area>

    <table-container>
      <template #btns-right>
        <!-- <icon-button icon="icon-device" title="标签识别" @click="execTag" /> -->
        <icon-button v-if="proxy.hasPerm('/device/receive/applyList/export')" icon="icon-export" title="导出" type="primary" @click="exportAll" />
        <icon-button v-if="proxy.hasPerm('/device/receive/applyList/print')" icon="icon-print" title="打印" type="primary" @click="printList" />
      </template>
      <normal-table
        :data="list" :total="total" :columns="columns" :query="listQuery"
        :list-loading="loadingTable" is-showmulti-select @change="changePage" @multiSelect="handleSelectionChange"
      >
        <template #preColumns>
          <el-table-column label="序号" width="55" align="center">
            <template #default="scope">
              {{ (listQuery.offset - 1) * listQuery.limit + scope.$index + 1 }}
            </template>
          </el-table-column>
        </template>
        <template #columns>
          <el-table-column label="操作" align="center" width="130" fixed="right">
            <template #default="{ row }">
              <el-button
                size="small"
                type="primary"
                link
                @click="handleEdit(row, '查看')"
              >
                查看
              </el-button>
              <el-button
                v-if="active === '4'"
                size="small"
                link
                type="primary"
                @click="handleEdit(row, '领用')"
              >
                领用
              </el-button>
              <!-- 发起者和有删除权限的可以删除，已通过未通过状态不可以删除 -->
              <el-button
                v-if="row.approvalStatus === '已通过'"
                size="small"
                link
                type="danger"
                @click="handleEdit(row, '删除')"
              >
                删除
              </el-button>
              <el-button
                v-if="row.approvalStatus === '未通过'"
                size="small"
                link
                type="primary"
                @click="handleEdit(row, '退领')"
              >
                退领
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
    <button-box
      :active="active"
      :menu="menu"
      @changeCurrentButton="changeCurrentButton"
    />
  </app-container>
</template>

<style lang="scss" scoped>
// 样式
</style>

