<!--
  Description: 升级任务管理列表页
  Author: 李亚光
  Date: 2025-05-28
 -->
<script name="DeviceTaskManage" lang="ts" setup>
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { getProductListPage } from '@/api/basic/product'
import { getTaskListPage, deleteTask } from '@/api/basic/task'
import { getDictByCode } from '@/api/system/dict'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
const dataList = ref([])
const total = ref(0)
const loadingTable = ref(true)
const searchQuery = ref({
  productId: '',
  upgradeVersionName: '',
  taskName: '',
  status: '',
  offset: 1,
  limit: 20
})
// 表头
const columns = ref<TableColumn[]>([
  { text: '任务名称', value: '', align: 'center' },
  { text: '产品名称', value: '', align: 'center' },
  { text: '升级包名称', value: '', align: 'center' },
  { text: '升级包版本号', value: '', align: 'center' },
  { text: '升级包版本描述', value: '', align: 'center' },
  { text: '任务状态', value: '', align: 'center' },
  { text: '创建人', value: '', align: 'center' },
  { text: '创建时间', value: '', align: 'center' },
])
// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    searchQuery.value.offset = 1
  }
  getTaskListPage(searchQuery.value).then((response) => {
    dataList.value = response.data.rows
    total.value = parseInt(response.data.total)
    calcTableHeight()
    loadingTable.value = false
  }).catch(() => {
    loadingTable.value = false
  })
}
fetchData()
// 重置查询
const reset = () => {
  searchQuery.value = {
    productId: '',
    upgradeVersionName: '',
    taskName: '',
    status: '',
    offset: 1,
    limit: 20
  }
  fetchData(true)
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    searchQuery.value.limit = val.size
  }
  if (val && val.page) {
    searchQuery.value.offset = val.page
  }
  fetchData(true)
}
// 删除任务
const deleteTaskById = (row: any) => {
  ElMessageBox.confirm(`是否删除任务 ${row.taskName}`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteTask(row.id).then((res) => {
      if (res.code === 200) {
        ElMessage.success(`任务 ${row.taskName} 删除成功`)
        fetchData()
      }
      else {
        ElMessage.error(`任务 ${row.taskName} 删除失败: ${res.message}`)
      }
    })
  })
}
// 获取字典相关
const productLoading = ref(false)
const productList = ref<any[]>([]) // 产品列表
// 获取字典相关
const taskLoading = ref(false)
const taskStatusList = ref<any[]>([]) // 任务状态列表
const fetchDict = () => {
  // 产品列表
  productLoading.value = true
  getProductListPage({ limit: 9999, offset: 1 }).then(res => {
    productList.value = res.data.rows
    productLoading.value = false
  }).catch(() => {
    productLoading.value = false
  })
  // 任务状态
  taskLoading.value = true
  getDictByCode('taskStatus').then((response) => {
    taskStatusList.value = response.data
    taskLoading.value = false
  }).catch(() => {
    taskLoading.value = false
  })
  //
}
fetchDict()

const tableHeight = ref(400)
const calcTableHeight = () => {
  // 顶部高度
  const topHeight = 110
  // app-container的 padding距离
  const appPadding = 20
  // 查询组件的高度
  const searchDiv = document.getElementById('search-div-id')
  const searchHeight = searchDiv ? searchDiv.clientHeight : 0
  // 表格顶部的文字提示高度
  const tableTopHeight = 32 + 10
  // 表格表头
  const tableHeaderHeight = 40
  // 分页器的高度
  const tablePaginationHeight = 40
  // 判断数据长度
  const height = window.innerHeight - topHeight - appPadding - searchHeight - tableTopHeight - tableHeaderHeight - tablePaginationHeight
  if (dataList.value.length * 40 >= height) {
    tableHeight.value = height
  }
  else {
    tableHeight.value = dataList.value.length ? (dataList.value.length + 1) * 40 : 200
  }
}
onBeforeUnmount(() => {
  window.removeEventListener('resize', calcTableHeight)
})
onMounted(() => {
  window.addEventListener('resize', calcTableHeight)
})
</script>

<template>
  <app-container>
    <search-area :need-clear="true" @search="fetchData" @clear="reset">
      <search-item>
        <el-input v-model="searchQuery.taskName" placeholder="任务名称" clearable />
      </search-item>
      <search-item>
        <el-select v-model="searchQuery.productId" placeholder="选择产品名称" clearable style="width: 192px;"
          :loading="productLoading">
          <el-option v-for="dict in productList" :key="dict.id" :value="dict.id" :label="dict.name" />
        </el-select>
      </search-item>
      <search-item>
        <el-input v-model="searchQuery.upgradeVersionName" placeholder="升级包名称" clearable />
      </search-item>
      <search-item>
        <el-select v-model="searchQuery.status" placeholder="选择任务状态" clearable style="width: 192px;"
          :loading="taskLoading">
          <el-option v-for="dict in taskStatusList" :key="dict.id" :value="dict.id" :label="dict.name" />
        </el-select>
      </search-item>
    </search-area>
    <!-- 表格数据展示 -->
    <table-container title="任务列表">
      <!-- 表格区域 -->
      <normal-table :data="dataList" :columns="columns" :total="total" :query="searchQuery" :list-loading="loadingTable"
        @change="changePage" :height="tableHeight">
        <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 fixed="right" label="操作" align="center" width="90">
            <template #default="{ row }">
              <el-button size="small" type="primary" link>
                查看
              </el-button>
              <el-button size="small" type="danger" link @click="deleteTaskById(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>
