<template>
  <div class="card">
    <div class="panel-title">
      <span class="title-dot"></span>
      <span>任务列表</span>
    </div>
    <div class="panel-body table-body">
      <el-table
        ref="tableRef"
        :data="taskRows"
        class="task-table"
        :show-header="true"
        :stripe="false"
        :border="false"
        :highlight-current-row="false"
      >
        <el-table-column prop="code" label="编号" width="100" show-overflow-tooltip />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="type" label="类型" />
        <el-table-column label="完成状态">
          <template #default="scope">
            <el-tag
              v-if="scope.row.finishStatusLabel"
              class="status-tag"
              size="small"
              :disable-transitions="true"
              :hit="false"
              :round="true"
              :type="scope.row.finishStatusType || 'info'"
            >
              {{ scope.row.finishStatusLabel }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="结果">
          <template #default="scope">
            <div class="status-cell">
              <el-tag
                v-if="scope.row.resultStatusLabel !== '-'"
                class="status-tag"
                size="small"
                :disable-transitions="true"
                :hit="false"
                :round="true"
                :type="scope.row.resultStatusType || 'info'"
              >
                {{ scope.row.resultStatusLabel }}
              </el-tag>
              <span v-else>-</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import type { ElTable } from 'element-plus'
import { DashboardApi, DashboardTaskItem } from '@/api/dashboard'

interface TaskRow {
	id: string
	code: string
	name: string
	type: string
	finishStatusLabel: string
	resultStatusLabel: string
	finishStatusType: '' | 'success' | 'warning' | 'danger' | 'info'
	resultStatusType: '' | 'success' | 'warning' | 'danger' | 'info'
}

const route = useRoute()
const orgId = route.query.orgId

const taskRows = ref<TaskRow[]>([])
const tableRef = ref<InstanceType<typeof ElTable> | null>(null)
let scrollTimer: number | undefined

const mapItemToRow = (item: DashboardTaskItem, index: number): TaskRow => {
	const resultStatus = Number(item.resultStatus) || 0
	const finishCode = String(item.finishStatus ?? '').trim()
	let finishStatusLabel = item.finishStatus
	let finishStatusType: TaskRow['finishStatusType'] = ''
	if (finishCode === '0') finishStatusLabel = '待完成'
	else if (finishCode === '1') finishStatusLabel = '已完成'
	else if (finishCode === '2') finishStatusLabel = '已取消'
	if (finishCode === '0') finishStatusType = 'warning'
	else if (finishCode === '1') finishStatusType = 'success'
	else if (finishCode === '2') finishStatusType = 'info'
	let resultStatusLabel = '-'
	let resultStatusType: TaskRow['resultStatusType'] = ''
	if (resultStatus === 1) {
		resultStatusLabel = '通过'
		resultStatusType = 'success'
	} else if (resultStatus === 2) {
		resultStatusLabel = '不通过'
		resultStatusType = 'danger'
	}
	return {
		id: `${item.code || 'task'}-${index}`,
		code: item.code,
		name: item.name,
		type: item.type,
		finishStatusLabel,
		resultStatusLabel,
		finishStatusType,
		resultStatusType
	}
}

const loadTaskList = async () => {
	try {
		const res = await DashboardApi.getAllTaskList({ orgId })
		const payload = (res && typeof res === 'object' && 'data' in res ? (res as any).data : res) as
			| DashboardTaskItem[]
			| null
		if (!payload || !Array.isArray(payload)) {
			taskRows.value = []
			return
		}
		taskRows.value = payload.map(mapItemToRow)
	} catch (error) {
		console.error(error)
		taskRows.value = []
	}
}

const startAutoScroll = () => {
	const el = tableRef.value?.$el as HTMLElement | undefined
	if (!el) return
	const tbody = el.querySelector('tbody') as HTMLElement | null
	if (!tbody) return
	const rows = tbody.querySelectorAll('tr')
	if (!rows || rows.length <= 8) return
	scrollTimer = window.setInterval(() => {
		const currentBody = (tableRef.value?.$el as HTMLElement | undefined)?.querySelector('tbody') as
			HTMLElement | null
		if (!currentBody) return
		const first = currentBody.firstElementChild as HTMLElement | null
		if (!first) return
		first.style.transition = 'all 0.35s'
		first.style.transform = 'translateY(-36px)'
		first.style.opacity = '0'
		window.setTimeout(() => {
			const bodyAgain = (tableRef.value?.$el as HTMLElement | undefined)?.querySelector('tbody') as
				HTMLElement | null
			if (!bodyAgain || !first.parentElement) return
			first.style.transition = 'none'
			first.style.transform = 'translateY(0)'
			first.style.opacity = '1'
			bodyAgain.appendChild(first)
		}, 360)
	}, 5000)
}

onMounted(async () => {
	await loadTaskList()
	startAutoScroll()
})

onUnmounted(() => {
	if (scrollTimer) {
		clearInterval(scrollTimer)
		scrollTimer = undefined
	}
})
</script>

<style scoped>
.card {
  position: relative;
  display: flex;
  height: 100%;
  min-height: 0;
  overflow: hidden;
  background: linear-gradient(135deg, rgb(15 23 42 / 96%), rgb(15 23 42 / 88%));
  border: 1px solid rgb(30 64 175 / 85%);
  border-radius: 8px;
  box-shadow:
    0 18px 45px rgb(15 23 42 / 95%),
    0 0 0 1px rgb(15 23 42 / 100%),
    inset 0 0 0 1px rgb(56 189 248 / 5%);
  flex-direction: column;
}

.card::before,
.card::after {
  position: absolute;
  width: 12px;
  height: 12px;
  pointer-events: none;
  border: 1px solid rgb(56 189 248 / 75%);
  border-radius: 2px;
  content: "";
  opacity: 0.6;
}

.card::before {
  top: -1px;
  left: -1px;
  border-right: none;
  border-bottom: none;
}

.card::after {
  right: -1px;
  bottom: -1px;
  border-top: none;
  border-left: none;
}

.panel-title {
  display: flex;
  padding: 10px 12px;
  font-size: 16px;
  font-weight: 900;
  color: #e5f0ff;
  border-bottom: 1px solid rgb(41 54 95 / 90%);
  align-items: center;
  gap: 10px;
}

.title-dot {
  width: 10px;
  height: 10px;
  border: 1px solid rgb(56 189 248 / 95%);
  border-radius: 50%;
  box-shadow: 0 0 12px rgb(56 189 248 / 45%);
}

.panel-body {
  flex: 1;
  min-height: 0;
  padding: 10px 12px;
}

.table-body {
  padding: 0;
  overflow: auto hidden;
}

.task-table {
  /* Element Plus Table Variables Override */
  --el-table-bg-color: transparent;
  --el-table-tr-bg-color: transparent;
  --el-table-header-bg-color: transparent;
  --el-table-text-color: #e5f0ff;
  --el-table-header-text-color: #22d3ee;
  --el-table-row-hover-bg-color: rgb(56 189 248 / 12%);
  --el-table-border-color: rgb(30 64 175 / 30%);

  width: 100%;
  min-width: 450px;
  font-size: 12px;
  background-color: transparent !important;
}

/* Ensure inner wrapper is transparent */
.task-table :deep(.el-table__inner-wrapper) {
  background-color: transparent !important;
}

/* Remove bottom border line */
.task-table :deep(.el-table__inner-wrapper::before) {
  display: none;
}

/* 横向滚动条样式，贴合深色大屏风格，仅在任务列表区域生效 */
.table-body::-webkit-scrollbar {
  height: 6px;
}

.table-body::-webkit-scrollbar-track {
  background: rgb(15 23 42 / 90%);
  border-radius: 999px;
}

.table-body::-webkit-scrollbar-thumb {
  background: linear-gradient(to right, rgb(56 189 248 / 85%), rgb(59 130 246 / 80%));
  border-radius: 999px;
  box-shadow: 0 0 10px rgb(56 189 248 / 40%);
}

/* Header Styles */
.task-table :deep(thead th.el-table__cell) {
  padding: 8px 0;
  font-weight: 700;
  background: radial-gradient(circle at 0 0, rgb(56 189 248 / 18%), transparent 90%) !important;
  border-bottom: 1px solid rgb(51 65 85 / 90%) !important;
}

/* Cell Styles */
.task-table :deep(td.el-table__cell) {
  padding: 8px 0;
  white-space: nowrap;
  background-color: transparent !important;
  border-bottom: 1px solid rgb(30 64 175 / 30%) !important;
}

/* Ensure code, name, type columns show ellipsis */
.task-table :deep(td.el-table__cell:nth-child(1) .cell),
.task-table :deep(td.el-table__cell:nth-child(2) .cell),
.task-table :deep(td.el-table__cell:nth-child(3) .cell) {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* Ensure finishStatus and result columns DO NOT show ellipsis */
.task-table :deep(td.el-table__cell:nth-child(4) .cell),
.task-table :deep(td.el-table__cell:nth-child(5) .cell) {
  overflow: visible;
  text-overflow: clip;
  white-space: nowrap;
}

/* Hover Styles */
.task-table :deep(tbody tr:hover > td.el-table__cell) {
  background-color: rgb(56 189 248 / 10%) !important;
}

.status-cell {
  font-weight: 800;
}

.status-tag {
	min-width: 60px;
	padding: 0 10px;
	text-align: center;
	border-radius: 999px;
}
</style>
