<!-- 设备借用申请 -->
<script lang="ts" setup name="BorrowApply">
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 { SCHEDULE } from '@/utils/scheduleDict'
import ButtonBox from '@/components/buttonBox/buttonBox.vue'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'
import type { IMenu } from '@/components/buttonBox/buttonBox'
import type { IlistQuery, IlistType, dictType } from '@/views/device/receive/receive'
import { cancelApproval, deleteApply, exportApply, getApplyList, submitApply } from '@/api/device/borrow'
import {
  submitReceiveApplyList,
} from '@/api/device/receive'

import { getDictByCode } from '@/api/system/dict'
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 { getDeptTreeList } from '@/api/system/dept'
import { exportFile } from '@/utils/exportUtils'
import { printJSON } from '@/utils/printUtils'
import type { TableColumn } from '@/components/NormalTable/table_interface'
const { proxy } = getCurrentInstance() as any
const active = ref('') // 选中的按钮
const activeTitle = ref('') // active对应的审批状态名字
const approvalDialog = ref() // 审批对话框显隐
const menu = ref<IMenu[]>([]) // 审批状态按钮组合
// 筛选时间段数据
const timeRange = ref<[DateModelType, DateModelType]>(['', ''])
const loadingTable = ref(false) // 表格loading
const list = ref<IlistType[]>([])// 表格数据
const total = ref(20)// 页码总数
const useDeptList = ref<deptType[]>([]) // 部门列表
const usePersonList = ref<userType[]>([]) // 申请人列表（用户）
const usePersonOptions = ref<userType[]>([]) // 申请人列表（用户）--模糊搜索数据
const applyPersonLoading = ref(false) // 申请人模糊搜索框loading

// 查询条件
const listQuery: Ref<IlistQuery> = ref({
  applyNo: '', // 申请编号
  applyName: '', // 申请名称
  applyUnit: '', // 申请部门id
  applyUnitName: '', // 申请部门名称
  applyPerson: '', // 申请人id
  applyPersonName: '', // 申请人姓名
  startTime: '', // 领用开始日期
  endTime: '', // 领用结束日期
  approvalStatus: active.value, // 	审批状态 1 2 3 对应待借用|已借用|已归还
  processResult: '', // 	处置结果
  applyType: '2', // 申请类型 借用2
  createUser: '', // 创建人
  formId: SCHEDULE.DEVICE_BORROW_APPROVAL,
  offset: 1,
  limit: 20,
})

const approvalStatusMap = ref({}) as any// 审批状态字典{1：草稿箱}
const approvalStatusReserveMap = ref({}) as any// 审批状态字典{草稿箱: 1}

// 选中的内容
const checkoutList = ref<string[]>([])
// 表格数据
const columns = ref<TableColumn[]>([
  {
    text: '申请编号',
    value: 'applyNo',
    align: 'center',
  },
  {
    text: '申请名称',
    value: 'applyName',
    align: 'center',
  },
  {
    text: '申请部门',
    value: 'applyUnitName',
    align: 'center',
  },
  {
    text: '申请人',
    value: 'applyPersonName',
    align: 'center',
  },
  {
    text: '申请时间',
    value: 'time',
    align: 'center',
  },
  {
    text: '审批状态',
    value: 'approvalStatusName',
    align: 'center',
  },
])

// 数据查询
const fetchData = (isNowPage = false) => {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  listQuery.value.startTime = timeRange.value[0] as string || ''
  listQuery.value.endTime = timeRange.value[1] as string || ''
  listQuery.value.approvalStatus = active.value
  getApplyList(listQuery.value).then((response) => {
    list.value = response.data.rows.map((item: IlistType) => {
      return {
        ...item,
        approvalStatus: approvalStatusMap.value[item.approvalStatus],

      }
    })
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  })
}

// 获取字典值
const getDict = async () => {
  // 审批状态
  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}`
  })

  // 制作右上角的菜单
  res.data.forEach((item: dictType) => {
    if (item.name === '全部' || item.name === '草稿箱'
      || item.name === '待审批' || item.name === '审批中'
      || item.name === '已通过' || item.name === '未通过'
      || item.name === '已取消') {
      menu.value.push({
        name: item.name,
        id: `${item.value}`,
      })
    }
  })
}

const clearList = () => {
  listQuery.value = {
    applyNo: '', // 申请编号
    applyName: '', // 申请名称
    applyUnit: '', // 申请部门
    applyPerson: '', // 申请人
    startTime: '', // 申请开始日期
    endTime: '', // 申请结束日期
    approvalStatus: active.value, // 	审批状态  // 	审批状态 1 2 3 对应待借用|已借用|已归还
    processResult: '', // 	处置结果
    applyType: '2', // 申请类型 借用2
    createUser: '', // 创建人
    formId: SCHEDULE.DEVICE_BORROW_APPROVAL,
    offset: 1,
    limit: 20,
  }
  timeRange.value = ['', '']
  fetchData(true)
}

// 切换tab状态
const changeCurrentButton = (val: string) => {
  active.value = val
  activeTitle.value = menu.value.find(item => item.id === val)!.name
  window.sessionStorage.setItem('buttonBoxActive', val)
  clearList()
}

// 获取用户列表(增加模糊查询)
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 $router = useRouter()

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

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

// 导出
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, // 申请结束日期
      approvalStatus: listQuery.value.approvalStatus, // 	审批状态
      processResult: listQuery.value.processResult, // 	处置结果
      applyType: listQuery.value.applyType, // 申请类型 领用0
      createUser: listQuery.value.createUser, // 创建人
      formId: SCHEDULE.DEVICE_BORROW_APPROVAL,
      offset: 1,
      limit: 20,
      ids: checkoutList.value,
    }
    // 调导出接口
    exportApply(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: IlistType) => checkoutList.value.includes(item.id))
    printJSON(printList, properties, '设备借用申请列表')
  }
  else {
    ElMessage.warning('无可打印内容')
  }
}

// 选择器模糊查询
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
  }
}

// 审批结束回调
const approvalSuccess = () => {
  fetchData(true)
}

// 新建
const add = () => {
  $router.push({
    name: 'stateManageDetail',
    params: {
      type: 'add',
    },
    query: {
      title: '新建',
      name: '设备借用申请',
      applyType: '2',
    },
  })
}

// 操作
const handleEdit = (row: IlistType, val: string, title = '') => {
  if (val === '取消') {
    const params = {
      processInstanceId: row.processId!,
      comments: '',
    }
    ElMessageBox.confirm(
      '确认取消该审批吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
      .then(() => {
        cancelApproval(params).then((res) => {
          ElMessage({
            type: 'success',
            message: '取消成功',
          })
        })
        fetchData(true)
      })
  }
  else if (val === '删除') {
    ElMessageBox.confirm(
      '确认删除该审批吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
      .then(() => {
        deleteApply({ id: row.id, taskId: row.taskId }).then((res) => {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          fetchData(true)
        })
      })
  }
  else if (val === '提交') {
    ElMessageBox.confirm(
      '确认提交该审批吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
      .then(() => {
        submitReceiveApplyList({ id: row.id, formId: SCHEDULE.DEVICE_BORROW_APPROVAL }).then((res) => {
          ElMessage({
            type: 'success',
            message: '已提交',
          })
        })
        fetchData(true)
      })
  }
  else if (val === '同意') {
    approvalDialog.value.initDialog('agree', row.taskId)
  }
  else if (val === '驳回') {
    approvalDialog.value.initDialog('reject', row.taskId)
  }
  else if (val === '拒绝') {
    approvalDialog.value.initDialog('refuse', row.taskId)
  }
  else if (val === '查看' || val === '编辑') {
    if (val === '查看') {
      $router.push({
        name: 'stateManageDetail',
        params: {
          type: 'detail',
        },
        query: {
          id: row.id,
          title: '详情',
          name: '设备借用申请',
          approvalStatus: active.value,
          approvalStatusName: row.approvalStatusName,
        },
      })
    }
    else {
      $router.push({
        name: 'stateManageDetail',
        params: {
          type: 'edit',
        },
        query: {
          id: row.id,
          title: '编辑',
          name: '设备借用申请',
        },
      })
    }
  }
}
onMounted(async () => {
  await getDict() // 获取字典-审批状态
  if (window.sessionStorage.getItem('buttonBoxActive') !== 'undefined' && window.sessionStorage.getItem('buttonBoxActive') !== '') {
    active.value = window.sessionStorage.getItem('buttonBoxActive')!
  }
  else {
    active.value = menu.value.find(item => item.name === '全部')!.id // 全部
    activeTitle.value === '全部'
  }
  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="申请编号"
          class="short-input"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.applyName"
          placeholder="申请名称"
          class="short-input"
          clearable
        />
      </search-item>
      <search-item>
        <dept-select v-model="listQuery.applyUnit" placeholder="请选择申请部门" :data="useDeptList" />
      </search-item>
      <search-item>
        <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>
      </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 v-if="proxy.hasPerm('/device/borrow/borrowapply/add')" icon="icon-add" title="新建" type="primary" @click="add" />
        <icon-button v-if="proxy.hasPerm('/device/borrow/borrowapply/export')" icon="icon-export" title="导出" type="primary" @click="exportAll" />
        <icon-button v-if="proxy.hasPerm('/device/borrow/borrowapply/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="(activeTitle === '全部') ? 220 : (activeTitle === '草稿箱' || activeTitle === '已取消' || activeTitle === '审批中') ? 150 : (activeTitle === '已通过' || activeTitle === '未通过') ? 140 : 200"
            fixed="right"
          >
            <template #default="{ row }">
              <el-button
                size="small"
                type="primary"
                link
                @click="handleEdit(row, '查看', 'detail')"
              >
                查看
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/device/borrow/borrowapply/add') && (activeTitle === '全部' || activeTitle === '待审批')"
                size="small"
                link
                type="primary"
                :disabled="(row.approvalStatus !== '待审批' && row.approvalStatus !== '审批中') || row.decisionItem === 3"
                @click="handleEdit(row, '同意')"
              >
                同意
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/device/borrow/borrowapply/reject') && (activeTitle === '全部' || activeTitle === '待审批')"
                size="small"
                link
                type="primary"
                :disabled="(row.approvalStatus !== '待审批' && row.approvalStatus !== '审批中') || row.decisionItem === 3"
                @click="handleEdit(row, '驳回')"
              >
                驳回
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/device/borrow/borrowapply/refuse') && (activeTitle === '全部' || activeTitle === '待审批')"
                size="small"
                link
                type="danger"
                :disabled="(row.approvalStatus !== '待审批' && row.approvalStatus !== '审批中') || row.decisionItem === 1 || row.decisionItem === 2"
                @click="handleEdit(row, '拒绝')"
              >
                拒绝
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/device/borrow/borrowapply/update') && (activeTitle === '草稿箱' || activeTitle === '已取消')"
                size="small"
                link
                type="primary"
                @click="handleEdit(row, '编辑', 'edit')"
              >
                编辑
              </el-button>

              <el-button
                v-if="proxy.hasPerm('/device/borrow/borrowapply/update') && activeTitle === '未通过'"
                size="small"
                link
                type="primary"
                :disabled="row.approvalStatusName.search('驳回') === -1 "
                @click="handleEdit(row, '编辑', 'edit')"
              >
                编辑
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/device/borrow/borrowapply/update') && (activeTitle === '草稿箱' || activeTitle === '已取消')"
                size="small"
                link
                type="primary"
                @click="handleEdit(row, '提交')"
              >
                提交
              </el-button>
              <!-- 是发起者且审批中可以取消 -->
              <el-button
                v-if="proxy.hasPerm('/device/borrow/borrowapply/cancel') && (activeTitle === '全部' || activeTitle === '审批中')"
                size="small"
                link
                type="info"
                :disabled="row.approvalStatus !== '审批中'"
                @click="handleEdit(row, '取消')"
              >
                取消
              </el-button>
              <!-- 发起者和有删除权限的可以删除，已通过未通过状态不可以删除 -->
              <el-button
                v-show="activeTitle === '草稿箱' ? true : false"
                v-if="proxy.hasPerm('/device/borrow/borrowapply/delete') && (activeTitle !== '已通过' && activeTitle !== '未通过')"
                size="small"
                link
                type="danger"
                :disabled="row.approvalStatus === '未通过' || row.approvalStatus === '已通过'"
                @click="handleEdit(row, '删除')"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
    <button-box :active="active" :menu="menu" @changeCurrentButton="changeCurrentButton" />
    <approval-dialog ref="approvalDialog" @on-success="approvalSuccess" />
  </app-container>
</template>

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