<!-- 设备借用处理 -->
<script lang="ts" setup name="BorrowHandle">
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 type { IMenu } from '@/components/buttonBox/buttonBox'
import type { IlistQuery, IlistType, dictType } from '@/views/device/receive/receive'
import { borrowApply, deleteApply, exportApply, getBorrowApplyList, returnApply } from '@/api/device/borrow'
import { keepSearchParams, renewSearchParams } from '@/utils/keepQuery'
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 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: '4', // 	审批状态 (已通过)
  processResult: '1' || active.value, // 	处置结果 (3个状态字典值)
  applyType: '2', // 申请类型 借用2
  createUser: '', // 创建人
  formId: SCHEDULE.DEVICE_BORROW_APPROVAL,
  offset: 1,
  limit: 20,
})
// 页面跳转之前保存参数
onBeforeRouteLeave((to: any) => {
  keepSearchParams(to.path, 'borrow-borrowHandle', listQuery.value)
})
// 重新赋值
listQuery.value = renewSearchParams('borrow-borrowHandle') || {
  applyNo: '', // 申请编号
  applyName: '', // 申请名称
  applyUnit: '', // 申请部门id
  applyUnitName: '', // 申请部门名称
  applyPerson: '', // 申请人id
  applyPersonName: '', // 申请人姓名
  startTime: '', // 借用开始日期
  endTime: '', // 借用结束日期
  approvalStatus: '4', // 	审批状态 (已通过)
  processResult: '1' || active.value, // 	处置结果 (3个状态字典值)
  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',
    width: '180',
  },
  {
    text: '申请名称',
    value: 'applyName',
    align: 'center',
  },
  {
    text: '申请部门',
    value: 'applyUnitName',
    align: 'center',
  },
  {
    text: '申请人',
    value: 'applyPersonName',
    align: 'center',
  },
  {
    text: '申请时间',
    value: 'time',
    align: 'center',
    width: '180',
  },
]) // 表格
// 时间变更
watch(timeRange, (val) => {
  if (val) {
    listQuery.value.startTime = `${val[0]}`
    listQuery.value.endTime = `${val[1]}`
  }
  else {
    listQuery.value.startTime = ''
    listQuery.value.endTime = ''
  }
})
// 数据查询
const fetchData = (isNowPage = false) => {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  listQuery.value.processResult = active.value
  getBorrowApplyList(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 clearList = () => {
  listQuery.value = {
    applyNo: '', // 申请编号
    applyName: '', // 申请名称
    applyUnit: '', // 申请部门
    applyPerson: '', // 申请人
    startTime: '', // 申请开始日期
    endTime: '', // 申请结束日期
    approvalStatus: '4', // 	审批状态(已通过)
    processResult: active.value, // 	处置结果
    applyType: '2', // 申请类型 借用2
    createUser: '', // 创建人
    formId: SCHEDULE.DEVICE_BORROW_APPROVAL,
    offset: 1,
    limit: 20,
  }
  timeRange.value = ['', '']
  fetchData(true)
}

// 切换tab状态
const changeCurrentButton = (val: string) => {
  if (!val) {
    active.value = '1'
    activeTitle.value = '待借用'
    window.sessionStorage.setItem('borrowhandleActive', '1')
    // clearList()
    listQuery.value.processResult = active.value
    fetchData(true)
  }
  else {
    console.log('ppppp', val)

    active.value = val
    activeTitle.value = menu.value.find(item => item.id === val)!.name
    window.sessionStorage.setItem('borrowhandleActive', val)
    fetchData(true)
    // clearList()
  }
}

// 搜索
const searchList = () => {
  fetchData(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
  }
}

// 获取用户列表(增加模糊查询)
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) => {
    if (res.data) { // 将列表转树结构
      useDeptList.value = toTreeList(res.data, '0', true)
    }
  })
}

// 获取字典值
const getDict = async () => {
  // 审批状态
  const res = await getDictByCode('equipmentApplyProcessResult')
  // 审批状态字典 {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 === '已归还') {
      menu.value.push({
        name: item.name,
        id: `${item.value}`,
      })
    }
  })
}

// 导出
const exportExcelBtn = () => {
  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()
}
// 打印
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 templateDownload = () => {
}
// 多选发生改变时
const handleSelectionChange = (e: any) => {
  checkoutList.value = e.map((item: { id: string }) => item.id)
}

// 借用
const borrow = (row: IlistType) => {
  ElMessageBox.confirm(
    `确认借用${row.applyName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    borrowApply({ id: row.id as string }).then((res) => {
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '借用成功',
        })
        fetchData(true)
      }
    })
  })
}
// 归还
const returnBtn = (row: IlistType) => {
  ElMessageBox.confirm(
    `确认归还${row.applyName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then((res) => {
    returnApply({ id: row.id as string }).then((res) => {
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '归还成功',
        })
        fetchData(true)
      }
    })
  })
}

const $router = useRouter()

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
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)
}

// 详情
const detail = (row: IlistType) => {
  $router.push({
    path: '/borrow/borrowDetail',
    query: {
      id: row.id,
      processId: row.processId, // 查询审批记录使用
      activeTitle: activeTitle.value,
    },
  })
}

// 删除
const remove = (row: IlistType) => {
  ElMessageBox.confirm(
    `确认删除${row.applyName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      deleteApply({ id: row.id as string }).then((res) => {
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          fetchData(true)
        }
      })
    })
}

onMounted(async () => {
  await getDict() // 获取字典-审批状态
  if (window.sessionStorage.getItem('borrowhandleActive')) {
    active.value = window.sessionStorage.getItem('borrowhandleActive') as string
  }
  else {
    active.value = menu.value.find(item => item.name === '待借用')!.id as string // 待借用
    activeTitle.value === '待借用'
  }
  setTimeout(() => {
    fetchData(true) // 获取表格数据
    fetchDeptTreeList() // 获取使用部门
    fetchUserList() // 获取人员列表
  }, 300)
})
</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:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          start-placeholder="申请开始时间"
          end-placeholder="申请结束时间"
        />
      </search-item>
    </search-area>
    <table-container>
      <template #btns-right>
        <icon-button v-if="proxy.hasPerm('/device/borrow/borrowhandle/export')" icon="icon-export" title="导出" @click="exportExcelBtn" />
        <icon-button v-if="proxy.hasPerm('/device/borrow/borrowhandle/print')" icon="icon-print" title="打印" @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 v-if="activeTitle === '已归还'" label="归还时间" width="180" align="center">
            <template #default="scope">
              {{ scope.row.backTime }}
            </template>
          </el-table-column>
          <el-table-column label="审批状态" width="120" align="center">
            <template #default="scope">
              {{ scope.row.approvalStatusName }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" :width="activeTitle === '待借用' ? '130' : activeTitle === '已借用' ? '110' : '80'">
            <template #default="{ row }">
              <el-button size="small" type="primary" link @click="detail(row)">
                查看
              </el-button>
              <el-button v-if="proxy.hasPerm('/device/borrow/borrowhandle/borrow') && activeTitle === '待借用'" size="small" type="primary" link @click="borrow(row)">
                借用
              </el-button>
              <el-button v-if="proxy.hasPerm('/device/borrow/borrowhandle/return') && activeTitle === '已借用'" size="small" type="primary" link @click="returnBtn(row)">
                归还
              </el-button>
              <el-button v-if="proxy.hasPerm('/device/borrow/borrowhandle/delete') && activeTitle === '待借用'" size="small" type="danger" link @click="remove(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>
