<script setup lang="ts">
import { ref, onMounted } from 'vue'
import api from '../api'
import { ElMessage, ElMessageBox } from 'element-plus'

interface TaskRule {
  name: string
  prompt: string
}

interface Task {
  id: number
  name: string
  cron_expression: string
  is_running: boolean
  rules: TaskRule[]
  model_config_id: number
  camera_ids: number[]
}

const tasks = ref<Task[]>([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const editId = ref<number | null>(null)
const testing = ref(false)
const testResults = ref<any[]>([])
const showTestResults = ref(false)

const form = ref({
  name: '',
  model_config_id: null as number | null,
  camera_ids: [] as number[],
  rules: [] as TaskRule[],
  // Cron UI fields
  intervalValue: 5,
  intervalUnit: 'minutes' // seconds, minutes, hours
})

const cameras = ref<any[]>([])
const models = ref<any[]>([])

const fetchTasks = async () => {
  const res = await api.get('/tasks')
  tasks.value = res.data
}

const fetchData = async () => {
  const [camRes, modelRes] = await Promise.all([
    api.get('/cameras'),
    api.get('/models')
  ])
  cameras.value = camRes.data
  models.value = modelRes.data
}

const resetForm = () => {
  form.value = {
    name: '',
    model_config_id: models.value.length > 0 ? models.value[0].id : null,
    camera_ids: [],
    rules: [{ name: '', prompt: '' }],
    intervalValue: 5,
    intervalUnit: 'minutes'
  }
  isEdit.value = false
  editId.value = null
  testResults.value = []
  showTestResults.value = false
}

// Convert UI interval to Cron String
const generateCron = () => {
  const { intervalValue, intervalUnit } = form.value
  if (intervalUnit === 'seconds') {
    return `*/${intervalValue} * * * * *`
  } else if (intervalUnit === 'minutes') {
    return `*/${intervalValue} * * * *`
  } else if (intervalUnit === 'hours') {
    return `0 */${intervalValue} * * *`
  }
  return '*/5 * * * *'
}

// Parse Cron String to UI (Simple parser for standard intervals)
const parseCron = (cron: string) => {
  if (!cron) return
  const parts = cron.split(' ')
  // Check seconds (6 parts) or standard (5 parts)
  if (parts.length === 6 && parts[0] && parts[0].startsWith('*/')) {
     form.value.intervalUnit = 'seconds'
     form.value.intervalValue = parseInt(parts[0].replace('*/', ''))
  } else if (parts.length >= 5) {
     if (parts[0] && parts[0].startsWith('*/')) {
        form.value.intervalUnit = 'minutes'
        form.value.intervalValue = parseInt(parts[0].replace('*/', ''))
     } else if (parts[1] && parts[1].startsWith('*/')) {
        form.value.intervalUnit = 'hours'
        form.value.intervalValue = parseInt(parts[1].replace('*/', ''))
     }
  }
}

const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row: Task) => {
  isEdit.value = true
  editId.value = row.id
  form.value.name = row.name
  form.value.model_config_id = row.model_config_id
  form.value.camera_ids = row.camera_ids
  // Ensure rules is an array
  form.value.rules = row.rules && row.rules.length > 0 ? JSON.parse(JSON.stringify(row.rules)) : [{ name: '', prompt: '' }]
  parseCron(row.cron_expression)
  dialogVisible.value = true
}

const handleSave = async () => {
  // Validate rules
  if (form.value.rules.length === 0) {
    ElMessage.warning('请至少添加一条规则')
    return
  }
  for (const rule of form.value.rules) {
    if (!rule.name || !rule.prompt) {
      ElMessage.warning('请完善告警规则名称和提示词')
      return
    }
  }

  const payload = {
    name: form.value.name,
    model_config_id: form.value.model_config_id,
    camera_ids: form.value.camera_ids,
    rules: form.value.rules,
    cron_expression: generateCron()
  }

  try {
    if (isEdit.value && editId.value) {
      await api.put(`/tasks/${editId.value}`, payload)
      ElMessage.success('更新成功')
    } else {
      await api.post('/tasks', payload)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    fetchTasks()
  } catch (e) {
    ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
  }
}

const handleDelete = (id: number) => {
  ElMessageBox.confirm('确认删除该任务？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await api.delete(`/tasks/${id}`)
      ElMessage.success('删除成功')
      fetchTasks()
    } catch (e) {
      ElMessage.error('删除失败')
    }
  })
}

const handleToggle = async (task: Task) => {
  try {
    await api.post(`/tasks/${task.id}/toggle`, { running: task.is_running })
    ElMessage.success('状态更新成功')
  } catch (e) {
    task.is_running = !task.is_running // Revert
    ElMessage.error('状态更新失败')
  }
}

const handleTest = async () => {
  if (!form.value.model_config_id || form.value.camera_ids.length === 0) {
    ElMessage.warning('请选择模型和至少一个摄像头')
    return
  }
  
  // Validate rules
  for (const rule of form.value.rules) {
    if (!rule.name || !rule.prompt) {
      ElMessage.warning('请完善告警规则名称和提示词')
      return
    }
  }

  testing.value = true
  showTestResults.value = false
  testResults.value = []
  
  try {
    const payload = {
      model_config_id: form.value.model_config_id,
      camera_ids: form.value.camera_ids,
      rules: form.value.rules
    }
    const res = await api.post('/tasks/test', payload)
    testResults.value = res.data.results
    showTestResults.value = true
    ElMessage.success('测试完成')
  } catch (e) {
    ElMessage.error('测试失败')
  } finally {
    testing.value = false
  }
}

const getCameraName = (id: number) => {
  const cam = cameras.value.find(c => c.id === id)
  return cam ? cam.name : `Cam ${id}`
}

const addRule = () => {
  form.value.rules.push({ name: '', prompt: '' })
}

const removeRule = (index: number) => {
  form.value.rules.splice(index, 1)
}

const parseResult = (jsonStr: string) => {
  try {
    const cleanStr = jsonStr.replace(/```json/g, '').replace(/```/g, '').trim()
    const data = JSON.parse(cleanStr)
    return Array.isArray(data) ? data : [data]
  } catch (e) {
    return [{ alarm_name: '解析错误', alarm_content: jsonStr, is_alarm: false, time: '', area: '' }]
  }
}

onMounted(() => {
  fetchTasks()
  fetchData()
})
</script>

<template>
  <div class="tasks-view">
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">新建任务</el-button>
    </div>
    <el-table :data="tasks" style="width: 100%">
      <el-table-column prop="id" label="ID" width="60" />
      <el-table-column prop="name" label="任务名称" />
      <el-table-column label="轮询频率">
        <template #default="scope">
           {{ scope.row.cron_expression }}
        </template>
      </el-table-column>
      <el-table-column label="运行状态">
        <template #default="scope">
          <el-switch v-model="scope.row.is_running" @change="handleToggle(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑任务' : '新建任务'" width="70%">
      <div class="dialog-content">
        <el-form :model="form" label-width="120px">
          <el-form-item label="任务名称">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="选择模型">
            <el-select v-model="form.model_config_id" style="width: 100%">
              <el-option v-for="m in models" :key="m.id" :label="m.name" :value="m.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="选择摄像头">
            <el-select v-model="form.camera_ids" multiple style="width: 100%">
              <el-option v-for="c in cameras" :key="c.id" :label="c.name" :value="c.id" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="告警规则">
            <div style="width: 100%">
              <div v-for="(rule, index) in form.rules" :key="index" class="rule-item">
                <div class="rule-header">
                  <span>规则 #{{ index + 1 }}</span>
                  <el-button type="danger" link @click="removeRule(index)" v-if="form.rules.length > 1">删除</el-button>
                </div>
                <div class="rule-content">
                  <el-input v-model="rule.name" placeholder="告警名称 (如: 未佩戴安全帽)" style="margin-bottom: 5px" />
                  <el-input v-model="rule.prompt" type="textarea" :rows="2" placeholder="提示词 (如: 帮我看看当前画面有没有人没有带安全帽)" />
                </div>
              </div>
              <el-button type="primary" link @click="addRule" style="margin-top: 5px">+ 添加规则</el-button>
            </div>
          </el-form-item>

          <el-form-item label="轮询频率">
            <div class="cron-input">
              <span>每</span>
              <el-input-number v-model="form.intervalValue" :min="1" style="margin: 0 10px; width: 120px;" />
              <el-select v-model="form.intervalUnit" style="width: 120px;">
                <el-option label="秒 (Seconds)" value="seconds" />
                <el-option label="分钟 (Minutes)" value="minutes" />
                <el-option label="小时 (Hours)" value="hours" />
              </el-select>
              <span>执行一次</span>
            </div>
          </el-form-item>
        </el-form>
        
        <!-- Test Results Area -->
        <div v-if="showTestResults" class="test-results">
          <el-divider content-position="left">测试结果预览</el-divider>
          <div v-for="(res, idx) in testResults" :key="idx" class="result-item">
             <div class="result-header">
               <strong>{{ getCameraName(res.camera_id) }}</strong>
               <el-tag :type="res.is_alarm ? 'danger' : 'success'" size="small" style="margin-left: 10px;">
                 {{ res.is_alarm ? '异常' : '正常' }}
               </el-tag>
             </div>
             <!-- Parse and display JSON result -->
             <div class="result-content">
               <el-table :data="parseResult(res.ai_result)" size="small" border style="width: 100%">
                 <el-table-column prop="alarm_name" label="告警名称" width="120" />
                 <el-table-column prop="alarm_content" label="内容" />
                 <el-table-column prop="time" label="时间" width="160" />
                 <el-table-column prop="area" label="区域" width="100" />
                 <el-table-column label="状态" width="80">
                   <template #default="scope">
                     <el-tag :type="scope.row.is_alarm ? 'danger' : 'success'" size="small">
                       {{ scope.row.is_alarm ? '异常' : '正常' }}
                     </el-tag>
                   </template>
                 </el-table-column>
               </el-table>
             </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleTest" :loading="testing" type="success" plain>立即运行测试</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.cron-input {
  display: flex;
  align-items: center;
}
.test-results {
  margin-top: 20px;
  background: #f8f9fa;
  padding: 10px;
  border-radius: 4px;
  max-height: 400px;
  overflow-y: auto;
}
.result-item {
  margin-bottom: 20px;
  border-bottom: 1px solid #ddd;
  padding-bottom: 10px;
}
.result-header {
  margin-bottom: 10px;
}
.result-content {
  font-size: 13px;
}
.rule-item {
  background: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 10px;
  border: 1px solid #e4e7ed;
}
.rule-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  font-weight: bold;
  font-size: 12px;
  color: #606266;
}
</style>