<template>
  <ContentWrap>
    <!-- 搜索表单 -->
    <el-form
      ref="searchFormRef"
      :model="searchForm"
      :inline="true"
      label-width="80px"
      class="-mb-15px"
    >
      <el-form-item label="产品类型" prop="productType">
        <el-select
          v-model="searchForm.productType"
          placeholder="请选择产品类型"
          clearable
          class="!w-240px"
        >
          <el-option label="甜菊糖" value="stevia" />
          <el-option label="番茄酱" value="tomato" />
        </el-select>
      </el-form-item>
      <el-form-item label="时间范围" prop="timeRange">
        <el-date-picker
          v-model="searchForm.timeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          class="!w-420px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery" type="primary">
          <Icon icon="ep:search" class="mr-[5px]" /> 查询
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-[5px]" /> 重置
        </el-button>
        <el-button @click="handleExport" type="success" plain>
          <Icon icon="ep:download" class="mr-[5px]" /> 导出图表
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 趋势图表 -->
  <ContentWrap>
    <div class="trend-chart-container">
      <div class="chart-header">
        <h3>质检指标趋势图</h3>
        <div class="chart-controls">
          <el-button-group>
            <el-button
              :type="chartType === 'line' ? 'primary' : ''"
              @click="chartType = 'line'"
            >
              折线图
            </el-button>
            <el-button
              :type="chartType === 'area' ? 'primary' : ''"
              @click="chartType = 'area'"
            >
              面积图
            </el-button>
          </el-button-group>
        </div>
      </div>

      <!-- 图表容器 -->
      <div
        ref="chartRef"
        class="chart-container"
        v-loading="chartLoading"
      ></div>

      <!-- 指标选择器 -->
      <div class="indicator-selector">
        <div class="selector-title">显示指标：</div>
        <el-checkbox-group v-model="selectedIndicators" @change="updateChart">
          <el-checkbox
            v-for="indicator in availableIndicators"
            :key="indicator.key"
            :label="indicator.key"
            :style="{ color: indicator.color }"
          >
            {{ indicator.name }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
    </div>
  </ContentWrap>

  <!-- 数据统计表格 -->
  <ContentWrap>
    <div class="statistics-container">
      <h4>数据统计</h4>
      <el-table :data="statisticsData" border stripe>
        <el-table-column prop="indicator" label="指标" width="120" />
        <el-table-column prop="average" label="平均值" width="100" />
        <el-table-column prop="max" label="最大值" width="100" />
        <el-table-column prop="min" label="最小值" width="100" />
        <el-table-column prop="latest" label="最新值" width="100" />
        <el-table-column prop="trend" label="趋势" width="80">
          <template #default="{ row }">
            <el-tag
              :type="row.trend === 'up' ? 'danger' : row.trend === 'down' ? 'success' : 'info'"
            >
              {{ row.trend === 'up' ? '上升' : row.trend === 'down' ? '下降' : '平稳' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag
              :type="row.status === 'normal' ? 'success' : row.status === 'warning' ? 'warning' : 'danger'"
            >
              {{ row.status === 'normal' ? '正常' : row.status === 'warning' ? '预警' : '异常' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </ContentWrap>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { getFinishedProductQualityPage } from '@/api/mes/quality/productquality/index'

defineOptions({ name: 'QualityTrend' })

// 搜索表单
const searchForm = reactive({
  productType: 'stevia', // 默认甜菊糖
  timeRange: [] as string[]
})

// 图表相关
const chartRef = ref<HTMLDivElement>()
const chartInstance = ref<echarts.ECharts>()
const chartLoading = ref(false)
const chartType = ref<'line' | 'area'>('line')

// 可用指标配置
const availableIndicators = ref([
  { key: 'ph', name: 'PH值', color: '#5470c6', unit: '' },
  { key: 'rd', name: 'RD', color: '#91cc75', unit: '%' },
  { key: 'ra', name: 'RA', color: '#fac858', unit: '%' },
  { key: 'stv', name: 'STV', color: '#ee6666', unit: '%' },
  { key: 'rf', name: 'RF', color: '#73c0de', unit: '%' },
  { key: 'rc', name: 'RC', color: '#3ba272', unit: '%' },
  { key: 'da', name: 'DA', color: '#fc8452', unit: '%' },
  { key: 'rv', name: 'RV', color: '#9a60b4', unit: '%' },
  { key: 'rb', name: 'RB', color: '#ea7ccc', unit: '%' },
  { key: 'sb', name: 'SB', color: '#5470c6', unit: '%' },
  { key: 'moisture', name: '水分', color: '#91cc75', unit: '%' }
])

// 选中的指标
const selectedIndicators = ref(['ph', 'rd', 'ra', 'stv', 'moisture'])

// 图表数据
const chartData = ref<any>({
  dates: [],
  series: {}
})

// 统计数据
const statisticsData = ref<any[]>([])

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return

  chartInstance.value = echarts.init(chartRef.value)

  // 设置图表配置
  updateChart()

  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    chartInstance.value?.resize()
  })
}

// 更新图表
const updateChart = () => {
  if (!chartInstance.value) return

  const option = {
    title: {
      text: '质检指标趋势分析',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      },
      formatter: (params: any) => {
        let result = `<div style="margin-bottom: 5px">${params[0].axisValue}</div>`
        params.forEach((item: any) => {
          const indicator = availableIndicators.value.find(ind => ind.key === item.seriesName)
          result += `
            <div style="display: flex; align-items: center; margin-bottom: 3px">
              <span style="display: inline-block; width: 10px; height: 10px; background-color: ${item.color}; border-radius: 50%; margin-right: 8px"></span>
              <span style="margin-right: 10px">${indicator?.name || item.seriesName}:</span>
              <span style="font-weight: bold">${item.value}${indicator?.unit || ''}</span>
            </div>
          `
        })
        return result
      }
    },
    legend: {
      data: selectedIndicators.value.map(key => {
        const indicator = availableIndicators.value.find(ind => ind.key === key)
        return indicator?.name || key
      }),
      top: 30,
      type: 'scroll'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    toolbox: {
      feature: {
        saveAsImage: {
          title: '保存为图片'
        },
        dataZoom: {
          title: {
            zoom: '区域缩放',
            back: '区域缩放还原'
          }
        },
        restore: {
          title: '还原'
        }
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: chartData.value.dates,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value}'
      }
    },
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 100
      },
      {
        start: 0,
        end: 100,
        height: 30
      }
    ],
    series: selectedIndicators.value.map(key => {
      const indicator = availableIndicators.value.find(ind => ind.key === key)
      return {
        name: key,
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: {
          width: 2
        },
        areaStyle: chartType.value === 'area' ? {
          opacity: 0.3
        } : undefined,
        data: chartData.value.series[key] || [],
        itemStyle: {
          color: indicator?.color || '#5470c6'
        }
      }
    })
  }

  chartInstance.value.setOption(option, true)
}

// 获取质检数据
const getQualityData = async () => {
  chartLoading.value = true
  try {
    const params: any = {
      pageNo: 1,
      pageSize: 100, // 获取更多数据用于趋势分析
      status: 3 // 只获取已入库的质检数据
    }

    // 添加时间范围过滤
    if (searchForm.timeRange && searchForm.timeRange.length === 2) {
      params.inspectionTime = [
        searchForm.timeRange[0] + ' 00:00:00',
        searchForm.timeRange[1] + ' 23:59:59'
      ]
    }

    const res = await getFinishedProductQualityPage(params)
    const list = res.list || res.data?.list || []

    // 根据产品类型过滤数据
    const filteredList = list.filter((item: any) => {
      if (searchForm.productType === 'stevia') {
        return item.workOrderCode && item.workOrderCode.toUpperCase().startsWith('X') &&
               !item.workOrderCode.toUpperCase().startsWith('X8')
      } else if (searchForm.productType === 'tomato') {
        return item.workOrderCode && item.workOrderCode.toUpperCase().startsWith('X8')
      }
      return true
    })

    // 处理数据
    processChartData(filteredList)
    calculateStatistics(filteredList)

  } catch (error) {
    console.error('获取质检数据失败:', error)
    ElMessage.error('获取质检数据失败')
  } finally {
    chartLoading.value = false
  }
}

// 处理图表数据
const processChartData = (list: any[]) => {
  // 按时间排序
  const sortedList = list
    .filter(item => item.inspectionTime)
    .sort((a, b) => new Date(a.inspectionTime).getTime() - new Date(b.inspectionTime).getTime())

  const dates: string[] = []
  const series: any = {}

  // 初始化系列数据
  availableIndicators.value.forEach(indicator => {
    series[indicator.key] = []
  })

  sortedList.forEach(item => {
    const date = item.inspectionTime.split(' ')[0] // 只取日期部分
    dates.push(date)

    // 根据产品类型提取对应的指标数据
    if (searchForm.productType === 'stevia') {
      series.ph.push(item.steviaPhValue || null)
      series.rd.push(item.steviaRd || null)
      series.ra.push(item.steviaRa || null)
      series.stv.push(item.steviaStv || null)
      series.rf.push(item.steviaRf || null)
      series.rc.push(item.steviaRc || null)
      series.da.push(item.steviaDa || null)
      series.rv.push(item.steviaRv || null)
      series.rb.push(item.steviaRb || null)
      series.sb.push(item.steviaSb || null)
      series.moisture.push(item.steviaMoisture || null)
    } else if (searchForm.productType === 'tomato') {
      series.ph.push(item.tomatoPhValue || null)
      // 番茄产品的其他指标可能不同，这里用默认值
      series.rd.push(null)
      series.ra.push(null)
      series.stv.push(null)
      series.rf.push(null)
      series.rc.push(null)
      series.da.push(null)
      series.rv.push(null)
      series.rb.push(null)
      series.sb.push(null)
      series.moisture.push(null)
    }
  })

  chartData.value = { dates, series }

  // 更新图表
  nextTick(() => {
    updateChart()
  })
}

// 计算统计数据
const calculateStatistics = (_list: any[]) => {
  const stats: any[] = []

  selectedIndicators.value.forEach(key => {
    const indicator = availableIndicators.value.find(ind => ind.key === key)
    if (!indicator) return

    const values = chartData.value.series[key].filter((v: any) => v !== null && v !== undefined)

    if (values.length === 0) {
      stats.push({
        indicator: indicator.name,
        average: '-',
        max: '-',
        min: '-',
        latest: '-',
        trend: 'stable',
        status: 'normal'
      })
      return
    }

    const average = (values.reduce((sum: number, val: number) => sum + val, 0) / values.length).toFixed(2)
    const max = Math.max(...values).toFixed(2)
    const min = Math.min(...values).toFixed(2)
    const latest = values[values.length - 1]?.toFixed(2) || '-'

    // 计算趋势（简单的前后对比）
    let trend = 'stable'
    if (values.length >= 2) {
      const recent = values.slice(-3).reduce((sum: number, val: number) => sum + val, 0) / Math.min(3, values.length)
      const earlier = values.slice(0, Math.max(1, values.length - 3)).reduce((sum: number, val: number) => sum + val, 0) / Math.max(1, values.length - 3)

      if (recent > earlier * 1.05) trend = 'up'
      else if (recent < earlier * 0.95) trend = 'down'
    }

    // 状态判断（这里可以根据实际业务规则调整）
    let status = 'normal'
    const latestValue = parseFloat(latest)
    if (key === 'ph') {
      if (latestValue < 6.0 || latestValue > 8.0) status = 'warning'
      if (latestValue < 5.5 || latestValue > 8.5) status = 'danger'
    } else if (key === 'moisture') {
      if (latestValue > 10) status = 'warning'
      if (latestValue > 15) status = 'danger'
    }

    stats.push({
      indicator: indicator.name,
      average,
      max,
      min,
      latest,
      trend,
      status
    })
  })

  statisticsData.value = stats
}

// 查询操作
const handleQuery = () => {
  getQualityData()
}

// 重置查询
const resetQuery = () => {
  searchForm.productType = 'stevia'
  searchForm.timeRange = []
  getQualityData()
}

// 导出图表
const handleExport = () => {
  if (chartInstance.value) {
    const url = chartInstance.value.getDataURL({
      type: 'png',
      pixelRatio: 2,
      backgroundColor: '#fff'
    })

    const link = document.createElement('a')
    link.download = `质检趋势图_${new Date().toISOString().split('T')[0]}.png`
    link.href = url
    link.click()

    ElMessage.success('图表导出成功')
  }
}

// 监听图表类型变化
watch(chartType, () => {
  updateChart()
})

// 监听产品类型变化
watch(() => searchForm.productType, () => {
  // 根据产品类型调整可用指标
  if (searchForm.productType === 'tomato') {
    selectedIndicators.value = ['ph'] // 番茄产品主要关注PH值
  } else {
    selectedIndicators.value = ['ph', 'rd', 'ra', 'stv', 'moisture'] // 甜菊糖产品的主要指标
  }
  getQualityData()
})

onMounted(() => {
  nextTick(() => {
    initChart()
    getQualityData()
  })
})
</script>

<style scoped>
.trend-chart-container {
  padding: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-header h3 {
  margin: 0;
  color: #303133;
}

.chart-container {
  width: 100%;
  height: 500px;
  margin-bottom: 20px;
}

.indicator-selector {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

.selector-title {
  font-weight: bold;
  color: #606266;
  margin-right: 15px;
}

.statistics-container {
  padding: 20px;
}

.statistics-container h4 {
  margin: 0 0 15px 0;
  color: #303133;
}

:deep(.el-checkbox) {
  margin-right: 20px;
  margin-bottom: 10px;
}

:deep(.el-checkbox__label) {
  font-weight: 500;
}

/* 保持 checkbox 选中后文字颜色不变 */
:deep(.el-checkbox.is-checked .el-checkbox__label) {
  color: inherit !important;
}
</style>
