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

const router = useRouter()
const { userInfo, getUserInfo } = useUserStore()
const resourceStore = useResourceStore()
const pro = useProfessionalModulesStore()

const mediaList = ref([])
const modelOptions = ref([])
const selectedModelId = ref(null)
const selectedMedias = ref([])
const batchName = ref('')
const jobs = ref([])
const detailVisible = ref(false)
const currentJob = ref(null)
let advanceTimer = null

const selectedModelName = computed(() => {
  const m = modelOptions.value.find((x) => x.model_id === selectedModelId.value)
  return m?.model_name || ''
})

const statusType = {
  pending: 'info',
  running: 'warning',
  completed: 'success',
  failed: 'danger',
  cancelled: 'info',
}

const loadMedia = async () => {
  const { medias, error } = await resourceStore.fetchMediaList(userInfo.value, 1, 50, true)
  if (error) throw error
  mediaList.value = medias
}

const loadModels = async () => {
  const { models, error } = await resourceStore.fetchModelList(1, 50, true)
  if (error) throw error
  modelOptions.value = models
  if (models.length && !selectedModelId.value) {
    selectedModelId.value = models[0].model_id
  }
}

const refreshJobs = () => {
  jobs.value = pro.listBatchJobs()
}

const handleSelectionChange = (rows) => {
  selectedMedias.value = rows
}

const createBatch = () => {
  if (!selectedModelId.value) {
    ElMessage.warning('请选择模型')
    return
  }
  if (!selectedMedias.value.length) {
    ElMessage.warning('请勾选至少一条媒体')
    return
  }
  const { ok, message, job } = pro.createBatchJob({
    batch_name: batchName.value,
    model_id: selectedModelId.value,
    model_name: selectedModelName.value,
    mediaItems: selectedMedias.value.map((m) => ({
      media_id: m.media_id,
      media_name: m.media_name,
    })),
  })
  if (!ok) {
    ElMessage.error(message)
    return
  }
  ElMessage.success('批量任务已创建')
  batchName.value = ''
  refreshJobs()
  currentJob.value = job
  detailVisible.value = true
}

const startJob = (row) => {
  const { ok, message } = pro.startBatchJob(row.batch_id)
  if (!ok) {
    ElMessage.error(message)
    return
  }
  ElMessage.success('已开始执行')
  refreshJobs()
  autoAdvance(row.batch_id)
}

const autoAdvance = (batchId) => {
  if (advanceTimer) clearInterval(advanceTimer)
  advanceTimer = setInterval(() => {
    const job = pro.listBatchJobs().find((j) => j.batch_id === batchId)
    if (!job || job.status !== 'running') {
      clearInterval(advanceTimer)
      advanceTimer = null
      refreshJobs()
      return
    }
    const { ok, done } = pro.advanceBatchJob(batchId)
    refreshJobs()
    if (currentJob.value?.batch_id === batchId) {
      currentJob.value = pro.listBatchJobs().find((j) => j.batch_id === batchId)
    }
    if (done) {
      clearInterval(advanceTimer)
      advanceTimer = null
      ElMessage.success('批量检测已完成，相关安全隐患已写入安全隐患台账')
    }
    if (!ok) clearInterval(advanceTimer)
  }, 800)
}

const stepAdvance = (row) => {
  const { ok, message, done } = pro.advanceBatchJob(row.batch_id)
  if (!ok) {
    ElMessage.error(message)
    return
  }
  refreshJobs()
  if (done) ElMessage.success('本批次已全部处理完成')
}

const cancelJob = (row) => {
  const { ok, message } = pro.cancelBatchJob(row.batch_id)
  if (!ok) {
    ElMessage.error(message)
    return
  }
  ElMessage.info('任务已取消')
  refreshJobs()
}

const showDetail = (row) => {
  currentJob.value = { ...row }
  detailVisible.value = true
}

const fmt = (v) => (v ? formatDateTime(v) : '—')

onMounted(() => {
  getUserInfo().then(async () => {
    if (!userInfo.value) {
      router.push('/login')
      return
    }
    try {
      await Promise.all([loadMedia(), loadModels()])
      refreshJobs()
    } catch (e) {
      ElMessage.error('加载媒体/模型失败')
    }
  })
})
</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>
          </template>
          <el-form inline>
            <el-form-item label="任务名称">
              <el-input v-model="batchName" placeholder="可选" style="width: 220px" clearable />
            </el-form-item>
            <el-form-item label="检测模型">
              <el-select v-model="selectedModelId" placeholder="选择模型" style="width: 240px" filterable>
                <el-option
                  v-for="m in modelOptions"
                  :key="m.model_id"
                  :label="m.model_name"
                  :value="m.model_id"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="createBatch">
                <el-icon><Plus /></el-icon> 创建任务
              </el-button>
            </el-form-item>
          </el-form>

          <el-table
            :data="mediaList"
            max-height="280"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="48" />
            <el-table-column prop="media_id" label="ID" width="70" />
            <el-table-column prop="media_name" label="媒体名称" show-overflow-tooltip />
            <el-table-column prop="file_type" label="类型" width="80" />
            <el-table-column prop="description" label="描述" show-overflow-tooltip />
          </el-table>
        </el-card>

        <el-card class="iot-card">
          <template #header>
            <div class="card-header">
              <h2>批量任务列表</h2>
              <el-button @click="refreshJobs"><el-icon><Refresh /></el-icon> 刷新</el-button>
            </div>
          </template>
          <el-table :data="jobs">
            <el-table-column prop="batch_id" label="ID" width="60" />
            <el-table-column prop="batch_name" label="任务名称" min-width="160" show-overflow-tooltip />
            <el-table-column prop="model_name" label="模型" width="140" 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="130">
              <template #default="{ row }">
                {{ row.success_count }} / {{ row.fail_count }} / {{ row.total_count }}
              </template>
            </el-table-column>
            <el-table-column label="状态" width="90">
              <template #default="{ row }">
                <el-tag :type="statusType[row.status]" size="small">
                  {{ pro.batchStatusLabel[row.status] }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" width="165">
              <template #default="{ row }">{{ fmt(row.created_at) }}</template>
            </el-table-column>
            <el-table-column label="操作" width="260" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" @click="showDetail(row)">明细</el-button>
                <el-button
                  v-if="row.status === 'pending'"
                  link
                  type="success"
                  @click="startJob(row)"
                >
                  <el-icon><VideoPlay /></el-icon> 执行
                </el-button>
                <el-button
                  v-if="row.status === 'running'"
                  link
                  type="primary"
                  @click="stepAdvance(row)"
                >
                  <el-icon><Promotion /></el-icon> 推进
                </el-button>
                <el-button
                  v-if="row.status === 'pending' || row.status === 'running'"
                  link
                  type="danger"
                  @click="cancelJob(row)"
                >
                  <el-icon><CircleClose /></el-icon> 取消
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </div>

    <el-dialog v-model="detailVisible" title="批量任务明细" width="640px">
      <template v-if="currentJob">
        <p><strong>模型：</strong>{{ currentJob.model_name }}</p>
        <el-progress :percentage="currentJob.progress" class="mb-12" />
        <el-table :data="currentJob.items" size="small">
          <el-table-column prop="media_name" label="媒体" show-overflow-tooltip />
          <el-table-column prop="status" label="状态" width="100" />
          <el-table-column prop="detection_id" label="检测ID" width="90" />
          <el-table-column prop="error" label="备注" show-overflow-tooltip />
        </el-table>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
@import '../styles/iot-page.css';
.mb-12 {
  margin: 12px 0;
}
</style>
