<template>
  <div class="task-management-wrap">
    <EdfsWrap class="task-table" title="任务列表">
      <template #title-right>
        <div class="task-table-title">
          <EdfsButton
            type="primary"
            inner-text="创建升级任务"
            :icon="createIcon"
            @click="addTask"
          />
        </div>
      </template>
      <edfs-table
        :data="dataList"
        :highlight-current-row="true"
        ref="tableRef"
        row-class-name="row"
        :page-size="pageSize"
        :page-total="pageTotal"
        class="table"
        :current-page="pageIndex"
        @pageCurrentChange="handleJump"
      >
        <template v-for="(col, idx) in tableColumns" :key="idx">
          <el-table-column
            v-if="col.prop === 'createTime'"
            :label="col.label"
            :prop="col.prop"
            :min-width="col.width"
          >
            <template #default="scope">
              {{ dayjs(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column
            v-else-if="col.prop === 'status'"
            :label="col.label"
            :prop="col.prop"
            :min-width="col.width"
          >
            <template #default="scope">
              {{ taskStatusMap[scope.row.status] }}
            </template>
          </el-table-column>
          <el-table-column
            v-else-if="col.prop === 'executeTime'"
            :label="col.label"
            :prop="col.prop"
            :min-width="col.width"
          >
            <template #default="scope">
              {{ dayjs(scope.row.executeTime).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column
            v-else-if="col.prop === 'deviceUpgradeDetail'"
            :label="col.label"
            :prop="col.prop"
            :min-width="col.width"
          >
            <template #default="scope">
              <div>
                <div>升级中：{{ scope.row.processingCount }}</div>
                <div>失败数量: {{ scope.row.failCount }}</div>
                <div>升级完成: {{ scope.row.successCount }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            v-else
            :label="col.label"
            :prop="col.prop"
            :min-width="col.width"
          />
        </template>

        <el-table-column label="操作" min-width="8%">
          <template #default="scope">
            <EdfsButton
              type="primary"
              link
              v-if="scope.row.status === 1 || scope.row.status === 2"
              inner-text="详情"
              @click="onDetails(scope.row)"
            />
          </template>
        </el-table-column>
      </edfs-table>
    </EdfsWrap>
    <createTaskDlg :isShow="isShowDlg" @on-close="onClose" @on-save="onSave" />
    <detailsDrawer
      ref="detailsRef"
      :rowData="rowData"
      :taskMap="taskMap"
      v-model="isShowDetails"
      v-if="isShowDetails"
    />
  </div>
</template>
<script setup lang="ts">
import {
  addListener,
  removeListener,
  type SocketMsgListener,
} from '@/tools/event/socketEvent'
import { tableColumns, taskStatusMap } from './utils'
import EdfsButton from '@/components/dashboard/Edfs-button/index.vue'
import EdfsTable from '@/components/dashboard/Edfs-table/index.vue'
import EdfsWrap from '@/components/dashboard/Edfs-wrap.vue'
import { useIcon } from '@/utils/useIcon'
import createTaskDlg from './components/create-task-dlg.vue'
import detailsDrawer from './components/details-drawer.vue'
import { isResError, useMessage } from '@/hooks/useMessage.js'
import dayjs from 'dayjs'
import { getTaskList } from '@/api/module/eam/device/task'

const message = useMessage()

const createIcon = useIcon({ icon: 'gravity-ui:plus' })
const tableRef = ref<any>(null)
const dataList = ref<any>([])
const pageIndex = ref(1)
const pageSize = ref()
const pageTotal = ref(0)
const pageJump = ref(1)

type DeviceMap = Map<number, any>
type TaskMap = Map<number, DeviceMap>

const taskMap: TaskMap = new Map<number, DeviceMap>()
async function loadData() {
  if (!pageSize.value) {
    pageSize.value = tableRef.value.getSize()
  }
  const res = await getTaskList({
    pageNo: pageIndex.value,
    pageSize: pageSize.value,
  })
  if (isResError(res)) return
  const { list, total } = res.data
  dataList.value = list
  pageTotal.value = total

  updateTaskData()
}

watch(pageIndex, () => {
  pageJump.value = pageIndex.value
  loadData()
})

function handleJump(page: number) {
  pageIndex.value = page
}

const isShowDlg = ref(false)
function addTask() {
  isShowDlg.value = true
}

function onClose() {
  isShowDlg.value = false
}

function onSave() {
  isShowDlg.value = false
  loadData()
}

const rowData = ref<any>({})
const isShowDetails = ref(false)
async function onDetails(row: any) {
  rowData.value = row
  isShowDetails.value = true
}

onMounted(async () => {
  await loadData()
  addListener(socketMsgListener)
})

onBeforeUnmount(() => {
  removeListener(socketMsgListener)
})
const detailsRef = ref<any>(null)

const tasksStatusMap = new Map()
const socketMsgListener: SocketMsgListener = {
  onCmdPost: function (type: string, stationId: number, data?: any, time?: string) {
    if (type === 'upgrade') {
      const { deviceSn, taskId } = data
      if (!taskId || !deviceSn) return
      let deviceMap = taskMap.get(taskId)
      if (!deviceMap) {
        deviceMap = new Map<number, any>()
        taskMap.set(taskId, deviceMap)
      }
      deviceMap.set(deviceSn, data)

      if (detailsRef.value && rowData.value?.id) {
        const taskId = rowData.value?.id
        let taskData = taskMap.get(taskId)
        const dataArray = taskData ? Array.from(taskData.values()) : []
        detailsRef.value.updateData(dataArray)
      }
    }
    if (type === 'upgrade-task' && data.id) {
      tasksStatusMap.set(data.id, data)
      updateTaskData()
    }
  },
}

function updateTaskData() {
  for (const data of dataList.value) {
    const taskData = tasksStatusMap.get(data.id)
    if (!taskData) continue
    data.status = taskData.status
    data.processingCount = taskData.processingCount
    data.failCount = taskData.failCount
    data.successCount = taskData.successCount
  }
}

// let a = [
//   {
//     type: 'upgrade',
//     stationId: 1,
//     time: 1726129158000,
//     data: {
//       id: 1,
//       taskId: 32,
//       deviceId: 1,
//       node: 0,
//       subNode: 10,
//       reason: null,
//       deviceSn: '4',
//       tenantId: 162,
//       createTime: 1725533993000,
//       updateTime: 1725533993000,
//       creator: '145',
//       updater: '145',
//       deleted: false,
//     },
//   },
//   {
//     type: 'upgrade',
//     stationId: 1,
//     time: 1726129158000,
//     data: {
//       id: 1,
//       taskId: 32,
//       deviceId: 1,
//       node: 1,
//       subNode: 10,
//       reason: 'null',
//       deviceSn: '5',
//       tenantId: 162,
//       createTime: 1725533993000,
//       updateTime: 1725533993000,
//       creator: '145',
//       updater: '145',
//       deleted: false,
//     },
//   },
//   {
//     type: 'upgrade',
//     stationId: 1,
//     time: 1726129158000,
//     data: {
//       id: 1,
//       taskId: 32,
//       deviceId: 1,
//       node: 2,
//       subNode: 10,
//       reason: 'null',
//       deviceSn: '6',
//       tenantId: 162,
//       createTime: 1725533993000,
//       updateTime: 1725533993000,
//       creator: '145',
//       updater: '145',
//       deleted: false,
//     },
//   },
//   {
//     type: 'upgrade',
//     stationId: 1,
//     time: 1726129158000,
//     data: {
//       id: 1,
//       taskId: 1,
//       deviceId: 1,
//       node: 3,
//       subNode: 10,
//       reason: null,
//       deviceSn: '6',
//       tenantId: 162,
//       createTime: 1725533993000,
//       updateTime: 1725533993000,
//       creator: '145',
//       updater: '145',
//       deleted: false,
//     },
//   },
//   {
//     type: 'upgrade',
//     stationId: 1,
//     time: 1726129158000,
//     data: {
//       id: 1,
//       taskId: 1,
//       deviceId: 1,
//       node: 1,
//       subNode: 10,
//       reason: null,
//       deviceSn: '6',
//       tenantId: 162,
//       createTime: 1725533993000,
//       updateTime: 1725533993000,
//       creator: '145',
//       updater: '145',
//       deleted: false,
//     },
//   },
// ]
// function test(type: string, stationId: number, data?: any, time?: number) {
//   if (type === 'upgrade') {
//     const { deviceSn, taskId } = data
//     if (!taskId || !deviceSn) return
//     // 存储设备状态
//     let deviceMap = taskMap.get(taskId)
//     if (!deviceMap) {
//       deviceMap = new Map<number, any>()
//       taskMap.set(taskId, deviceMap)
//     }
//     deviceMap.set(deviceSn, data)

//     if (detailsRef.value && rowData.value?.id) {
//       const taskId = rowData.value?.id
//       let taskData = taskMap.get(taskId)
//       const dataArray = taskData ? Array.from(taskData.values()) : []
//       detailsRef.value.updateData(dataArray)
//     }
//   }
// }

// setInterval(() => {
//   for (const item of a) {
//     test(item.type, item.stationId, item.data, item.time)
//   }
// }, 1000)
</script>

<style scoped lang="scss">
.task-management-wrap {
  width: 100%;
  height: 100%;
  .task-table {
    height: 100%;
    box-sizing: border-box;

    background: #fff;
    padding-bottom: 0;
    .table {
      height: 100%;
      width: 100%;
    }
  }
}
</style>
