<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, VideoPlay, VideoPause, Download, 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: '', sensor_id: null })
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)

const defaultForm = () => ({
  task_id: null,
  task_name: '',
  sensor_id: null,
  interval_sec: 60,
  batch_size: 100,
})

const form = ref(defaultForm())

const formRules = {
  task_name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
  sensor_id: [{ required: true, message: '请选择传感器', trigger: 'change' }],
}

const statusLabel = { idle: '空闲', running: '采集中', paused: '已暂停', error: '异常' }
const statusType = { idle: 'info', running: 'success', paused: 'warning', error: 'danger' }

const onlineSensors = computed(() =>
  iot.sensors.value.filter((s) => s.status === iot.SENSOR_STATUS.ONLINE),
)

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

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

const openCreate = () => {
  isEdit.value = false
  form.value = defaultForm()
  dialogVisible.value = true
}

const openEdit = (row) => {
  isEdit.value = true
  form.value = {
    task_id: row.task_id,
    task_name: row.task_name,
    sensor_id: row.sensor_id,
    interval_sec: row.interval_sec,
    batch_size: row.batch_size,
  }
  dialogVisible.value = true
}

const submitForm = async () => {
  await formRef.value?.validate()
  const { ok, message } = iot.upsertCollectionTask(form.value)
  if (!ok) {
    ElMessage.error(message)
    return
  }
  ElMessage.success(isEdit.value ? '任务已更新' : '任务已创建')
  dialogVisible.value = false
  refreshList()
}

const handleDelete = async (row) => {
  await ElMessageBox.confirm(`确定删除采集任务「${row.task_name}」？`, '删除确认', { type: 'warning' })
  const { ok, message } = iot.deleteCollectionTask(row.task_id)
  if (!ok) {
    ElMessage.error(message)
    return
  }
  ElMessage.success('已删除')
  refreshList()
}

const handleStart = (row) => {
  const { ok, message } = iot.startCollection(row.task_id)
  if (!ok) {
    ElMessage.error(message)
    return
  }
  ElMessage.success('采集已启动')
  refreshList()
}

const handlePause = (row) => {
  const { ok, message } = iot.pauseCollection(row.task_id)
  if (!ok) {
    ElMessage.error(message)
    return
  }
  ElMessage.success('采集已暂停')
  refreshList()
}

const handleRunOnce = (row) => {
  const { ok, message, added } = iot.runCollectionOnce(row.task_id)
  if (!ok) {
    ElMessage.error(message)
    refreshList()
    return
  }
  ElMessage.success(`本次采集成功，新增 ${added} 条样本`)
  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-alert
          type="info"
          :closable="false"
          show-icon
          class="iot-tip"
          title="交互说明：仅「在线」传感器可启动采集；「立即采集」会累加样本数，并可能触发预警；处理作业需引用已有样本的采集任务。"
        />

        <el-card class="iot-card">
          <template #header>
            <div class="card-header">
              <h2>采集任务 · 运行中 {{ iot.runningTaskCount }}</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: 200px" />
            </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 label="传感器">
              <el-select v-model="searchForm.sensor_id" placeholder="全部" clearable style="width: 180px">
                <el-option
                  v-for="s in iot.sensors.value"
                  :key="s.sensor_id"
                  :label="`${s.sensor_code} · ${s.name}`"
                  :value="s.sensor_id"
                />
              </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="task_id" label="ID" width="60" />
            <el-table-column prop="task_name" label="任务名称" min-width="150" show-overflow-tooltip />
            <el-table-column prop="sensor_name" label="传感器" width="140" show-overflow-tooltip />
            <el-table-column prop="bridge_section" label="桥区" width="110" show-overflow-tooltip />
            <el-table-column prop="interval_sec" label="周期(秒)" width="95" />
            <el-table-column prop="batch_size" label="批次量" width="85" />
            <el-table-column prop="sample_count" label="累计样本" width="100" sortable />
            <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="last_run_at" label="上次采集" width="165" :formatter="fmtTime" />
            <el-table-column prop="error_message" label="异常信息" min-width="160" show-overflow-tooltip />
            <el-table-column label="操作" width="300" fixed="right">
              <template #default="{ row }">
                <el-button
                  v-if="row.status !== 'running'"
                  link
                  type="success"
                  @click="handleStart(row)"
                >
                  <el-icon><VideoPlay /></el-icon> 启动
                </el-button>
                <el-button v-else link type="warning" @click="handlePause(row)">
                  <el-icon><VideoPause /></el-icon> 暂停
                </el-button>
                <el-button link type="primary" @click="handleRunOnce(row)">
                  <el-icon><Download /></el-icon> 立即采集
                </el-button>
                <el-button link type="primary" @click="openEdit(row)">编辑</el-button>
                <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </div>

    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑采集任务' : '新建采集任务'" width="480px">
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px">
        <el-form-item label="任务名称" prop="task_name"><el-input v-model="form.task_name" /></el-form-item>
        <el-form-item label="传感器" prop="sensor_id">
          <el-select v-model="form.sensor_id" placeholder="选择传感器" style="width: 100%" filterable>
            <el-option
              v-for="s in iot.sensors.value"
              :key="s.sensor_id"
              :label="`${s.sensor_code} · ${s.name} (${statusLabel[s.status] || s.status})`"
              :value="s.sensor_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="采集周期(秒)">
          <el-input-number v-model="form.interval_sec" :min="5" :max="3600" />
        </el-form-item>
        <el-form-item label="每批样本数">
          <el-input-number v-model="form.batch_size" :min="1" :max="10000" />
        </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';
.iot-tip {
  margin-bottom: 12px;
}
</style>
