<template>
  <div class="scheduler-config">
    <n-space
      vertical
      :size="14"
    >
      <!-- 启用开关 -->
      <div class="config-item">
        <n-switch
          v-model:value="formData.enabled"
          size="large"
        >
          <template #checked>
            启用定时任务
          </template>
          <template #unchecked>
            停用定时任务
          </template>
        </n-switch>
      </div>

      <!-- 定时类型 -->
      <div
        v-if="formData.enabled"
        class="config-item"
      >
        <label>定时类型：</label>
        <n-radio-group
          v-model:value="formData.type"
          size="large"
        >
          <n-space>
            <n-radio value="interval">
              间隔执行
            </n-radio>
            <n-radio value="daily">
              每日定时
            </n-radio>
          </n-space>
        </n-radio-group>
      </div>

      <!-- 间隔设置 -->
      <div
        v-if="formData.enabled && formData.type === 'interval'"
        class="config-item"
      >
        <label>执行间隔：</label>
        <n-input-number
          v-model:value="formData.interval"
          :min="1"
          :max="1440"
          size="large"
        >
          <template #suffix>
            分钟
          </template>
        </n-input-number>
        <p class="hint" style="margin-top: 6px;">
          任务将每隔{{ formData.interval }}分钟自动执行一次{{ formData.interval >= 60 ? ` (约${Math.floor(formData.interval / 60)}小时${formData.interval % 60 > 0 ? formData.interval % 60 + '分钟' : ''})` : '' }}。间隔从任务开始时计时，建议间隔大于任务执行时长。
        </p>
      </div>

      <!-- 每日时间设置 -->
      <div
        v-if="formData.enabled && formData.type === 'daily'"
        class="config-item"
      >
        <label>执行计划：</label>
        
        <!-- 每日计划列表 -->
        <div class="daily-schedules-list">
          <div
            v-for="(schedule, index) in dailySchedules"
            :key="index"
            class="schedule-item"
          >
            <!-- 时间选择器 -->
            <div class="schedule-header">
              <n-time-picker
                v-model:value="schedule.timeValue"
                format="HH:mm"
                size="small"
                @update:value="(value) => handleTimeChange(index, value)"
              />
              <n-button
                size="small"
                quaternary
                type="error"
                @click="removeSchedule(index)"
              >
                <template #icon>
                  <n-icon>
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                      <path fill="currentColor" d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
                    </svg>
                  </n-icon>
                </template>
              </n-button>
            </div>
            
            <!-- 任务选择区域 -->
            <div class="task-selection">
              <div
                v-for="task in availableTasks"
                :key="task.id"
                class="task-checkbox-item"
                :class="{ 'checked': schedule.tasks.includes(task.id) }"
                @click="toggleTask(index, task.id)"
              >
                <div class="checkbox-circle">
                  <svg v-if="schedule.tasks.includes(task.id)" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                    <path fill="currentColor" d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z"/>
                  </svg>
                </div>
                <span class="task-label">{{ task.name }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 添加按钮 -->
        <n-button
          size="small"
          type="primary"
          dashed
          :disabled="dailySchedules.length >= 10"
          @click="addSchedule"
          style="margin-top: 6px; width: 100%;"
        >
          <template #icon>
            <n-icon><Add /></n-icon>
          </template>
          添加时间点 ({{ dailySchedules.length }}/10)
        </n-button>
        
        <p class="hint" style="margin-top: 6px; margin-bottom: 6px;">
          为每个时间点选择需要执行的任务，更加灵活精准。点击圆点选择任务，最多10个时间点。
        </p>
      </div>

      <!-- 最后执行时间 -->
      <div
        v-if="formData.enabled && formData.lastExecutionTime"
        class="config-item last-execution"
      >
        <n-icon><Time /></n-icon>
        最后执行时间：{{ formatLastExecutionTime }}
      </div>

      <!-- 按钮 -->
      <n-space>
        <n-button
          type="primary"
          size="large"
          @click="handleSave"
        >
          保存设置
        </n-button>
        <n-button
          size="large"
          @click="emit('close')"
        >
          取消
        </n-button>
      </n-space>
    </n-space>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useMessage } from 'naive-ui'
import { Add, Time } from '@vicons/ionicons5'
import { useBatchTaskStore } from '@/stores/batchTaskStore'

const props = defineProps({
  config: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['save', 'close'])

const message = useMessage()
const batchStore = useBatchTaskStore()

// 可用任务列表
const availableTasks = [
  { id: 'dailyFix', name: '补差' },
  { id: 'restartBottle', name: '盐罐' },
  { id: 'legionSignIn', name: '签到' },
  { id: 'autoStudy', name: '答题' },
  { id: 'claimHangupReward', name: '挂机' },
  { id: 'addClock', name: '加钟' },
  { id: 'sendCar', name: '发车' },
  { id: 'climbTower', name: '爬塔' }
]

// 表单数据
const formData = ref({ ...props.config })

// 每日计划数据（用于UI展示和编辑）
const dailySchedules = ref([])

// 初始化每日计划数据
const initDailySchedules = () => {
  if (formData.value.dailySchedules && formData.value.dailySchedules.length > 0) {
    // 使用新格式数据 (tasks 数组)
    dailySchedules.value = formData.value.dailySchedules.map(schedule => {
      // 兼容旧的 template 格式
      let tasks = []
      if (schedule.tasks) {
        tasks = schedule.tasks
      } else if (schedule.template) {
        // 从模板转换为任务列表
        const template = batchStore.taskTemplates[schedule.template]
        tasks = template ? template.tasks : []
      }
      
      return {
        time: schedule.time,
        tasks: tasks,
        timeValue: parseTime(schedule.time)
      }
    })
  } else if (formData.value.dailyTimes && formData.value.dailyTimes.length > 0) {
    // 兼容旧格式数据
    dailySchedules.value = formData.value.dailyTimes.map(time => ({
      time: time,
      tasks: ['dailyFix', 'restartBottle', 'legionSignIn', 'autoStudy', 'claimHangupReward', 'addClock', 'sendCar', 'climbTower'],
      timeValue: parseTime(time)
    }))
  } else {
    // 默认数据
    dailySchedules.value = []
  }
}

// 解析时间字符串为时间戳
const parseTime = (timeStr) => {
  const [hour, minute] = timeStr.split(':').map(Number)
  const date = new Date()
  date.setHours(hour, minute, 0, 0)
  return date.getTime()
}

// 切换任务选择
const toggleTask = (scheduleIndex, taskId) => {
  const schedule = dailySchedules.value[scheduleIndex]
  const taskIndex = schedule.tasks.indexOf(taskId)
  
  if (taskIndex > -1) {
    // 已选中，移除
    schedule.tasks.splice(taskIndex, 1)
  } else {
    // 未选中，添加
    schedule.tasks.push(taskId)
  }
}

// 添加计划
const addSchedule = () => {
  if (dailySchedules.value.length >= 10) {
    message.warning('最多支持10个时间点')
    return
  }
  
  const now = new Date()
  dailySchedules.value.push({
    time: '08:00',
    tasks: ['dailyFix', 'restartBottle', 'legionSignIn', 'autoStudy', 'claimHangupReward', 'addClock', 'sendCar', 'climbTower'],
    timeValue: new Date(now.getFullYear(), now.getMonth(), now.getDate(), 8, 0).getTime()
  })
}

// 删除计划
const removeSchedule = (index) => {
  dailySchedules.value.splice(index, 1)
}

// 时间改变处理
const handleTimeChange = (index, value) => {
  if (value) {
    dailySchedules.value[index].time = formatTime(value)
  }
}

// 初始化
initDailySchedules()

// 格式化最后执行时间
const formatLastExecutionTime = computed(() => {
  if (!formData.value.lastExecutionTime) return '从未执行'
  
  const date = new Date(formData.value.lastExecutionTime)
  return date.toLocaleString('zh-CN')
})

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  
  const date = new Date(timestamp)
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  return `${hours}:${minutes}`
}

// 保存配置
const handleSave = () => {
  if (formData.value.enabled) {
    if (formData.value.type === 'interval' && !formData.value.interval) {
      message.error('请设置执行间隔')
      return
    }
    
    if (formData.value.type === 'daily') {
      if (dailySchedules.value.length === 0) {
        message.error('请至少添加一个执行时间')
        return
      }
      
      // 保存新格式的dailySchedules
      formData.value.dailySchedules = dailySchedules.value.map(schedule => ({
        time: schedule.time,
        tasks: schedule.tasks
      }))
      
      // 同时保留dailyTimes用于兼容（只保存时间）
      formData.value.dailyTimes = dailySchedules.value.map(schedule => schedule.time)
    }
  }
  
  emit('save', formData.value)
}
</script>

<style scoped lang="scss">
.scheduler-config {
  .config-item {
    label {
      display: block;
      margin-bottom: 8px;
      font-weight: 500;
      color: #666;
    }

    .hint {
      margin-top: 8px;
      font-size: 12px;
      color: #999;
    }
    
    .interval-info {
      font-size: 13px;
      line-height: 1.6;
      
      p {
        margin: 4px 0;
        
        &:first-child {
          margin-top: 0;
        }
      }
      
      ul {
        margin: 8px 0;
        padding-left: 20px;
        
        li {
          margin: 4px 0;
          
          strong {
            color: #2080f0;
          }
        }
      }
    }
    
    // 每日计划列表样式
    .daily-schedules-list {
      display: flex;
      flex-direction: column;
      gap: 10px;
      
      .schedule-item {
        padding: 10px 12px;
        background: var(--bg-tertiary);
        border-radius: 8px;
        transition: all 0.3s ease;
        border: 1px solid transparent;
        
        &:hover {
          background: var(--bg-secondary);
          border-color: rgba(32, 128, 240, 0.2);
        }
        
        .schedule-header {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 8px;
          padding-bottom: 8px;
          border-bottom: 1px solid rgba(128, 128, 128, 0.15);
        }
        
        .task-selection {
          display: grid;
          grid-template-columns: repeat(4, 1fr);
          gap: 6px;
          
          .task-checkbox-item {
            display: flex;
            align-items: center;
            gap: 6px;
            padding: 6px 8px;
            border-radius: 6px;
            background: rgba(128, 128, 128, 0.05);
            cursor: pointer;
            transition: all 0.2s ease;
            user-select: none;
            
            &:hover {
              background: rgba(32, 128, 240, 0.08);
              transform: translateX(1px);
            }
            
            &.checked {
              background: rgba(32, 128, 240, 0.12);
              border: 1px solid rgba(32, 128, 240, 0.3);
              
              .checkbox-circle {
                background: #2080f0;
                border-color: #2080f0;
                
                svg {
                  opacity: 1;
                }
              }
              
              .task-label {
                color: #2080f0;
                font-weight: 500;
              }
            }
            
            .checkbox-circle {
              width: 16px;
              height: 16px;
              border-radius: 50%;
              border: 2px solid rgba(128, 128, 128, 0.3);
              background: rgba(255, 255, 255, 0.8);
              display: flex;
              align-items: center;
              justify-content: center;
              flex-shrink: 0;
              transition: all 0.2s ease;
              
              svg {
                width: 12px;
                height: 12px;
                color: white;
                opacity: 0;
                transition: opacity 0.2s ease;
              }
            }
            
            .task-label {
              font-size: 12px;
              color: #666;
              transition: all 0.2s ease;
              white-space: nowrap;
            }
          }
        }
      }
    }

    &.last-execution {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 12px;
      background: rgba(102, 126, 234, 0.05);
      border-radius: 8px;
      color: #666;

      .n-icon {
        font-size: 18px;
      }
    }
  }
}

/* 深色主题 */
html.dark .scheduler-config,
html[data-theme="dark"] .scheduler-config {
  .config-item {
    label {
      color: #cccccc;
    }

    .hint {
      color: #888888;
    }
    
    .interval-info {
      ul li strong {
        color: #63a4ff;
      }
    }
    
    .daily-schedules-list {
      .schedule-item {
        .schedule-header {
          border-bottom-color: rgba(255, 255, 255, 0.1);
        }
        
        .task-selection {
          .task-checkbox-item {
            background: rgba(255, 255, 255, 0.05);
            
            &:hover {
              background: rgba(99, 164, 255, 0.15);
            }
            
            &.checked {
              background: rgba(99, 164, 255, 0.2);
              border-color: rgba(99, 164, 255, 0.4);
              
              .checkbox-circle {
                background: #63a4ff;
                border-color: #63a4ff;
              }
              
              .task-label {
                color: #63a4ff;
              }
            }
            
            .checkbox-circle {
              border-color: rgba(255, 255, 255, 0.3);
              background: rgba(0, 0, 0, 0.3);
            }
            
            .task-label {
              color: #cccccc;
            }
          }
        }
      }
    }

    &.last-execution {
      background: rgba(255, 255, 255, 0.05);
      color: #cccccc;
    }
  }
}

/* 移动端响应式 */
@media (max-width: 768px) {
  .scheduler-config {
    .config-item {
      .daily-schedules-list {
        .schedule-item {
          .schedule-header {
            flex-wrap: wrap;
            gap: 8px;
          }
          
          .task-selection {
            grid-template-columns: repeat(2, 1fr);
            
            .task-checkbox-item {
              .task-label {
                font-size: 12px;
              }
            }
          }
        }
      }
    }
  }
}

@media (max-width: 500px) {
  .scheduler-config {
    .config-item {
      .daily-schedules-list {
        .schedule-item {
          .task-selection {
            grid-template-columns: repeat(2, 1fr);
            gap: 5px;
            
            .task-checkbox-item {
              padding: 5px 6px;
              
              .task-label {
                font-size: 11px;
              }
            }
          }
        }
      }
    }
  }
}
</style>
