<template>
  <div class="plan-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2 class="page-title">计划管理</h2>
          <el-button type="primary" @click="addPlan">添加计划</el-button>
        </div>
      </template>
      
      <el-table :data="plans" style="width: 100%" table-layout="auto" fit>
        <el-table-column prop="name" label="计划名称" />
        <el-table-column prop="description" label="计划描述" />
        <el-table-column prop="execution_type" label="执行类型">
          <template #default="scope">
            <el-tag v-if="scope.row.execution_type === 'manual'">手动</el-tag>
            <el-tag v-else-if="scope.row.execute_num === 0" type="success">自动(无限执行)</el-tag>
            <el-tag v-else type="warning">自动({{ scope.row.execute_num }}次)</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="execute_count" label="已执行次数" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0" type="danger">禁用</el-tag>
            <el-tag v-else-if="scope.row.status === 1" type="success">启用</el-tag>
            <el-tag v-else type="info">执行完毕</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="cron_expression" label="下次执行时间">
          <template #default="scope">
            {{ formatNextExecutionTime(scope.row.cron_expression) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="editPlan(scope.row)">编辑</el-button>
            <el-button size="small" @click="startPlan(scope.row)" :loading="startingPlanId === scope.row.id">
              启动
            </el-button>
            <el-button size="small" type="danger" @click="deletePlan(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 使用新的计划表单组件 -->
    <PlanForm 
      v-model:visible="dialogVisible" 
      :plan-data="currentPlan" 
      :is-edit="isEdit"
      @success="handlePlanSuccess"
      @cancel="handlePlanCancel"
    />
  </div>
</template>

<script>
import apiClient from '../api/index.js';
import PlanForm from './PlanForm.vue';
import cronParser from 'cron-parser';

export default {
  name: 'PlanList',
  components: {
    PlanForm
  },
  data() {
    return {
      plans: [],
      dialogVisible: false,
      isEdit: false,
      currentPlan: {
        id: null,
        name: '',
        description: '',
        execution_type: 'automatic',
        execute_num: 0,
        cron_expression: ''
      },
      startingPlanId: null
    };
  },
  async mounted() {
    await this.loadPlans();
  },
  methods: {
    // 加载计划列表
    async loadPlans() {
      try {
        const response = await apiClient.plans.list();
        this.plans = response.data?.plans || [];
      } catch (err) {
        this.$message.error('加载计划列表失败: ' + (err.message || '未知错误'));
        console.error('加载计划列表失败:', err);
      }
    },
    
    // 格式化下次执行时间
    formatNextExecutionTime(cronExpression) {
      if (!cronExpression) {
        return '-';
      }
      
      try {
        // 正确使用cron-parser库
        const parser = cronParser.default || cronParser;
        const interval = parser.parse(cronExpression);
        const next = interval.next().toDate();
        return next.toLocaleString('zh-CN');
      } catch (err) {
        console.error('解析cron表达式失败:', err);
        return '无效的表达式';
      }
    },
    
    addPlan() {
      this.currentPlan = {
        id: null,
        name: '',
        description: '',
        execution_type: 'automatic',
        execute_num: 0,
        cron_expression: ''
      };
      this.isEdit = false;
      this.dialogVisible = true;
    },
    
    editPlan(plan) {
      this.currentPlan = { ...plan };
      this.isEdit = true;
      this.dialogVisible = true;
    },
    
    async deletePlan(plan) {
      try {
        await this.$confirm('确认删除该计划吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        await apiClient.plans.delete(plan.id);
        this.$message.success('删除成功');
        await this.loadPlans();
      } catch (err) {
        if (err !== 'cancel') {
          this.$message.error('删除失败: ' + (err.message || '未知错误'));
        }
      }
    },
    
    async startPlan(plan) {
      try {
        this.startingPlanId = plan.id;
        await apiClient.plans.start(plan.id);
        this.$message.success('计划启动成功');
        await this.loadPlans();
      } catch (err) {
        this.$message.error('启动失败: ' + (err.message || '未知错误'));
      } finally {
        this.startingPlanId = null;
      }
    },
    
    // 处理计划表单提交成功
    async handlePlanSuccess(planData) {
      try {
        if (this.isEdit) {
          // 编辑计划
          await apiClient.plans.update(planData.id, planData);
          this.$message.success('计划更新成功');
        } else {
          // 添加新计划
          const planRequest = {
            ...planData,
            content_type: 'tasks' // 默认使用任务类型
          };
          
          await apiClient.plans.create(planRequest);
          this.$message.success('计划添加成功');
        }
        
        await this.loadPlans();
      } catch (err) {
        this.$message.error('保存失败: ' + (err.message || '未知错误'));
      }
    },
    
    // 处理计划表单取消
    handlePlanCancel() {
      this.dialogVisible = false;
    }
  }
};
</script>

<style scoped>
.plan-list {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
}

.page-title {
  margin: 0;
  font-size: 1.5rem;
  font-weight: bold;
}

.dialog-footer {
  text-align: right;
}

@media (max-width: 768px) {
  .plan-list {
    padding: 10px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 15px;
  }
}
</style>