<template>
  <div v-if="showMissions" class="mission-container">
    <el-row :gutter="20" class="grid-container">
      <el-col v-for="mission in currentPageData" :key="mission.id" :xs="24" :sm="12" :md="8" :lg="6">
        <el-tooltip :content="mission.description" placement="bottom" popper-class="mission-tooltip">
          <el-card class="mission-card" @click="handleCardClick(mission.id)">
            <!-- 状态指示灯 -->
            <div class="status-indicator">
              <el-tooltip effect="dark" :content="statusText[mission.status]" placement="top">
                <div class="status-light" :style="{ backgroundColor: statusColor[mission.status] }" />
              </el-tooltip>
            </div>
            <!-- 加密状态标签 -->
            <div v-if="mission.encrypted" class="encrypted-tag">
              <el-icon color="#67C23A" :size="18">
                <Lock />
              </el-icon>
              <span class="encrypted-text">已加密</span>
            </div>

            <div class="card-content">
              <h3 class="title">{{ mission.name }}</h3>
              <div class="meta">
                <el-icon>
                  <Calendar />
                </el-icon>
                <span>{{ formatTime(mission.createTime) }}</span>
              </div>

              <div class="stats">
                <!-- 节点行 -->
                <div class="stat-item node-row">
                  <div class="label-box">
                    <span class="label">节点</span>
                  </div>
                  <div class="node-stats">
                    <span class="node-count">S:{{ mission.nodesInfo.S }}</span>
                    <span class="node-count">D:{{ mission.nodesInfo.D }}</span>
                    <span class="node-count">I:{{ mission.nodesInfo.I }}</span>
                  </div>
                </div>

                <!-- 边行 -->
                <div class="stat-item edge-row">
                  <div class="label-box">
                    <span class="label">边</span>
                  </div>
                  <span class="edge-count">{{ mission.edgesInfo.num }}</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-tooltip>
      </el-col>
    </el-row>
    <!-- 分页控件 -->
    <el-pagination background layout="total, sizes, prev, pager, next" :page-sizes="[8, 16, 24]"
      :current-page="pagination.currentPage" :page-size="pagination.pageSize" :total="pagination.total"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" class="pagination" />
    <!-- 解密文件密码输入框 -->
    <el-dialog v-model="passwordDialogVisible" title="存在加密文件,需解密后进行下一步操作" width="500px">
      <div class="encrypted-files">
        <div v-for="(file, index) in encryptedFiles" :key="index" class="file-item">
          <div class="file-header">
            <div class="file-type-tag" :class="file.content">
              {{ file.content === 'node' ? '节点文件' : '边文件' }}
            </div>
            <el-icon :color="file.content === 'node' ? '#409EFF' : '#E6A23C'" class="file-icon">
              <component :is="file.content === 'node' ? 'User' : 'Connection'" />
            </el-icon>
          </div>
          <div class="input-wrapper">
            <el-input v-model="passwords[index]" type="password" clearable :placeholder="`输入${file.name}的解密密码`"
              show-password />
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePasswordConfirm">确认解密</el-button>
      </template>
    </el-dialog>
  </div>

  <div v-else>
    <router-view></router-view>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, inject, onActivated, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Calendar, User, Connection, Lock } from '@element-plus/icons-vue'
import { postData, getData } from '@/api/axios'
import { ElCalendar, ElMessage, ElMessageBox } from 'element-plus'

// 保存选中的mission
const useAnalyzeInfo = inject('analyzeInfo')
// 任务数据
const missions = ref([])
// 任务状态对应颜色
const statusColor = {
  'init': '#ff4d4f',  // 未开始或暂停、停止
  'pause': '#ff4d4f',  // 未开始或暂停、停止
  'calculating': '#faad14',  // 计算中
  'done': '#52c41a'   // 已完成
}
// 任务状态提示语句
const statusText = {
  'init': '尚未执行计算',
  'pause': '计算暂停中',
  'calculating': '计算进行中',
  'done': '计算已完成',
}
// 用于控制点击后跳转到plan页面
const showMissions = ref(false)

// 加密文件解密相关变量
const passwordDialogVisible = ref(false)
const encryptedFiles = ref([])
const passwords = ref([])

// 分页配置
const pagination = ref({
  currentPage: 1,
  pageSize: 8,
  total: missions.value.length
})

// 当前页数据计算
const currentPageData = computed(() => {
  const start = (pagination.value.currentPage - 1) * pagination.value.pageSize
  return missions.value.slice(start, start + pagination.value.pageSize)
})

// 分页事件处理
const handleSizeChange = (size) => {
  pagination.value.pageSize = size
  pagination.value.currentPage = 1
}

const handleCurrentChange = (page) => {
  pagination.value.currentPage = page
}

// 时间格式化
const formatTime = (isoString) => {
  return new Date(isoString).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 路由跳转
const router = useRouter()

const handleCardClick = async (id) => {
  const mission = missions.value.find(m => m.id === id)
  encryptedFiles.value = []
  if (mission.encrypted) {
    try {
      const response = await getData('/encryptfile/', { missionId: mission.id })
      encryptedFiles.value = response.data.map(file => ({
        id: file.id,
        name: file.name,
        content: file.content,
      }))
      passwords.value = new Array(encryptedFiles.value.length).fill('')
      // 准备mission，供解密请求使用，但是不跳转
      preparePlan(mission)
      passwordDialogVisible.value = true
      return // 中断后续跳转
    } catch (error) {
      ElMessage.error('获取加密文件失败')
      console.error(error)
    }
  } else {
    // 没有加密直接进入plan，如有加密，必须在解密失败时提前退出
    preparePlan(mission)
    if (mission.status === "init") {
      // 初始状态，应进入流程规划
      // 切换显示plan的routeview
      router.push(`/dashboard/analyze/plan`)
    } else {
      // 否则进入calculate界面，可查看计算过程或结果
      router.push(`/dashboard/analyze/plan/calculate`)
    }
    showMissions.value = false
  }
}

// 解密后跳转处理逻辑
const handlePasswordConfirm = async () => {
  try {
    const decryptRequests = encryptedFiles.value.map((file, index) =>
      postData('/encryptfile/', {
        fileId: file.id,
        action: 'verify',
        password: passwords.value[index]
      })
    )
    const results = await Promise.all(decryptRequests)
    console.log(results)
    if (results.every(r => r.status === "success")) {
      ElMessage.success('解密成功')
      passwordDialogVisible.value = false
      // 执行原有跳转逻辑
      const mission = missions.value.find(m => m.id === useAnalyzeInfo.analyzeInfo.value.mission.id)
      if (mission.status === "init") {
        router.push(`/dashboard/analyze/plan`)
      } else {
        router.push(`/dashboard/analyze/plan/calculate`)
      }
      showMissions.value = false
    } else {
      ElMessage.error('部分文件密码错误')
    }
  } catch (error) {
    ElMessage.error('解密请求失败')
    console.error(error)
  }
}

const preparePlan = (mission) => {
  useAnalyzeInfo.analyzeInfo.value.nodeFile.amount = mission.nodesInfo.S + mission.nodesInfo.D + mission.nodesInfo.I
  useAnalyzeInfo.analyzeInfo.value.nodeFile.sNodes = mission.nodesInfo.S
  useAnalyzeInfo.analyzeInfo.value.nodeFile.dNodes = mission.nodesInfo.D
  useAnalyzeInfo.analyzeInfo.value.nodeFile.iNodes = mission.nodesInfo.I

  useAnalyzeInfo.analyzeInfo.value.edgeFile.amount = mission.edgesInfo.num
  useAnalyzeInfo.analyzeInfo.value.mission = {
    id: mission.id,
    name: mission.name,
    createTime: mission.createTime,
    status: mission.status,
  }
  console.log(useAnalyzeInfo.analyzeInfo.value)
  // 将获取到的数据写入页面缓存，防止刷新丢失
  sessionStorage.setItem('analyze-info', JSON.stringify(useAnalyzeInfo.analyzeInfo.value))
}

//加载数据
const loadMissions = async () => {
  missions.value = [];
  showMissions.value = true;
  try {
    const response = await getData('/missions/');
    missions.value = response.data.map(mission => ({
      id: mission.id,
      name: mission.name,
      createTime: mission.createTime,
      encrypted: mission.encrypted,
      nodesInfo: mission.nodesInfo,
      edgesInfo: mission.edgesInfo,
      status: mission.status,
      // 需要后续完善描述输入
      description: mission.description,
    })).sort((a, b) => b.id - a.id);
    pagination.value.total = missions.value.length;
  } catch (error) {
    console.error(error);
    ElMessage.error("获取任务列表错误");
  }
}

const route = useRoute();
// 监听路由变化
watch(
  () => route.path,
  (newPath) => {
    if (newPath === '/dashboard/view' || newPath === '/dashboard/taskfile') {
      showMissions.value = true;
    }
  },
  { immediate: true }
);

// 首次加载
onMounted(loadMissions);
// 通过后退按钮返回页面时重新加载
onActivated(loadMissions);

</script>

<style scoped lang="scss">
.mission-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  background: #f8fafc;

  .grid-container {
    min-height: 60vh;
  }

  .mission-card {

    position: relative;
    border: 1px solid #e2e8f0;
    border-radius: 12px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    background: white;
    cursor: pointer;
    overflow: hidden;

    &:hover {
      transform: translateY(-3px);
      box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.08);

      .title {
        color: var(--el-color-primary);
      }
    }

    .label-box {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      width: 48px;
      height: 24px;
      background: #f1f5f9;
      border: 1px solid #e2e8f0;
      border-radius: 4px;
      margin-right: 8px;

      .label {
        color: #475569;
        font-size: 0.85rem;
        font-weight: 500;
        transform: scale(0.9);
      }
    }

    .status-indicator {
      position: absolute;
      right: 16px;
      top: 14px;
      z-index: 2;

      .status-light {
        width: 20px;
        height: 20px;
        border-radius: 50%;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        position: relative;

        &::after {
          content: '';
          position: absolute;
          inset: 0;
          border-radius: 50%;
          background: inherit;
          filter: brightness(1.2);
          opacity: 0.3;
        }
      }
    }

    .encrypted-tag {
      position: absolute;
      right: 44px;
      top: 12px;
      top: 16px;
      z-index: 2;
      display: flex;
      align-items: center;
      gap: 4px;
      background: rgba(103, 194, 58, 0.1);
      border-radius: 4px;
      backdrop-filter: blur(2px);

      .encrypted-text {
        color: #67C23A;
        font-size: 0.8rem;
        font-weight: 500;
        letter-spacing: 0.5px;
      }

      .el-icon {
        filter: drop-shadow(0 1px 1px rgba(0, 0, 0, 0.1));
      }
    }

    .card-content {

      .title {
        font-family: "Microsoft YaHei", system-ui;
        font-weight: 600;
        color: #1e293b;
        margin: 0 0 8px; // 减少上下间距
        font-size: 1.15rem;
        line-height: 1.3;
        position: relative;
        padding-left: 24px;

        &::before {
          content: '📌';
          position: absolute;
          left: -4px;
          top: -2px;
          font-size: 0.9em;
          opacity: 0.8;
        }
      }

      .meta {
        display: flex;
        align-items: center;
        margin-bottom: 12px;
        color: #64748b;
        font-size: 0.9rem;

        .el-icon {
          margin-right: 8px;
          font-size: 1.1em;
          color: #94a3b8;
        }
      }

      .stats {
        .stat-item {
          display: flex;
          align-items: center;
          margin-bottom: 8px;

          &.node-row {
            .node-stats {
              display: flex;
              gap: 12px;
              align-items: center;
            }
          }

          &.edge-row {
            .edge-count {
              color: #334155;
              font-weight: 500;
            }
          }
        }
      }
    }

    .pagination {
      margin-top: 30px;
      justify-content: center;

      ::v-deep(.el-pagination__total) {
        color: #64748b;
      }
    }
  }

  @media (max-width: 768px) {
    .mission-card {
      margin: 8px 0;

      .card-content {
        padding: 12px;

        .title {
          font-size: 1.1rem;
          padding-left: 20px;
        }

        .node-stats {
          flex-wrap: wrap;
          gap: 4px !important;

          span::after {
            display: none !important;
          }
        }
      }
    }
  }
}

.encrypted-files {
  max-height: 60vh;
  overflow-y: auto;
  padding: 10px;

  .file-item {
    display: flex;
    flex-direction: column;
    margin-bottom: 20px;
    background: #f8fafc;
    border-radius: 8px;
    padding: 12px;
    transition: all 0.2s;

    &:hover {
      background: #f1f5f9;
    }

    .file-header {
      display: flex;
      align-items: center;
      margin-bottom: 8px;
      gap: 8px;

      .file-type-tag {
        padding: 4px 10px;
        border-radius: 14px;
        font-size: 0.85rem;
        font-weight: 500;
        letter-spacing: 0.5px;

        &.node {
          background: rgba(64, 158, 255, 0.1);
          color: #409EFF;
          border: 1px solid rgba(64, 158, 255, 0.2);
        }

        &.edge {
          background: rgba(230, 162, 60, 0.1);
          color: #E6A23C;
          border: 1px solid rgba(230, 162, 60, 0.2);
        }
      }

      .file-icon {
        font-size: 18px;
        margin-left: auto;
      }
    }

    .input-wrapper {
      :deep(.el-input) {
        width: 100%;

        .el-input__wrapper {
          border-radius: 8px;
          padding: 8px 12px;
          transition: all 0.2s;

          &:hover {
            box-shadow: 0 0 0 1px var(--el-input-hover-border-color);
          }
        }
      }
    }
  }

  @media (max-width: 768px) {
    .file-item {
      padding: 8px;

      .file-type-tag {
        font-size: 0.8rem;
        padding: 3px 8px;
      }

      .file-icon {
        font-size: 16px;
      }
    }
  }
}
</style>