<template>
  <div class="use-reports">
    <!-- 头部导航 -->
    <div class="header">
      <div class="header-left">
        <el-button link class="back-btn" @click="handleBack">
          <el-icon>
            <ArrowLeft />
          </el-icon>
          <span>返回AI助手</span>
        </el-button>
      </div>
      <div class="header-right">
        <el-button class="export-btn" @click="handleExport">
          <el-icon>
            <Download />
          </el-icon>
          <span>导出文档</span>
        </el-button>
      </div>
    </div>

    <!-- 查询表单区域 -->
    <div class="query-form">
      <div class="form-container">
        <div class="custom-form horizontal-form">
          <div class="form-row">
            <div class="form-item">
              <div class="form-label">时间范围</div>
              <div class="form-content">
                <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                  end-placeholder="结束日期" value-format="YYYY-MM-DD" class="date-picker" @change="handleDateChange" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 报表内容区域 -->
    <div class="report-content" v-loading="loading">
      <!-- 标题 -->
      <div class="report-title">
        <h2><span class="highlight-text">{{ dateRangeText }}</span> 分级质控系统试用情况</h2>
      </div>

      <!-- 报表详情 -->
      <div class="report-details">
        <div class="detail-section">
          <h3>一、试运行基本情况</h3>
          <div class="detail-content">
            <p>目前试用人员覆盖<span class="dynamic-text">{{ reportData.sysDeptInfoListDesc }}</span>的一线员工及管理岗位，累计 <span
                class="dynamic-text">{{
                  reportData.totalPeopleNumber || '--'
                }}</span> 人参与。系统试运行聚焦于勤务、查获、抽问抽答、巡检四个核心模块。</p>
          </div>
        </div>

        <div class="detail-section">
          <h3>二、各模块运行情况</h3>

          <div class="module-section">
            <h4>1.勤务模块</h4>
            <div class="detail-content">
              <p>完成情况：本阶段共计 <span class="dynamic-text">{{ reportData?.attendanceModule?.totalPeopleNumber || '--'
                  }}</span>
                名人员完成上下班打卡流程，其中 <span class="dynamic-text">{{ reportData?.attendanceModule?.sysDeptInfoListDesc || '--'
                }}</span> 。
              </p>
            </div>
          </div>

          <div class="module-section">
            <h4>2.查获模块</h4>
            <div class="detail-content">
              <p>系统累计收录查获物品共上报表单<span class="dynamic-text">{{ reportData?.seizureModule?.totalForm || '--' }}</span>份，其中已归档表单<span class="dynamic-text">{{ reportData?.seizureModule?.totalFormArchived || '--' }}</span>份 
                ，查获总数 <span class="dynamic-text">{{ reportData?.seizureModule?.totalSeizure || '--' }}</span> 个，结合情况分析：
              </p>
              <p>违禁品类型：<span class="dynamic-text">{{(reportData?.seizureModule?.seizureTypeList || [])[0]?.name || '--'}}</span>为查获量最高品类，
                查获<span class="dynamic-text">{{(reportData?.seizureModule?.seizureTypeList || [])[0]?.total || '--'}}</span>个，
                其次为<span class="dynamic-text">{{(reportData?.seizureModule?.seizureTypeList || [])[1]?.name || '--'}}</span>，
                    查获<span class="dynamic-text">{{(reportData?.seizureModule?.seizureTypeList || [])[1]?.total || '--'}}</span>个。
              </p>
              <p>查获部位：<span class="dynamic-text">{{ reportData?.seizureModule?.seizurePartList[0]?.scaleDesc || '--'
              }}</span>以上集中在<span class="dynamic-text">{{ reportData?.seizureModule?.seizurePartList[0]?.name ||
                    '--'
                  }}</span>，查获场景集中度高；隐匿物品重点查获部位集中在<span class="dynamic-text">{{
                    reportData?.seizureModule?.seizurePartHiddenList[0]?.name || '--'
                  }}</span>。</p>
              <p>查获岗位：<span class="dynamic-text">{{(reportData?.seizureModule?.seizurePositionList || []).sort((a, b)=> b?.total - a?.total)[0]?.name || '--' }}</span>为核心查获岗位，其次为<span class="dynamic-text">{{
                    (reportData?.seizureModule?.seizurePositionList || []).sort((a, b) => b?.total - a?.total)[1]?.name ||
                  '--' }}</span>。</p>
            </div>
          </div>

          <div class="module-section">
            <h4>3.抽问抽答模块</h4>
            <div class="detail-content">
              <p>本阶段共计 <span class="dynamic-text">{{ reportData?.examModule?.totalPeopleNumber || '--' }}</span>
                名人员与该模块学习及测试，累计完成<span class="dynamic-text">{{ reportData?.examModule?.totalItem || '--' }}</span>
                项，平均得分 <span class="dynamic-text">{{ reportData?.examModule?.averageScore || '--' }}</span> 分，其中 <span
                  class="dynamic-text">{{reportData?.examModule?.typeList?.find(item => item.remark == '最高')?.name || '--'
                  }}</span>正确率<span class="dynamic-text">{{
                    reportData?.examModule?.typeList?.find(item => item.remark == '最高')?.scale || '--' }}</span>%掌握程度最好，
                <span class="dynamic-text">{{reportData?.examModule?.typeList?.find(item => item.remark == '薄弱')?.name ||
                  '--' }}</span>正确率仅为<span class="dynamic-text">{{
                    reportData?.examModule?.typeList?.find(item => item.remark == '薄弱')?.scale|| '--'
                  }}</span>%掌握程度比较薄弱，需强化学习督导和内容巩固。
              </p>
            </div>
          </div>

          <div class="module-section">
            <h4>4.巡检模块</h4>
            <div class="detail-content">
              <p>结合系统试运行进度，本阶段已正式启动<span class="dynamic-text">{{
                reportData?.checkModule?.checkTaskTypeList.map((item => `${item.name}(${item.remark})`)).join("、") ||
                '--'}}</span>巡检任务。目前已发布站级任务<span class="dynamic-text">{{
                    reportData?.checkModule?.checkTaskTypeList.find((item => item.name == '站级'))?.total || '--'
                  }}</span>个，大队级任务<span class="dynamic-text">{{
                    reportData?.checkModule?.checkTaskTypeList.find((item => item.name == '大队级'))?.total || '--'
                  }}</span>个，科级任务<span class="dynamic-text">{{
                    reportData?.checkModule?.checkTaskTypeList.find((item => item.name == '科级'))?.total || '--'
                  }}</span>个，班组级任务<span class="dynamic-text">{{
                    reportData?.checkModule?.checkTaskTypeList.find((item => item.name == '班组级'))?.total || '--'
                  }}</span>个，共提交检查单<span class="dynamic-text">{{
                    reportData?.checkModule?.totalCheckForm || '--' }}</span>份，共发现问题<span class="dynamic-text">{{
                    reportData?.checkModule?.totalProblemItem || '--' }}</span>项。其中发现<span class="dynamic-text">{{
                    (reportData?.checkModule?.checkCategoryTypeList || []).reduce((max,
                      item) => item?.total > max?.total ? item : max, { name: '--', total: 0 })?.name || '--'
                  }}</span>类问题<span class="dynamic-text">{{
                    (reportData?.checkModule?.checkCategoryTypeList || []).reduce((max,
                      item) => item?.total > max?.total ? item : max, { name: '--', total: 0 })?.total || '--'
                  }}</span>项，占比最大。</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ArrowLeft, Download } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getUsageReport } from '@/api/assistant/assistant.js'
import { Document, Packer, Paragraph, TextRun, HeadingLevel, AlignmentType } from 'docx'
import { saveAs } from 'file-saver'

const emit = defineEmits(['back'])

const loading = ref(false)
const dateRange = ref([])

const reportData = ref({

})

const dateRangeText = computed(() => {
  if (dateRange.value && dateRange.value.length === 2) {
    return `${dateRange.value[0]} 至 ${dateRange.value[1]}`
  }
  return '指定时间'
})

const getLastWeekRange = () => {
  const now = new Date()
  const day = now.getDay()
  const diff = now.getDate() - day + (day === 0 ? -6 : 1)
  const lastWeekEnd = new Date(now.setDate(diff - 1))
  const lastWeekStart = new Date(lastWeekEnd)
  lastWeekStart.setDate(lastWeekStart.getDate() - 6)

  const formatDate = (date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  }

  return [formatDate(lastWeekStart), formatDate(lastWeekEnd)]
}

const fetchReportData = async () => {
  if (!dateRange.value || dateRange.value.length !== 2) {
    ElMessage.warning('请选择时间范围')
    return
  }

  loading.value = true
  try {
    const params = {
      startDate: dateRange.value[0],
      endDate: dateRange.value[1]
    }
    const response = await getUsageReport(params)
    if (response.data) {
      reportData.value = {
        ...response.data,
        ...response.data.basicSituation,
        ...response.data.runSituation,
      }
    }
  } catch (error) {
    console.error('获取报表数据失败:', error)
    ElMessage.error('获取报表数据失败')
  } finally {
    loading.value = false
  }
}

const handleBack = () => {
  emit('back')
}

// 处理日期变化
const handleDateChange = () => {
  if (dateRange.value && dateRange.value.length === 2) {
    fetchReportData()
  }
}

const handleExport = async () => {
  try {
    // 提取report-content区域的所有文字内容
    const reportContent = extractReportContent()
    
    // 创建Word文档
    const doc = createWordDocument(reportContent)
    
    // 生成Blob并下载
    const blob = await Packer.toBlob(doc)
    const fileName = `分级质控系统试用情况报告_${dateRange.value[0]}_${dateRange.value[1]}.docx`
    saveAs(blob, fileName)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  }
}

// 提取报表内容
const extractReportContent = () => {
  const content = {
    title: `${dateRangeText.value} 分级质控系统试用情况`,
    basicInfo: {
      title: '一、试运行基本情况',
      content: `目前试用人员覆盖${reportData.value.sysDeptInfoListDesc || '--'}的一线员工及管理岗位，累计 ${reportData.value.totalPeopleNumber || '--'} 人参与。系统试运行聚焦于勤务、查获、抽问抽答、巡检四个核心模块。`
    },
    modules: {
      title: '二、各模块运行情况',
      attendance: {
        title: '1.勤务模块',
        content: `完成情况：本阶段共计 ${reportData.value?.attendanceModule?.totalPeopleNumber || '--'} 名人员完成上下班打卡流程，其中 ${reportData.value?.attendanceModule?.sysDeptInfoListDesc || '--'} 。`
      },
      seizure: {
        title: '2.查获模块',
        content: `系统累计收录查获物品共上报表单${reportData.value?.seizureModule?.totalForm || '--'}份，其中已归档表单${reportData.value?.seizureModule?.totalFormArchived || '--'}份，查获总数 ${reportData.value?.seizureModule?.totalSeizure || '--'} 个，结合情况分析：
违禁品类型：${(reportData.value?.seizureModule?.seizureTypeList || [])[0]?.name || '--'}为查获量最高品类，查获${(reportData.value?.seizureModule?.seizureTypeList || [])[0]?.total || '--'}个，其次为${(reportData.value?.seizureModule?.seizureTypeList || [])[1]?.name || '--'}，查获${(reportData.value?.seizureModule?.seizureTypeList || [])[1]?.total || '--'}个。
查获部位：${reportData.value?.seizureModule?.seizurePartList[0]?.scaleDesc || '--'}以上集中在${reportData.value?.seizureModule?.seizurePartList[0]?.name || '--'}，查获场景集中度高；隐匿物品重点查获部位集中在${reportData.value?.seizureModule?.seizurePartHiddenList[0]?.name || '--'}。
查获岗位：${(reportData.value?.seizureModule?.seizurePositionList || []).sort((a, b) => b?.total - a?.total)[0]?.name || '--'}为核心查获岗位，其次为${(reportData.value?.seizureModule?.seizurePositionList || []).sort((a, b) => b?.total - a?.total)[1]?.name || '--'}。`
      },
      exam: {
        title: '3.抽问抽答模块',
        content: `本阶段共计 ${reportData.value?.examModule?.totalPeopleNumber || '--'} 名人员与该模块学习及测试，累计完成${reportData.value?.examModule?.totalItem || '--'} 项，平均得分 ${reportData.value?.examModule?.averageScore || '--'} 分，其中 ${reportData.value?.examModule?.typeList?.find(item => item.remark == '最高')?.name || '--'}正确率${reportData.value?.examModule?.typeList?.find(item => item.remark == '最高')?.scale || '--'}%掌握程度最好，${reportData.value?.examModule?.typeList?.find(item => item.remark == '薄弱')?.name || '--'}正确率仅为${reportData.value?.examModule?.typeList?.find(item => item.remark == '薄弱')?.scale || '--'}%掌握程度比较薄弱，需强化学习督导和内容巩固。`
      },
      check: {
        title: '4.巡检模块',
        content: `结合系统试运行进度，本阶段已正式启动${reportData.value?.checkModule?.checkTaskTypeList?.map((item) => `${item.name}(${item.remark})`).join('、') || '--'}巡检任务。目前已发布站级任务${reportData.value?.checkModule?.checkTaskTypeList?.find((item) => item.name == '站级')?.total || '--'}个，大队级任务${reportData.value?.checkModule?.checkTaskTypeList?.find((item) => item.name == '大队级')?.total || '--'}个，科级任务${reportData.value?.checkModule?.checkTaskTypeList?.find((item) => item.name == '科级')?.total || '--'}个，班组级任务${reportData.value?.checkModule?.checkTaskTypeList?.find((item) => item.name == '班组级')?.total || '--'}个，共提交检查单${reportData.value?.checkModule?.totalCheckForm || '--'}份，共发现问题${reportData.value?.checkModule?.totalProblemItem || '--'}项。其中发现${(reportData.value?.checkModule?.checkCategoryTypeList || []).reduce((max, item) => item?.total > max?.total ? item : max, { name: '--', total: 0 })?.name || '--'}类问题${(reportData.value?.checkModule?.checkCategoryTypeList || []).reduce((max, item) => item?.total > max?.total ? item : max, { name: '--', total: 0 })?.total || '--'}项，占比最大。`
      }
    }
  }
  
  return content
}

// 创建Word文档
const createWordDocument = (content) => {
  const children = [
    // 标题
    new Paragraph({
      children: [
        new TextRun({
          text: content.title,
          bold: true,
          size: 32
        })
      ],
      alignment: AlignmentType.CENTER,
      spacing: { after: 400 }
    }),
    
    // 基本信息
    new Paragraph({
      children: [
        new TextRun({
          text: content.basicInfo.title,
          bold: true,
          size: 24
        })
      ],
      spacing: { after: 200 }
    }),
    new Paragraph({
      children: [
        new TextRun({
          text: content.basicInfo.content,
          size: 22
        })
      ],
      spacing: { after: 400 }
    }),
    
    // 各模块运行情况标题
    new Paragraph({
      children: [
        new TextRun({
          text: content.modules.title,
          bold: true,
          size: 24
        })
      ],
      spacing: { after: 200 }
    }),
    
    // 勤务模块
    new Paragraph({
      children: [
        new TextRun({
          text: content.modules.attendance.title,
          bold: true,
          size: 22
        })
      ],
      spacing: { after: 150 }
    }),
    new Paragraph({
      children: [
        new TextRun({
          text: content.modules.attendance.content,
          size: 20
        })
      ],
      spacing: { after: 300 }
    }),
    
    // 查获模块
    new Paragraph({
      children: [
        new TextRun({
          text: content.modules.seizure.title,
          bold: true,
          size: 22
        })
      ],
      spacing: { after: 150 }
    }),
    new Paragraph({
      children: [
        new TextRun({
          text: content.modules.seizure.content,
          size: 20
        })
      ],
      spacing: { after: 300 }
    }),
    
    // 抽问抽答模块
    new Paragraph({
      children: [
        new TextRun({
          text: content.modules.exam.title,
          bold: true,
          size: 22
        })
      ],
      spacing: { after: 150 }
    }),
    new Paragraph({
      children: [
        new TextRun({
          text: content.modules.exam.content,
          size: 20
        })
      ],
      spacing: { after: 300 }
    }),
    
    // 巡检模块
    new Paragraph({
      children: [
        new TextRun({
          text: content.modules.check.title,
          bold: true,
          size: 22
        })
      ],
      spacing: { after: 150 }
    }),
    new Paragraph({
      children: [
        new TextRun({
          text: content.modules.check.content,
          size: 20
        })
      ],
      spacing: { after: 300 }
    }),
    
    // 页脚
    new Paragraph({
      children: [
        new TextRun({
          text: '生成时间: ' + new Date().toLocaleString('zh-CN'),
          size: 18,
          color: '666666'
        })
      ],
      alignment: AlignmentType.RIGHT,
      spacing: { before: 600 }
    })
  ]
  
  return new Document({
    sections: [{
      properties: {},
      children: children
    }]
  })
}

onMounted(() => {
  dateRange.value = getLastWeekRange()
  fetchReportData()
})
</script>

<style lang="scss" scoped>
.use-reports {
  width: 100%;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 16px 16px 16px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.back-btn {
  color: #3D3D3D;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.back-btn:hover {
  color: #3D3D3D;
}

.export-btn {
  background-color: transparent;
  color: #557DDB;
  border: 1px solid #557DDB;
  display: flex;
  align-items: center;
  gap: 4px;
}

.export-btn:hover {
  background-color: #557DDB;
  color: white;
}

.query-form {
  background: white;
  border-radius: 8px;
  padding: 12px 18px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.form-container {
  width: 100%;
}

.custom-form .form-row {
  display: flex;
  align-items: flex-start;
  gap: 40px;
}

.custom-form .form-item {
  display: flex;
  align-items: center;
  gap: 6px;
  flex: 1;
}

.custom-form .form-label {
  width: 80px;
  font-size: 14px;
  color: #3D3D3D;
  font-size: 15px;
  text-align: left;
  flex-shrink: 0;
}

.form-content {
  display: flex;
  align-items: center;
  gap: 16px;
  width: 300px;
}

.date-picker {
  width: 300px;
}

.report-content {
  background: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.report-title {
  text-align: center;
  margin-bottom: 30px;
  border-bottom: 2px solid #557DDB;
  padding-bottom: 20px;
}

.report-title h2 {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.stat-cards {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  flex: 1;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  border: 1px solid #e0e0e0;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #557DDB;
}

.report-details {
  padding: 0 20px;
}

.detail-section {
  margin-bottom: 30px;
}

.detail-section h3 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 15px 0;
  padding-bottom: 8px;
  border-bottom: 1px solid #e0e0e0;
}

.module-section {
  margin-bottom: 25px;
}

.module-section h4 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 12px 0;
}

.detail-content {
  font-size: 15px;
  line-height: 2;
  color: #333;
}

.highlight-text {
  color: #557DDB;
  font-weight: 500;
}

.dynamic-text {
  color: #f56c6c;
  font-weight: 600;
}

.trend-text {
  font-weight: 600;

  &.up {
    color: #f56c6c;
  }

  &.down {
    color: #67c23a;
  }

  &.neutral {
    color: #909399;
  }
}

@media (max-width: 768px) {
  .use-reports {
    padding: 16px;
  }

  .header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .header-right {
    align-self: flex-end;
  }

  .form-row {
    flex-direction: column;
    align-items: flex-start;
  }

  .form-content {
    flex-direction: column;
    align-items: flex-start;
  }

  .date-picker {
    width: 400px;
  }

  .stat-cards {
    flex-direction: column;
  }

  .report-content {
    padding: 20px;
  }
}
</style>
