<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, VideoPlay, Promotion, Refresh } from '@element-plus/icons-vue'
import { useUserStore } from '../stores/userStore'
import { useIotMonitoringStore } from '../stores/iotMonitoringStore'
import { formatDateTime } from '../utils/dateTimeFormatter'
import SidebarMenu from '../components/SidebarMenu.vue'
import BreadcrumbNav from '../components/BreadcrumbNav.vue'
import HudPageHero from '../components/shell/HudPageHero.vue'

const router = useRouter()
const { userInfo, getUserInfo } = useUserStore()
const iot = useIotMonitoringStore()

const tableData = ref([])
const searchForm = ref({ keyword: '', status: '' })
const dialogVisible = ref(false)
const formRef = ref(null)

const form = ref({
  job_name: '',
  source_task_id: null,
  pipeline: 'denoise → resample → feature_extract',
})

const formRules = {
  job_name: [{ required: true, message: '请输入作业名称', trigger: 'blur' }],
  source_task_id: [{ required: true, message: '请选择采集任务', trigger: 'change' }],
}

const statusLabel = {
  pending: '待处理',
  running: '处理中',
  completed: '已完成',
  failed: '失败',
}
const statusType = {
  pending: 'info',
  running: 'warning',
  completed: 'success',
  failed: 'danger',
}

const tasksWithSamples = () =>
  iot.collectionTasks.value.filter((t) => t.sample_count > 0)

const refreshList = () => {
  tableData.value = iot.listProcessingJobs(searchForm.value)
}

const resetSearch = () => {
  searchForm.value = { keyword: '', status: '' }
  refreshList()
}

const openCreate = () => {
  form.value = {
    job_name: '',
    source_task_id: null,
    pipeline: 'denoise → resample → feature_extract',
  }
  dialogVisible.value = true
}

const submitForm = async () => {
  await formRef.value?.validate()
  const { ok, message } = iot.createProcessingJob(form.value)
  if (!ok) {
    ElMessage.error(message)
    return
  }
  ElMessage.success('处理作业已创建')
  dialogVisible.value = false
  refreshList()
}

const handleDelete = async (row) => {
  await ElMessageBox.confirm(`确定删除作业「${row.job_name}」？`, '删除确认', { type: 'warning' })
  const { ok, message } = iot.deleteProcessingJob(row.job_id)
  if (!ok) {
    ElMessage.error(message)
    return
  }
  ElMessage.success('已删除')
  refreshList()
}

const handleStart = (row) => {
  const { ok, message } = iot.startProcessing(row.job_id)
  if (!ok) {
    ElMessage.error(message)
    return
  }
  ElMessage.success('处理已开始')
  refreshList()
}

const handleAdvance = (row) => {
  const { ok, message, job } = iot.advanceProcessing(row.job_id)
  if (!ok) {
    ElMessage.error(message)
    return
  }
  if (job.status === 'completed') {
    ElMessage.success('处理已完成，可前往检测或导出结果')
  } else {
    ElMessage.info(`处理进度 ${job.progress}%`)
  }
  refreshList()
}

const fmtTime = (row, col) => (row[col.property] ? formatDateTime(row[col.property]) : '—')

onMounted(() => {
  getUserInfo().then(() => {
    if (!userInfo.value) router.push('/login')
    else refreshList()
  })
})
</script>

<template>
  <div class="iot-page shell-layout-root">
    <div class="main-container">
      <div class="sidebar"><SidebarMenu /></div>
      <div class="content-area">
        <BreadcrumbNav />
        <HudPageHero
          title="数据处理"
          description="基于采集任务样本创建清洗、特征提取等流水线作业，推进处理进度并产出结构化记录。"
        />

        <el-card class="iot-card">
          <template #header>
            <div class="card-header">
              <h2>处理作业</h2>
              <div>
                <el-button type="primary" @click="openCreate"><el-icon><Plus /></el-icon> 新建作业</el-button>
                <el-button @click="refreshList"><el-icon><Refresh /></el-icon> 刷新</el-button>
              </div>
            </div>
          </template>

          <el-form :model="searchForm" inline class="search-form">
            <el-form-item label="关键词">
              <el-input v-model="searchForm.keyword" placeholder="作业名/流水线" clearable style="width: 220px" />
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" placeholder="全部" clearable style="width: 120px">
                <el-option v-for="(label, key) in statusLabel" :key="key" :label="label" :value="key" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="refreshList">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>

          <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="job_id" label="ID" width="60" />
            <el-table-column prop="job_name" label="作业名称" min-width="150" show-overflow-tooltip />
            <el-table-column prop="source_task_name" label="来源采集任务" width="150" show-overflow-tooltip />
            <el-table-column prop="pipeline" label="处理流水线" min-width="200" show-overflow-tooltip />
            <el-table-column label="进度" width="160">
              <template #default="{ row }">
                <el-progress :percentage="row.progress" :status="row.status === 'completed' ? 'success' : undefined" />
              </template>
            </el-table-column>
            <el-table-column label="输入/输出" width="120">
              <template #default="{ row }">{{ row.input_records }} / {{ row.output_records }}</template>
            </el-table-column>
            <el-table-column label="状态" width="95">
              <template #default="{ row }">
                <el-tag :type="statusType[row.status]" size="small">{{ statusLabel[row.status] }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="started_at" label="开始时间" width="165" :formatter="fmtTime" />
            <el-table-column prop="finished_at" label="完成时间" width="165" :formatter="fmtTime" />
            <el-table-column label="操作" width="220" fixed="right">
              <template #default="{ row }">
                <el-button
                  v-if="row.status === 'pending'"
                  link
                  type="success"
                  @click="handleStart(row)"
                >
                  <el-icon><VideoPlay /></el-icon> 开始
                </el-button>
                <el-button
                  v-if="row.status === 'running'"
                  link
                  type="primary"
                  @click="handleAdvance(row)"
                >
                  <el-icon><Promotion /></el-icon> 推进 (+25%)
                </el-button>
                <el-button
                  v-if="row.status !== 'running'"
                  link
                  type="danger"
                  @click="handleDelete(row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </div>

    <el-dialog v-model="dialogVisible" title="新建数据处理作业" width="500px">
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="110px">
        <el-form-item label="作业名称" prop="job_name"><el-input v-model="form.job_name" /></el-form-item>
        <el-form-item label="来源采集任务" prop="source_task_id">
          <el-select v-model="form.source_task_id" placeholder="需有样本的采集任务" style="width: 100%" filterable>
            <el-option
              v-for="t in tasksWithSamples()"
              :key="t.task_id"
              :label="`${t.task_name}（样本 ${t.sample_count}）`"
              :value="t.task_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="处理流水线">
          <el-select v-model="form.pipeline" style="width: 100%">
            <el-option label="去噪 → 重采样 → 特征提取" value="denoise → resample → feature_extract" />
            <el-option label="FFT → 频带能量 → 异常评分" value="fft → band_energy → anomaly_score" />
            <el-option label="清洗 → 聚合 → 导出" value="clean → aggregate → export" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
@import '../styles/iot-page.css';
</style>
