<!-- 审批提醒列表页 -->
<script name="WorkBenchApprove" setup lang="ts">
import type { Ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { DateModelType } from 'element-plus'
import { number } from 'echarts'
import type { IApprovalMessageListQuery } from '../workbench-interface'
import { useChangePage } from './useChangePage'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { changeWorkbenchApproveStatus, getApprovalMessageList } from '@/api/workbench/workbench'
import { getDictByCode } from '@/api/system/dict'
import type { dictType } from '@/global'

import { formUrl } from '@/utils/scheduleDict'
const $router = useRouter()
const { proxy } = getCurrentInstance() as any
const messageSourceModuleList = ref<dictType[]>([]) // 是否加急
const statusList = [
  {
    id: '1',
    name: '已处理/已读',
  },
  {
    id: '0',
    name: '未处理/未读',
  },
]
// 查询条件
const listQuery: Ref<IApprovalMessageListQuery> = ref({
  endTime: '', // 通知结束时间
  messageSourceModule: '', // 来源模块（字典code）
  startTime: '', // 通知开始时间
  status: '0', // 已读1未读0
  offset: 1,
  limit: 20,
})
const total = ref(0) // 数据条数
const loadingTable = ref(false) // 表格loading
const list = ref([]) // 表格数据
// 筛选时间段数据
const dateRange = ref<[DateModelType, DateModelType]>(['', ''])
// 表头
const columns = ref<TableColumn[]>([
  { text: '创建时间', value: 'createTime', align: 'center', width: '180' },
  { text: '主题', value: 'messageTitle', align: 'center' },
  { text: '来源模块', value: 'messageSourceModuleName', align: 'center' },
  { text: '具体内容', value: 'messageContent', align: 'center' },
  { text: '处理情况', value: 'statusName', align: 'center', width: '100', styleFilter: (row: any) => { return row.statusName == '未处理' ? 'color: #f56c6c' : row.statusName == '已处理' ? 'color: #6ebf8a' : '' } },
])

// 获取审批提醒列表页
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  const param = {
    ...listQuery.value,
    status: listQuery.value.status === '' ? '' : Number(listQuery.value.status),
  }
  getApprovalMessageList(param).then((response) => {
    list.value = response.data.rows.map((item: { messageContent: string; statusName: string ; status: string; messageTitle: string }) => {
      return {
        ...item,
        messageContent: item.messageTitle === '结果通知' ? `${item.messageContent}审批已通过` : item.messageContent,
        statusName: item.messageTitle === '结果通知' ? item.status == '1' ? '已读' : '未读' : item.status == '1' ? '已处理' : '未处理',
      }
    })
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  }).catch(() => {
    loadingTable.value = false
  })
}

// 搜索
const searchList = () => {
  fetchData(false)
}
// 时间变更
watch(dateRange, (val) => {
  if (val) {
    listQuery.value.startTime = `${val[0]}`
    listQuery.value.endTime = `${val[1]}`
  }
  else {
    listQuery.value.startTime = ''
    listQuery.value.endTime = ''
  }
})
// 重置
const reset = () => {
  listQuery.value = {
    endTime: '', // 通知结束时间
    messageSourceModule: '', // 来源模块（字典code）
    startTime: '', // 通知开始时间
    status: '0', // 已读1未读0
    offset: 1,
    limit: 20,
  }
  dateRange.value = ['', '']
  fetchData(true)
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
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 getDict = async () => {
  // 来源模块
  getDictByCode('messageSourceModule').then((response) => {
    messageSourceModuleList.value = response.data
  })
}
/**
 * 离开守卫：通过路由规则，离开该组件时被调用
 * to 包含的内容是切换后的路由对象，也就是跳转后的路由对象
 * from，包含的内容的是切换前的路由对象，也就是跳转前的路由对象
 *next()，是否往下执行，执行的话，如果不写的话路由就不会跳转，操作将会终止
 */
onBeforeRouteLeave((to, from, next) => {
  console.log(to)
  if (to.path === '/standard/Applydetail') { // 更换、暂停、撤销、恢复、复查
    switch (to.query.applyType) {
      case '1':
        to.meta.activeMenu = '/standard/changeApply'
        to.meta.title = '更换申请'
        break
      case '2':
        to.meta.activeMenu = '/standard/pauseApply'
        to.meta.title = '暂停申请'
        break
      case '3':
        to.meta.activeMenu = '/standard/cancelApply'
        to.meta.title = '撤销申请'
        break
      case '4':
        to.meta.activeMenu = '/standard/resumeApply'
        to.meta.title = '恢复申请'
        break
      case '5':
        to.meta.activeMenu = '/standard/checkApply'
        to.meta.title = '复查申请'
        break
    }
  }

  if (to.meta.title === '设备闲置申请' || to.meta.title === '设备封存申请' || to.meta.title === '设备启封申请' || to.meta.title === '设备报废申请' || to.meta.title === '设备处置申请') {
    switch (to.query.applyType) {
      case '3':
        to.meta.activeMenu = '/stateManage/unusedApply'
        to.meta.title = '设备闲置申请'
        break
      case '4':
        to.meta.activeMenu = '/stateManage/sealupApply'
        to.meta.title = '设备封存申请'
        break
      case '5':
        to.meta.activeMenu = '/stateManage/openApply'
        to.meta.title = '设备启封申请'
        break
      case '6':
        to.meta.activeMenu = '/stateManage/scrapApply'
        to.meta.title = '设备报废申请'
        break
      case '10':
        to.meta.activeMenu = '/stateManage/handleApply'
        to.meta.title = '设备处置申请'
        break
    }
  }
  next()
})

// 跳转详情页
const detail = (row: any) => {
  sessionStorage.setItem('workbenchApproveParams', JSON.stringify(row))
  if (row.messageTitle === '结果通知') {
    changeWorkbenchApproveStatus({
      id: row.id,
      status: 1,
    })
  }
  // else {
  useChangePage($router, formUrl[row.formId], row)
  // }
}

onMounted(async () => {
  await getDict() // 获取字典
  fetchData(true) // 获取数据
})
</script>

<template>
  <!-- 布局 -->
  <app-container>
    <search-area :need-clear="true" @search="searchList" @clear="reset">
      <search-item>
        <el-select
          v-model.trim="listQuery.messageSourceModule"
          clearable
          placeholder="来源模块"
          size="default"
        >
          <el-option
            v-for="item in messageSourceModuleList"
            :key="item.id"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </search-item>
      <search-item>
        <el-select
          v-model.trim="listQuery.status"
          placeholder="处理状态"
        >
          <el-option
            v-for="item in statusList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </search-item>
      <search-item>
        <el-date-picker
          v-model="dateRange"
          class="short-input"
          type="daterange"
          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>
      <normal-table
        :data="list" :total="total" :columns="columns" :query="listQuery" :list-loading="loadingTable"
        @change="changePage"
      >
        <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" fixed="right" width="90">
            <template #default="{ row }">
              <el-button size="small" link type="primary" @click="detail(row)">
                详情
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>
