<template>
  <div>
    <h1>检疫报表导出</h1>
    
    <!-- 搜索和筛选条件 -->
    <a-card style="margin-bottom: 16px;">
      <div style="display: flex; flex-wrap: wrap; gap: 16px; align-items: center;">
        <a-select v-model:value="reportType" placeholder="报表类型" style="width: 200px;">
          <a-select-option value="daily">日报</a-select-option>
          <a-select-option value="weekly">周报</a-select-option>
          <a-select-option value="monthly">月报</a-select-option>
          <a-select-option value="quarterly">季报</a-select-option>
          <a-select-option value="yearly">年报</a-select-option>
          <a-select-option value="custom">自定义报表</a-select-option>
        </a-select>
        
        <div v-if="reportType === 'custom'" style="display: flex; gap: 16px;">
          <a-date-picker
            v-model:value="dateRange[0]"
            placeholder="开始日期"
            style="width: 180px;"
          />
          <span style="line-height: 32px;">至</span>
          <a-date-picker
            v-model:value="dateRange[1]"
            placeholder="结束日期"
            style="width: 180px;"
          />
        </div>
        
        <a-select v-model:value="quarantineType" placeholder="检疫类型" style="width: 150px;">
          <a-select-option value="">全部</a-select-option>
          <a-select-option value="animal">动物检疫</a-select-option>
          <a-select-option value="product">动物产品检疫</a-select-option>
          <a-select-option value="transport">运输检疫</a-select-option>
          <a-select-option value="slaughter">屠宰检疫</a-select-option>
          <a-select-option value="other">其他检疫</a-select-option>
        </a-select>
        
        <a-select v-model:value="reportFormat" placeholder="导出格式" style="width: 120px;">
          <a-select-option value="excel">Excel</a-select-option>
          <a-select-option value="pdf">PDF</a-select-option>
          <a-select-option value="csv">CSV</a-select-option>
        </a-select>
        
        <a-button type="primary" @click="handleGenerateReport" style="margin-left: auto;">
          <span class="iconfont icon-baocun"></span> 生成报表
        </a-button>
      </div>
    </a-card>
    
    <!-- 报表配置 -->
    <a-card style="margin-bottom: 16px;">
      <h3>报表配置</h3>
      <div style="display: flex; flex-wrap: wrap; gap: 24px; margin-top: 16px;">
        <div style="flex: 1; min-width: 300px;">
          <h4 style="margin-bottom: 12px;">报表内容</h4>
          <a-checkbox-group v-model:value="reportContents">
            <a-checkbox value="quarantineCount">检疫数量统计</a-checkbox><br/>
            <a-checkbox value="quarantineResult">检疫结果统计</a-checkbox><br/>
            <a-checkbox value="quarantineType">检疫类型分布</a-checkbox><br/>
            <a-checkbox value="quarantineLocation">检疫地点分布</a-checkbox><br/>
            <a-checkbox value="quarantinePersonnel">检疫人员工作量</a-checkbox><br/>
            <a-checkbox value="problemAnalysis">问题分析</a-checkbox><br/>
            <a-checkbox value="trendAnalysis">趋势分析</a-checkbox><br/>
          </a-checkbox-group>
        </div>
        
        <div style="flex: 1; min-width: 300px;">
          <h4 style="margin-bottom: 12px;">报表样式</h4>
          <a-radio-group v-model:value="reportStyle">
            <a-radio :value="'summary'">简洁汇总</a-radio><br/>
            <a-radio :value="'detailed'">详细报表</a-radio><br/>
            <a-radio :value="'graphical'">图文并茂</a-radio><br/>
          </a-radio-group>
          
          <div style="margin-top: 16px;">
            <a-checkbox v-model:checked="includeChart">包含图表</a-checkbox><br/>
            <a-checkbox v-model:checked="includeComparison">包含同比环比</a-checkbox><br/>
            <a-checkbox v-model:checked="includeRecommendations">包含建议分析</a-checkbox><br/>
          </div>
        </div>
      </div>
    </a-card>
    
    <!-- 报表预览 -->
    <a-card>
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
        <h3>报表预览</h3>
        <a-button v-if="generatedReport" type="primary" danger @click="handleDownloadReport">
          <span class="iconfont icon-xiazai"></span> 下载报表
        </a-button>
      </div>
      
      <div v-if="!generatedReport">
        <p style="text-align: center; color: #999; padding: 40px 0;">请选择报表类型和筛选条件，点击生成报表按钮</p>
      </div>
      
      <div v-else class="report-preview">
        <!-- 报表头部 -->
        <div class="report-header">
          <h2>动物检疫统计报表</h2>
          <div class="report-info">
            <span>报表类型：{{ getReportTypeText() }}</span>
            <span>统计时间：{{ getReportTimeRange() }}</span>
            <span>生成时间：{{ generateTime }}</span>
          </div>
        </div>
        
        <!-- 报表内容 -->
        <div class="report-content">
          <!-- 检疫数量统计 -->
          <div v-if="reportContents.includes('quarantineCount')" class="report-section">
            <h3>一、检疫数量统计</h3>
            <a-table :data-source="quarantineCountData" :columns="quarantineCountColumns" pagination="false" :size="'small'" :bordered="true" style="margin-top: 16px;">
            </a-table>
            
            <!-- 图表 -->
            <div v-if="includeChart" ref="quarantineCountChart" style="height: 300px; margin-top: 20px;"></div>
          </div>
          
          <!-- 检疫结果统计 -->
          <div v-if="reportContents.includes('quarantineResult')" class="report-section">
            <h3>二、检疫结果统计</h3>
            <a-table :data-source="quarantineResultData" :columns="quarantineResultColumns" pagination="false" :size="'small'" :bordered="true" style="margin-top: 16px;">
            </a-table>
            
            <!-- 图表 -->
            <div v-if="includeChart" ref="quarantineResultChart" style="height: 300px; margin-top: 20px;"></div>
          </div>
          
          <!-- 检疫类型分布 -->
          <div v-if="reportContents.includes('quarantineType')" class="report-section">
            <h3>三、检疫类型分布</h3>
            <a-table :data-source="quarantineTypeData" :columns="quarantineTypeColumns" pagination="false" :size="'small'" :bordered="true" style="margin-top: 16px;">
            </a-table>
            
            <!-- 图表 -->
            <div v-if="includeChart" ref="quarantineTypeChart" style="height: 300px; margin-top: 20px;"></div>
          </div>
          
          <!-- 检疫地点分布 -->
          <div v-if="reportContents.includes('quarantineLocation')" class="report-section">
            <h3>四、检疫地点分布</h3>
            <a-table :data-source="quarantineLocationData" :columns="quarantineLocationColumns" pagination="false" :size="'small'" :bordered="true" style="margin-top: 16px;">
            </a-table>
          </div>
          
          <!-- 检疫人员工作量 -->
          <div v-if="reportContents.includes('quarantinePersonnel')" class="report-section">
            <h3>五、检疫人员工作量</h3>
            <a-table :data-source="quarantinePersonnelData" :columns="quarantinePersonnelColumns" pagination="false" :size="'small'" :bordered="true" style="margin-top: 16px;">
            </a-table>
          </div>
          
          <!-- 问题分析 -->
          <div v-if="reportContents.includes('problemAnalysis')" class="report-section">
            <h3>六、问题分析</h3>
            <div class="analysis-content">
              <p>根据统计数据，本期检疫工作中主要存在以下问题：</p>
              <ol>
                <li>部分地区动物检疫申报不及时，影响检疫效率</li>
                <li>个别养殖场的防疫条件有待改善，存在一定风险</li>
                <li>运输检疫中，部分运输工具消毒不彻底</li>
                <li>基层检疫人员专业技能需要进一步提升</li>
              </ol>
            </div>
          </div>
          
          <!-- 趋势分析 -->
          <div v-if="reportContents.includes('trendAnalysis')" class="report-section">
            <h3>七、趋势分析</h3>
            <div v-if="includeChart" ref="trendAnalysisChart" style="height: 300px;"></div>
            <div v-else class="analysis-content">
              <p>本期检疫数量较上期有所增加，主要原因是：</p>
              <ol>
                <li>养殖规模扩大，出栏量增加</li>
                <li>加强了检疫宣传，申报意识提高</li>
                <li>运输量增加，运输检疫需求增长</li>
              </ol>
            </div>
          </div>
        </div>
      </div>
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { message } from 'ant-design-vue'
import * as echarts from 'echarts'

// 报表类型
const reportType = ref('monthly')

// 日期范围
const dateRange = ref([null, null])

// 检疫类型筛选
const quarantineType = ref('')

// 导出格式
const reportFormat = ref('excel')

// 报表内容选项
const reportContents = ref(['quarantineCount', 'quarantineResult', 'quarantineType'])

// 报表样式
const reportStyle = ref('summary')

// 是否包含图表
const includeChart = ref(true)

// 是否包含同比环比
const includeComparison = ref(true)

// 是否包含建议分析
const includeRecommendations = ref(true)

// 是否已生成报表
const generatedReport = ref(false)

// 报表生成时间
const generateTime = ref('')

// 检疫数量统计数据（模拟数据）
const quarantineCountData = ref([
  { type: '动物检疫', count: 1256, increase: 12.5 },
  { type: '动物产品检疫', count: 897, increase: 8.3 },
  { type: '运输检疫', count: 654, increase: 15.2 },
  { type: '屠宰检疫', count: 987, increase: 5.7 },
  { type: '其他检疫', count: 324, increase: 2.1 }
])

// 检疫数量统计列定义
const quarantineCountColumns = [
  { title: '检疫类型', dataIndex: 'type', key: 'type' },
  { title: '检疫数量', dataIndex: 'count', key: 'count' },
  { title: '同比增长(%)', dataIndex: 'increase', key: 'increase' }
]

// 检疫结果统计数据（模拟数据）
const quarantineResultData = ref([
  { result: '合格', count: 3521, rate: 92.3 },
  { result: '不合格', count: 293, rate: 7.7 }
])

// 检疫结果统计列定义
const quarantineResultColumns = [
  { title: '检疫结果', dataIndex: 'result', key: 'result' },
  { title: '数量', dataIndex: 'count', key: 'count' },
  { title: '占比(%)', dataIndex: 'rate', key: 'rate' }
]

// 检疫类型分布数据（模拟数据）
const quarantineTypeData = ref([
  { type: '生猪', count: 1567, rate: 40.9 },
  { type: '家禽', count: 897, rate: 23.3 },
  { type: '牛', count: 654, rate: 17.0 },
  { type: '羊', count: 324, rate: 8.4 },
  { type: '其他', count: 397, rate: 10.3 }
])

// 检疫类型分布列定义
const quarantineTypeColumns = [
  { title: '动物类型', dataIndex: 'type', key: 'type' },
  { title: '数量', dataIndex: 'count', key: 'count' },
  { title: '占比(%)', dataIndex: 'rate', key: 'rate' }
]

// 检疫地点分布数据（模拟数据）
const quarantineLocationData = ref([
  { location: '养殖场', count: 1897, rate: 49.4 },
  { location: '屠宰场', count: 987, rate: 25.7 },
  { location: '交易市场', count: 654, rate: 17.0 },
  { location: '运输环节', count: 324, rate: 8.4 }
])

// 检疫地点分布列定义
const quarantineLocationColumns = [
  { title: '检疫地点', dataIndex: 'location', key: 'location' },
  { title: '数量', dataIndex: 'count', key: 'count' },
  { title: '占比(%)', dataIndex: 'rate', key: 'rate' }
]

// 检疫人员工作量数据（模拟数据）
const quarantinePersonnelData = ref([
  { name: '张三', count: 567, rate: 14.8 },
  { name: '李四', count: 489, rate: 12.8 },
  { name: '王五', count: 456, rate: 11.9 },
  { name: '赵六', count: 423, rate: 11.0 },
  { name: '钱七', count: 398, rate: 10.4 },
  { name: '孙八', count: 376, rate: 9.8 },
  { name: '周九', count: 356, rate: 9.3 },
  { name: '吴十', count: 334, rate: 8.7 }
])

// 检疫人员工作量列定义
const quarantinePersonnelColumns = [
  { title: '检疫人员', dataIndex: 'name', key: 'name' },
  { title: '检疫数量', dataIndex: 'count', key: 'count' },
  { title: '占比(%)', dataIndex: 'rate', key: 'rate' }
]

// 图表引用
const quarantineCountChart = ref(null)
const quarantineResultChart = ref(null)
const quarantineTypeChart = ref(null)
const trendAnalysisChart = ref(null)

// 图表实例
let quarantineCountChartInstance = null
let quarantineResultChartInstance = null
let quarantineTypeChartInstance = null
let trendAnalysisChartInstance = null

// 获取报表类型文本
const getReportTypeText = () => {
  const typeMap = {
    daily: '日报',
    weekly: '周报',
    monthly: '月报',
    quarterly: '季报',
    yearly: '年报',
    custom: '自定义报表'
  }
  return typeMap[reportType.value] || ''
}

// 获取报表时间范围
const getReportTimeRange = () => {
  if (reportType.value === 'custom' && dateRange.value[0] && dateRange.value[1]) {
    return `${formatDate(dateRange.value[0])} 至 ${formatDate(dateRange.value[1])}`
  } else {
    // 根据报表类型返回默认时间范围
    const now = new Date()
    let startDate, endDate
    
    switch (reportType.value) {
      case 'daily':
        startDate = now
        endDate = now
        break
      case 'weekly':
        startDate = new Date(now.getTime() - (now.getDay() || 7) * 24 * 60 * 60 * 1000)
        endDate = new Date(startDate.getTime() + 6 * 24 * 60 * 60 * 1000)
        break
      case 'monthly':
        startDate = new Date(now.getFullYear(), now.getMonth(), 1)
        endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0)
        break
      case 'quarterly':
        const quarter = Math.floor(now.getMonth() / 3)
        startDate = new Date(now.getFullYear(), quarter * 3, 1)
        endDate = new Date(now.getFullYear(), quarter * 3 + 3, 0)
        break
      case 'yearly':
        startDate = new Date(now.getFullYear(), 0, 1)
        endDate = new Date(now.getFullYear(), 11, 31)
        break
      default:
        startDate = now
        endDate = now
    }
    
    return `${formatDate(startDate)} 至 ${formatDate(endDate)}`
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 生成报表
const handleGenerateReport = () => {
  // 在实际应用中，这里应该调用API获取数据
  generateTime.value = new Date().toLocaleString('zh-CN')
  generatedReport.value = true
  
  // 等待DOM更新后初始化图表
  nextTick(() => {
    if (includeChart.value) {
      initCharts()
    }
  })
  
  message.success('报表生成成功')
}

// 下载报表
const handleDownloadReport = () => {
  // 在实际应用中，这里应该调用API下载报表
  message.success(`报表已以${getFormatText(reportFormat.value)}格式下载`)
}

// 获取导出格式文本
const getFormatText = (format) => {
  const formatMap = {
    excel: 'Excel',
    pdf: 'PDF',
    csv: 'CSV'
  }
  return formatMap[format] || format
}

// 初始化图表
const initCharts = () => {
  // 销毁已存在的图表实例
  if (quarantineCountChartInstance) {
    quarantineCountChartInstance.dispose()
  }
  if (quarantineResultChartInstance) {
    quarantineResultChartInstance.dispose()
  }
  if (quarantineTypeChartInstance) {
    quarantineTypeChartInstance.dispose()
  }
  if (trendAnalysisChartInstance) {
    trendAnalysisChartInstance.dispose()
  }
  
  // 初始化检疫数量统计图表
  if (quarantineCountChart.value && reportContents.value.includes('quarantineCount')) {
    quarantineCountChartInstance = echarts.init(quarantineCountChart.value)
    const option = {
      title: {
        text: '检疫数量统计',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: quarantineCountData.value.map(item => item.type)
      },
      yAxis: [
        {
          type: 'value',
          name: '检疫数量',
          position: 'left'
        },
        {
          type: 'value',
          name: '增长率(%)',
          position: 'right',
          axisLabel: {
            formatter: '{value}%'
          }
        }
      ],
      series: [
        {
          name: '检疫数量',
          type: 'bar',
          data: quarantineCountData.value.map(item => item.count)
        },
        {
          name: '增长率',
          type: 'line',
          yAxisIndex: 1,
          data: quarantineCountData.value.map(item => item.increase),
          axisLabel: {
            formatter: '{value}%'
          }
        }
      ]
    }
    quarantineCountChartInstance.setOption(option)
  }
  
  // 初始化检疫结果统计图表
  if (quarantineResultChart.value && reportContents.value.includes('quarantineResult')) {
    quarantineResultChartInstance = echarts.init(quarantineResultChart.value)
    const option = {
      title: {
        text: '检疫结果统计',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '检疫结果',
          type: 'pie',
          radius: '50%',
          data: quarantineResultData.value.map(item => ({
            value: item.count,
            name: item.result
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          label: {
            formatter: '{b}: {c} ({d}%)'
          }
        }
      ]
    }
    quarantineResultChartInstance.setOption(option)
  }
  
  // 初始化检疫类型分布图表
  if (quarantineTypeChart.value && reportContents.value.includes('quarantineType')) {
    quarantineTypeChartInstance = echarts.init(quarantineTypeChart.value)
    const option = {
      title: {
        text: '检疫类型分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '动物类型',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 20,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: quarantineTypeData.value.map(item => ({
            value: item.count,
            name: item.type
          }))
        }
      ]
    }
    quarantineTypeChartInstance.setOption(option)
  }
  
  // 初始化趋势分析图表
  if (trendAnalysisChart.value && reportContents.value.includes('trendAnalysis')) {
    trendAnalysisChartInstance = echarts.init(trendAnalysisChart.value)
    const option = {
      title: {
        text: '检疫数量趋势分析',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['动物检疫', '动物产品检疫', '运输检疫'],
        bottom: 0
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '动物检疫',
          type: 'line',
          data: [1200, 1100, 1300, 1250, 1400, 1350, 1500, 1450, 1600, 1550, 1700, 1650]
        },
        {
          name: '动物产品检疫',
          type: 'line',
          data: [800, 850, 820, 900, 880, 950, 920, 980, 1000, 960, 1050, 1020]
        },
        {
          name: '运输检疫',
          type: 'line',
          data: [600, 650, 700, 680, 750, 720, 800, 780, 850, 830, 900, 880]
        }
      ]
    }
    trendAnalysisChartInstance.setOption(option)
  }
}

// 组件挂载时
onMounted(() => {
  // 监听窗口大小变化，调整图表
  window.addEventListener('resize', () => {
    if (quarantineCountChartInstance) {
      quarantineCountChartInstance.resize()
    }
    if (quarantineResultChartInstance) {
      quarantineResultChartInstance.resize()
    }
    if (quarantineTypeChartInstance) {
      quarantineTypeChartInstance.resize()
    }
    if (trendAnalysisChartInstance) {
      trendAnalysisChartInstance.resize()
    }
  })
})

// 组件卸载时
const onUnmounted = () => {
  // 销毁图表实例
  if (quarantineCountChartInstance) {
    quarantineCountChartInstance.dispose()
  }
  if (quarantineResultChartInstance) {
    quarantineResultChartInstance.dispose()
  }
  if (quarantineTypeChartInstance) {
    quarantineTypeChartInstance.dispose()
  }
  if (trendAnalysisChartInstance) {
    trendAnalysisChartInstance.dispose()
  }
  
  // 移除事件监听
  window.removeEventListener('resize', () => {
    // 清理事件监听
  })
}
</script>

<style scoped>
  h1 {
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 20px;
    color: #333;
  }
  
  h3 {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 12px;
    color: #333;
  }
  
  h4 {
    font-size: 14px;
    font-weight: 600;
    color: #555;
  }
  
  .report-preview {
    background: white;
    padding: 20px;
    border: 1px solid #e8e8e8;
  }
  
  .report-header {
    text-align: center;
    margin-bottom: 30px;
  }
  
  .report-header h2 {
    font-size: 24px;
    font-weight: 600;
    margin-bottom: 10px;
    color: #333;
  }
  
  .report-info {
    display: flex;
    justify-content: center;
    gap: 30px;
    font-size: 14px;
    color: #666;
  }
  
  .report-content {
    margin-top: 20px;
  }
  
  .report-section {
    margin-bottom: 30px;
  }
  
  .report-section h3 {
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 15px;
    color: #333;
    padding-bottom: 10px;
    border-bottom: 2px solid #1890ff;
  }
  
  .analysis-content {
    padding: 15px;
    background: #f9f9f9;
    border-left: 4px solid #1890ff;
    font-size: 14px;
    line-height: 1.8;
  }
  
  .analysis-content p {
    margin-bottom: 10px;
  }
  
  .analysis-content ol {
    padding-left: 20px;
  }
  
  .analysis-content li {
    margin-bottom: 5px;
  }
</style>