<script setup lang="ts">
import { computed } from 'vue';
import { ElDialog, ElProgress, ElTag, ElButton, ElEmpty, ElScrollbar } from 'element-plus';
import { 
  Loading, 
  Check, 
  Close, 
  Delete,
  ChatDotRound,
  VideoCamera,
  User,
  Upload,
  ChatLineSquare,
} from '@element-plus/icons-vue';
import { useTaskQueueStore } from '@/stores/taskQueue';
import { PLATFORMS } from '@media-manager/shared';
import type { Task, TaskType, TaskStatus } from '@media-manager/shared';
import dayjs from 'dayjs';

const taskStore = useTaskQueueStore();

// 图标映射
const iconMap: Record<TaskType, typeof ChatDotRound> = {
  sync_comments: ChatDotRound,
  sync_works: VideoCamera,
  sync_account: User,
  publish_video: Upload,
  batch_reply: ChatLineSquare,
  delete_work: Delete,
};

// 状态配置
const statusConfig: Record<TaskStatus, { text: string; type: 'info' | 'warning' | 'success' | 'danger' }> = {
  pending: { text: '等待中', type: 'info' },
  running: { text: '执行中', type: 'warning' },
  completed: { text: '已完成', type: 'success' },
  failed: { text: '失败', type: 'danger' },
  cancelled: { text: '已取消', type: 'info' },
};

// 按时间倒序排序（最新的在前）
const sortByTimeDesc = (a: Task, b: Task) => {
  const timeA = new Date(a.createdAt).getTime();
  const timeB = new Date(b.createdAt).getTime();
  return timeB - timeA;
};

// 按状态分组任务，每组内按时间倒序排列
const groupedTasks = computed(() => {
  const running = taskStore.tasks
    .filter(t => t.status === 'running')
    .sort(sortByTimeDesc);
  const pending = taskStore.tasks
    .filter(t => t.status === 'pending')
    .sort(sortByTimeDesc);
  const completed = taskStore.tasks
    .filter(t => t.status === 'completed' || t.status === 'failed' || t.status === 'cancelled')
    .sort(sortByTimeDesc);
  return { running, pending, completed };
});

function getIcon(type: TaskType) {
  return iconMap[type] || ChatDotRound;
}

function getStatusConfig(status: TaskStatus) {
  return statusConfig[status] || statusConfig.pending;
}

function getPlatformName(platform?: string): string {
  if (!platform) return '';
  return PLATFORMS[platform as keyof typeof PLATFORMS]?.name || platform;
}

function formatTime(time?: string) {
  if (!time) return '-';
  return dayjs(time).format('HH:mm:ss');
}

function handleCancel(task: Task) {
  taskStore.cancelTask(task.id);
}

function handleClose() {
  taskStore.closeDialog();
}

function handleClearCompleted() {
  taskStore.clearCompletedTasks();
}
</script>

<template>
  <ElDialog
    :model-value="taskStore.isDialogVisible"
    title="任务队列"
    width="560px"
    :close-on-click-modal="true"
    :close-on-press-escape="true"
    @close="handleClose"
  >
    <div class="task-dialog-content">
      <!-- 空状态 -->
      <ElEmpty 
        v-if="taskStore.tasks.length === 0" 
        description="暂无任务"
        :image-size="80"
      />

      <ElScrollbar v-else max-height="400px">
        <!-- 执行中的任务 -->
        <div v-if="groupedTasks.running.length > 0" class="task-group">
          <div class="task-group-title">
            <el-icon class="spin-icon"><Loading /></el-icon>
            执行中 ({{ groupedTasks.running.length }})
          </div>
          <div 
            v-for="task in groupedTasks.running" 
            :key="task.id" 
            class="task-item running"
          >
            <div class="task-header">
              <div class="task-info">
                <el-icon class="task-icon"><component :is="getIcon(task.type)" /></el-icon>
                <span class="task-title">{{ task.title }}</span>
                <el-tag v-if="task.platform" size="small" type="info" class="platform-tag">
                  {{ getPlatformName(task.platform) }}
                </el-tag>
                <el-tag v-else-if="task.accountName" size="small" type="info" class="platform-tag">
                  {{ task.accountName }}
                </el-tag>
              </div>
              <ElTag size="small" :type="getStatusConfig(task.status).type">
                {{ getStatusConfig(task.status).text }}
              </ElTag>
            </div>
            <div class="task-progress">
              <ElProgress
                :percentage="task.progress || 0"
                :stroke-width="8"
                :show-text="true"
              />
            </div>
            <div v-if="task.currentStep" class="task-step">
              {{ task.currentStep }}
            </div>
          </div>
        </div>

        <!-- 等待中的任务 -->
        <div v-if="groupedTasks.pending.length > 0" class="task-group">
          <div class="task-group-title">
            等待中 ({{ groupedTasks.pending.length }})
          </div>
          <div
            v-for="task in groupedTasks.pending"
            :key="task.id"
            class="task-item pending"
          >
            <div class="task-header">
              <div class="task-info">
                <el-icon class="task-icon"><component :is="getIcon(task.type)" /></el-icon>
                <span class="task-title">{{ task.title }}</span>
                <el-tag v-if="task.platform" size="small" type="info" class="platform-tag">
                  {{ getPlatformName(task.platform) }}
                </el-tag>
                <el-tag v-else-if="task.accountName" size="small" type="info" class="platform-tag">
                  {{ task.accountName }}
                </el-tag>
              </div>
              <div class="task-actions">
                <ElTag size="small" type="info">等待中</ElTag>
                <ElButton 
                  size="small" 
                  type="danger" 
                  text 
                  @click="handleCancel(task)"
                >
                  取消
                </ElButton>
              </div>
            </div>
            <div class="task-meta">
              创建于 {{ formatTime(task.createdAt) }}
            </div>
          </div>
        </div>

        <!-- 已完成的任务 -->
        <div v-if="groupedTasks.completed.length > 0" class="task-group">
          <div class="task-group-title">
            已完成 ({{ groupedTasks.completed.length }})
            <ElButton 
              size="small" 
              text 
              type="primary"
              @click="handleClearCompleted"
            >
              清空
            </ElButton>
          </div>
          <div 
            v-for="task in groupedTasks.completed" 
            :key="task.id" 
            class="task-item completed"
            :class="{ 'is-failed': task.status === 'failed' }"
          >
            <div class="task-header">
              <div class="task-info">
                <el-icon class="task-icon"><component :is="getIcon(task.type)" /></el-icon>
                <span class="task-title">{{ task.title }}</span>
                <el-tag v-if="task.platform" size="small" type="info" class="platform-tag">
                  {{ getPlatformName(task.platform) }}
                </el-tag>
                <el-tag v-else-if="task.accountName" size="small" type="info" class="platform-tag">
                  {{ task.accountName }}
                </el-tag>
              </div>
              <ElTag size="small" :type="getStatusConfig(task.status).type">
                {{ getStatusConfig(task.status).text }}
              </ElTag>
            </div>
            <div class="task-result">
              <template v-if="task.status === 'completed'">
                <el-icon class="result-icon success"><Check /></el-icon>
                {{ task.result?.message || '完成' }}
              </template>
              <template v-else-if="task.status === 'failed'">
                <el-icon class="result-icon failed"><Close /></el-icon>
                {{ task.error || '失败' }}
              </template>
              <template v-else>
                <el-icon class="result-icon"><Delete /></el-icon>
                已取消
              </template>
            </div>
            <div class="task-meta">
              {{ formatTime(task.completedAt) }}
            </div>
          </div>
        </div>
      </ElScrollbar>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <span class="footer-info">
          共 {{ taskStore.tasks.length }} 个任务
          <template v-if="taskStore.activeTaskCount > 0">
            ，{{ taskStore.activeTaskCount }} 个进行中
          </template>
        </span>
        <ElButton @click="handleClose">关闭</ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<style scoped lang="scss">
@use '@/styles/variables.scss' as *;

.task-dialog-content {
  min-height: 100px;
}

.task-group {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.task-group-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  font-weight: 600;
  color: $text-secondary;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid $border-light;

  .spin-icon {
    width: 14px;
    height: 14px;
    color: $primary-color;
    animation: spin 1s linear infinite;
  }
}

.task-item {
  padding: 14px 16px;
  border-radius: $radius-lg;
  background: $bg-base;
  margin-bottom: 10px;
  border: 1px solid $border-light;
  transition: all 0.2s;

  &:last-child {
    margin-bottom: 0;
  }

  &.running {
    background: $primary-color-light;
    border-color: rgba($primary-color, 0.2);
    
    .task-icon {
      color: $primary-color;
    }
  }
  
  &.pending {
    background: $bg-base;
    
    .task-icon {
      color: $text-secondary;
    }
  }

  &.completed {
    background: #fff;

    &.is-failed {
      background: $danger-color-light;
      border-color: rgba($danger-color, 0.2);
    }
  }
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.task-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.task-icon {
  width: 20px;
  height: 20px;
  color: $primary-color;
}

.task-title {
  font-size: 14px;
  font-weight: 600;
  color: $text-primary;
}

.platform-tag {
  flex-shrink: 0;
}

.task-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.task-progress {
  margin-bottom: 8px;
  
  :deep(.el-progress-bar__outer) {
    background: rgba(0, 0, 0, 0.06);
    border-radius: 4px;
  }
  
  :deep(.el-progress-bar__inner) {
    background: linear-gradient(90deg, $primary-color, #64b5f6);
    border-radius: 4px;
  }
}

.task-step {
  font-size: 12px;
  color: $text-secondary;
}

.task-result {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: $text-regular;

  .result-icon {
    width: 16px;
    height: 16px;

    &.success {
      color: $success-color;
    }

    &.failed {
      color: $danger-color;
    }
  }
}

.task-meta {
  font-size: 12px;
  color: $text-placeholder;
  margin-top: 6px;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.footer-info {
  font-size: 13px;
  color: $text-secondary;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>
