<template>
  <div class="app-container">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="16" class="stat-row">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-value">{{ statTotal }}</div>
          <div class="stat-label">待办总数</div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card stat-overdue" shadow="hover">
          <div class="stat-value">{{ statOverdue }}</div>
          <div class="stat-label">已超时</div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card stat-warning" shadow="hover">
          <div class="stat-value">{{ statWarning }}</div>
          <div class="stat-label">即将超时</div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card stat-completed" shadow="hover">
          <div class="stat-value">{{ statHandledToday }}</div>
          <div class="stat-label">今日已处理</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 任务列表 -->
    <el-card class="task-section">
      <template #header>
        <div class="section-header">
          <span>我的工作台</span>
          <el-button type="primary" size="small" @click="goToExecute">发起流程</el-button>
        </div>
      </template>

      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="待处理" name="todo">
          <div v-loading="loading" class="task-card-list">
            <el-empty v-if="!loading && filteredTodoList.length === 0" description="暂无待办任务" />
            <el-card
              v-for="row in filteredTodoList"
              :key="row.id"
              class="task-card"
              shadow="hover"
              :class="{ 'urgent': row.urgency === 1, 'overdue': row.urgency === 2 }"
            >
              <div class="task-card-main">
                <div class="task-card-header">
                  <div class="task-title">{{ row.definitionName || '未命名流程' }}</div>
                  <el-tag v-if="row.urgency === 2" type="danger" size="small" effect="dark">已超时</el-tag>
                  <el-tag v-else-if="row.urgency === 1" type="warning" size="small" effect="dark">即将超时</el-tag>
                </div>
                <div class="task-card-body">
                  <div class="task-meta"><span class="meta-label">当前节点</span><el-tag type="warning" size="small">{{ row.nodeName }}</el-tag></div>
                  <div class="task-meta"><span class="meta-label">到达时间</span><span>{{ row.createTime }}</span></div>
                  <div v-if="row.timeoutTime" class="task-meta"><span class="meta-label">剩余时间</span><span :class="{ 'text-danger': row.urgency === 2, 'text-warning': row.urgency === 1 }">{{ formatRemaining(row) }}</span></div>
                </div>
              </div>
              <div class="task-card-actions">
                <el-button circle type="success" size="small" :icon="Check" @click.stop="openQuickApprove(row, 'pass')" />
                <el-button circle type="danger" size="small" :icon="Close" @click.stop="openQuickApprove(row, 'reject')" />
                <el-button circle type="warning" size="small" :icon="Back" @click.stop="openRollback(row)" />
                <el-button circle type="info" size="small" :icon="Plus" @click.stop="handleAddSign(row)" />
                <el-button circle type="primary" size="small" :icon="View" @click.stop="handleDetail(row)" />
              </div>
            </el-card>
          </div>
        </el-tab-pane>

        <el-tab-pane label="已超时" name="overdue">
          <div v-loading="loading" class="task-card-list">
            <el-empty v-if="!loading && overdueList.length === 0" description="暂无已超时任务" />
            <TaskCard
              v-for="row in overdueList"
              :key="row.id"
              :task="row"
              @approve="openQuickApprove($event, 'pass')"
              @reject="openQuickApprove($event, 'reject')"
              @rollback="openRollback"
              @add-sign="handleAddSign"
              @detail="handleDetail"
            />
          </div>
        </el-tab-pane>

        <el-tab-pane label="即将超时" name="warning">
          <div v-loading="loading" class="task-card-list">
            <el-empty v-if="!loading && warningList.length === 0" description="暂无即将超时任务" />
            <TaskCard
              v-for="row in warningList"
              :key="row.id"
              :task="row"
              @approve="openQuickApprove($event, 'pass')"
              @reject="openQuickApprove($event, 'reject')"
              @rollback="openRollback"
              @add-sign="handleAddSign"
              @detail="handleDetail"
            />
          </div>
        </el-tab-pane>

        <el-tab-pane label="已办" name="handled">
          <div v-loading="loading" class="task-card-list">
            <el-empty v-if="!loading && handledList.length === 0" description="暂无已办任务" />
            <TaskCard
              v-for="row in handledList"
              :key="row.id"
              :task="row"
              :show-actions="false"
              @detail="handleDetail"
            />
          </div>
        </el-tab-pane>

        <el-tab-pane label="抄送" name="cc">
          <div v-loading="loading" class="task-card-list">
            <el-empty v-if="!loading && ccList.length === 0" description="暂无抄送任务" />
            <TaskCard
              v-for="row in ccList"
              :key="row.id"
              :task="row"
              @detail="handleDetail"
            />
          </div>
        </el-tab-pane>

        <el-tab-pane label="我发起的" name="mine">
          <div v-loading="loading" class="task-card-list">
            <el-empty v-if="!loading && mineList.length === 0" description="暂无我发起的流程" />
            <el-card
              v-for="row in mineList"
              :key="row.id"
              class="task-card"
              shadow="hover"
            >
              <div class="task-card-main">
                <div class="task-card-header">
                  <div class="task-title">{{ row.definitionName || '未命名流程' }}</div>
                  <el-tag :type="instanceStatusTagType(row.status)" size="small">{{ instanceStatusText(row.status) }}</el-tag>
                </div>
                <div class="task-card-body">
                  <div class="task-meta"><span class="meta-label">业务编号</span><span>{{ row.businessKey || row.instanceNo }}</span></div>
                  <div class="task-meta"><span class="meta-label">当前节点</span><span>{{ row.currentNodeName || row.currentNode || '-' }}</span></div>
                  <div class="task-meta"><span class="meta-label">发起时间</span><span>{{ row.startTime }}</span></div>
                </div>
              </div>
              <div class="task-card-actions">
                <el-button circle type="primary" size="small" :icon="View" @click.stop="handleInstanceDetail(row.id)" />
              </div>
            </el-card>
          </div>
        </el-tab-pane>
      </el-tabs>

      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        class="pagination"
        @current-change="loadData"
        @size-change="loadData"
      />
    </el-card>

    <!-- 审批抽屉 -->
    <ApprovalDrawer ref="approvalDrawerRef" @success="onApproved" />

    <!-- 加签对话框 -->
    <AddSignDialog ref="addSignDialogRef" @success="onAddSigned" />

    <!-- 流程详情抽屉 -->
    <InstanceDetail v-model="detailVisible" :instance-id="currentInstanceId" @approved="loadData" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Check, Close, Back, Plus, View } from '@element-plus/icons-vue'
import { listTodo, listHandled, listCc } from '@/api/flow/task'
import { listMyInstance } from '@/api/flow/instance'
import { todoCount } from '@/api/flow/task'
import type { FlowTask, FlowInstance } from '@/types/flow'
import { instanceStatusText, instanceStatusTagType } from '@/utils/flow'
import InstanceDetail from '@/views/flow/execute/InstanceDetail.vue'
import TaskCard from './components/TaskCard.vue'
import ApprovalDrawer from '@/components/ApprovalDrawer/index.vue'
import AddSignDialog from '@/components/AddSignDialog/index.vue'

const router = useRouter()
const activeTab = ref<'todo' | 'overdue' | 'warning' | 'handled' | 'cc' | 'mine'>('todo')
const loading = ref(false)
const todoList = ref<FlowTask[]>([])
const handledList = ref<FlowTask[]>([])
const ccList = ref<FlowTask[]>([])
const mineList = ref<FlowInstance[]>([])
const total = ref(0)
const approvalDrawerRef = ref<InstanceType<typeof ApprovalDrawer> | null>(null)
const addSignDialogRef = ref<InstanceType<typeof AddSignDialog> | null>(null)

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  processName: undefined as string | undefined
})

const statTotal = ref(0)
const statOverdue = ref(0)
const statWarning = ref(0)
const statHandledToday = ref(0)

const overdueList = computed(() => todoList.value.filter(r => r.urgency === 2))
const warningList = computed(() => todoList.value.filter(r => r.urgency === 1))
const filteredTodoList = computed(() => todoList.value.filter(r => r.urgency !== 2))

function formatRemaining(row: FlowTask) {
  if (row.urgency === 2) {
    const hours = Math.abs(Math.ceil((row.remainingMinutes ?? 0) / 60))
    return `已超时 ${hours} 小时`
  }
  const hours = Math.ceil((row.remainingMinutes ?? 0) / 60)
  return `剩余 ${hours} 小时`
}

function handleTabChange() {
  queryParams.pageNum = 1
  loadData()
}

async function loadStats() {
  try {
    statTotal.value = await todoCount()
  } catch { statTotal.value = 0 }
}

async function loadData() {
  loading.value = true
  try {
    const tab = activeTab.value
    if (tab === 'todo' || tab === 'overdue' || tab === 'warning') {
      const res = await listTodo(queryParams)
      todoList.value = res.list
      total.value = res.total
      statOverdue.value = res.list.filter(r => r.urgency === 2).length
      statWarning.value = res.list.filter(r => r.urgency === 1).length
    } else if (tab === 'handled') {
      const res = await listHandled(queryParams)
      handledList.value = res.list
      total.value = res.total
      const today = new Date().toISOString().slice(0, 10)
      statHandledToday.value = res.list.filter(r => r.endTime && r.endTime.startsWith(today)).length
    } else if (tab === 'cc') {
      const res = await listCc(queryParams)
      ccList.value = res.list
      total.value = res.total
    } else if (tab === 'mine') {
      const res = await listMyInstance(queryParams)
      mineList.value = res.list
      total.value = res.total
    }
  } finally {
    loading.value = false
  }
}

function goToExecute() {
  router.push('/approval/execute')
}

function openQuickApprove(row: FlowTask, action: 'pass' | 'reject') {
  approvalDrawerRef.value?.open(row, action)
}

function openRollback(row: FlowTask) {
  approvalDrawerRef.value?.open(row, 'rollback')
}

function onApproved() {
  loadData()
  loadStats()
}

// 详情
const detailVisible = ref(false)
const currentInstanceId = ref(0)

function handleDetail(row: FlowTask) {
  if (!row.instanceId) {
    ElMessage.warning('该任务没有关联流程实例')
    return
  }
  currentInstanceId.value = row.instanceId
  detailVisible.value = true
}

function handleInstanceDetail(id: number) {
  currentInstanceId.value = id
  detailVisible.value = true
}

function handleAddSign(row: FlowTask) {
  addSignDialogRef.value?.open(row.id)
}

function onAddSigned() {
  loadData()
}

onMounted(() => {
  loadData()
  loadStats()
})
</script>

<style scoped>
.stat-row {
  margin-bottom: 16px;
}
.stat-card {
  text-align: center;
  padding: 16px 0;
}
.stat-card .stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #409eff;
}
.stat-card .stat-label {
  margin-top: 8px;
  color: #606266;
  font-size: 14px;
}
.stat-overdue .stat-value { color: #f56c6c; }
.stat-warning .stat-value { color: #e6a23c; }
.stat-completed .stat-value { color: #67c23a; }
.task-section {
  margin-top: 16px;
}
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.task-card-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 16px;
  min-height: 200px;
}
.task-card {
  position: relative;
  overflow: hidden;
}
.task-card.overdue {
  border-left: 4px solid #f56c6c;
}
.task-card.urgent {
  border-left: 4px solid #e6a23c;
}
.task-card-main {
  padding-right: 48px;
}
.task-card-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 12px;
}
.task-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.task-card-body {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.task-meta {
  display: flex;
  align-items: center;
  font-size: 13px;
  color: #606266;
}
.meta-label {
  color: #909399;
  width: 70px;
  flex-shrink: 0;
}
.task-card-actions {
  position: absolute;
  top: 12px;
  right: 12px;
  display: flex;
  flex-direction: column;
  gap: 8px;
  opacity: 0.3;
  transition: opacity 0.2s ease;
}
.task-card:hover .task-card-actions {
  opacity: 1;
}
.task-card-actions .el-button {
  margin: 0;
}
.text-danger { color: #f56c6c; }
.text-warning { color: #e6a23c; }
.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
.drawer-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.batch-alert {
  margin-bottom: 16px;
}
.drawer-footer {
  margin-top: auto;
  padding-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
.previous-attachments {
  margin-bottom: 10px;
  padding: 10px 12px;
  background: #f5f7fa;
  border-radius: 4px;
}
.previous-title {
  font-size: 13px;
  color: #909399;
  margin-bottom: 6px;
}
.previous-item {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
  margin-bottom: 4px;
}
.previous-meta {
  font-size: 12px;
  color: #909399;
}
</style>
