<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Document, Download, Plus } from '@element-plus/icons-vue'
import { useUserStore } from '../stores/userStore'
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'
import { EXPORT_PREFIX } from '../shellConstants'

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

const reportList = ref([])
const generateVisible = ref(false)
const form = ref({
  template_id: 'weekly_inspection',
  title: '',
  bridge_name: '示例长江大桥',
  period: '',
})

const refreshReports = () => {
  reportList.value = [...pro.reports.value]
}

const openGenerate = (templateId) => {
  form.value.template_id = templateId
  const tpl = pro.REPORT_TEMPLATES.find((t) => t.template_id === templateId)
  form.value.title = tpl ? `${tpl.name}_${new Date().toISOString().slice(0, 10)}` : ''
  generateVisible.value = true
}

const submitGenerate = () => {
  const { ok, message, report } = pro.generateReport({
    ...form.value,
    created_by: userInfo.value?.username || 'admin',
  })
  if (!ok) {
    ElMessage.error(message)
    return
  }
  ElMessage.success('报告已生成')
  generateVisible.value = false
  refreshReports()
}

const downloadReport = async (row) => {
  try {
    const XLSX = await import('xlsx')
    const wb = XLSX.utils.book_new()
    const summary = [
      { 项目: '报告标题', 内容: row.title },
      { 项目: '桥梁名称', 内容: row.bridge_name },
      { 项目: '统计周期', 内容: row.period },
      { 项目: '模板', 内容: row.template_name },
      { 项目: '检测任务数', 内容: row.summary?.detection_count },
      { 项目: '安全隐患台账数', 内容: row.summary?.defect_count },
      { 项目: '未销项隐患', 内容: row.summary?.open_defects },
    ]
    XLSX.utils.book_append_sheet(wb, XLSX.utils.json_to_sheet(summary), '报告概要')
    XLSX.utils.book_append_sheet(
      wb,
      XLSX.utils.json_to_sheet(pro.getReportExportRows(row)),
      '安全隐患台账明细',
    )
    XLSX.writeFile(wb, row.file_name || `${EXPORT_PREFIX}_报告.xlsx`)
    ElMessage.success('报告已导出')
  } catch (e) {
    ElMessage.error('导出失败')
  }
}

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

onMounted(() => {
  getUserInfo().then(() => {
    if (!userInfo.value) router.push('/login')
    else refreshReports()
  })
})
</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="按模板生成桥梁巡检周报、安全隐患专项检测报告与预警汇总，支持导出 Excel 交付。"
        />

        <el-row :gutter="16" class="template-row">
          <el-col v-for="tpl in pro.REPORT_TEMPLATES" :key="tpl.template_id" :span="8">
            <el-card shadow="hover" class="template-card">
              <el-icon class="tpl-icon"><Document /></el-icon>
              <h3>{{ tpl.name }}</h3>
              <p>{{ tpl.description }}</p>
              <ul class="sections">
                <li v-for="s in tpl.sections" :key="s">{{ s }}</li>
              </ul>
              <el-button type="primary" @click="openGenerate(tpl.template_id)">
                <el-icon><Plus /></el-icon> 生成报告
              </el-button>
            </el-card>
          </el-col>
        </el-row>

        <el-card class="iot-card">
          <template #header>
            <div class="card-header"><h2>已生成报告</h2></div>
          </template>
          <el-table :data="reportList">
            <el-table-column prop="report_id" label="ID" width="60" />
            <el-table-column prop="title" label="报告标题" min-width="180" show-overflow-tooltip />
            <el-table-column prop="template_name" label="模板" width="130" />
            <el-table-column prop="bridge_name" label="桥梁" width="130" show-overflow-tooltip />
            <el-table-column prop="period" label="周期" width="160" show-overflow-tooltip />
            <el-table-column prop="created_by" label="生成人" width="90" />
            <el-table-column label="生成时间" width="165">
              <template #default="{ row }">{{ fmt(row.created_at) }}</template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" @click="downloadReport(row)">
                  <el-icon><Download /></el-icon> 导出
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </div>

    <el-dialog v-model="generateVisible" title="生成报告" width="480px">
      <el-form :model="form" label-width="90px">
        <el-form-item label="报告标题">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="桥梁名称">
          <el-input v-model="form.bridge_name" />
        </el-form-item>
        <el-form-item label="统计周期">
          <el-input v-model="form.period" placeholder="如 2026-04-01 ~ 2026-04-07" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="generateVisible = false">取消</el-button>
        <el-button type="primary" @click="submitGenerate">生成</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
@import '../styles/iot-page.css';
.template-row {
  margin-bottom: 16px;
}
.template-card {
  min-height: 260px;
  background: var(--card);
  border: 1px solid var(--border);
}
.template-card h3 {
  margin: 8px 0;
  font-size: 16px;
}
.template-card p {
  color: var(--muted);
  font-size: 13px;
  min-height: 40px;
}
.tpl-icon {
  font-size: 32px;
  color: var(--primary);
}
.sections {
  font-size: 12px;
  color: var(--muted);
  padding-left: 18px;
  margin: 8px 0 16px;
}
</style>
