<template>
  <view class="qa-analysis mobile-section">
    <!-- 抽问抽答标题 -->
    <view class="section-title">
      <text class="title-text">抽问抽答</text>
    </view>

    <!-- 三个横向均分的内容区域 -->
    <view class="three-panel-layout">
      <!-- 第一个：答题完成趋势 -->
      <view class="panel-item">
        <view class="panel-header">
          <text class="header-text">答题完成趋势</text>
        </view>

        <!-- 描述卡片 -->
        <view class="describe-card">
          <view class="describe-content">
            {{ completionTrendDescription }}
          </view>
        </view>

        <!-- 折线图 -->
        <view class="chart-container">
          <view ref="completionTrendChartRef" class="echarts-chart"></view>
        </view>
      </view>

      <!-- 第二个：错题分布 -->
      <view class="panel-item">
        <view class="panel-header">
          <text class="header-text">错题分布</text>
        </view>

        <!-- 描述卡片 -->
        <view class="describe-card">
          <view class="describe-content">
            {{ errorDistributionDescription }}
          </view>
        </view>

        <!-- 饼图 -->
        <view class="chart-container">
          <view ref="errorDistributionChartRef" class="echarts-chart"></view>
        </view>
      </view>

      <!-- 第三个：各科错题分布对比 -->
      <view class="panel-item" v-show="isStationType">
        <view class="panel-header">
          <text class="header-text">各科错题分布对比</text>
        </view>

        <!-- 描述卡片 -->
        <view class="describe-card">
          <view class="describe-content">
            {{ departmentComparisonDescription }}
          </view>
        </view>

        <!-- 雷达图 -->
        <view class="chart-container">
          <view ref="departmentComparisonChartRef" class="echarts-chart"></view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import * as echarts from 'echarts'
import { getCompletionTrend, getWrongAnalysisOverview, getWrongAnalysisRadar } from '@/api/qualityControlAnalysisReport/qualityControlAnalysisReport'

export default {
  name: 'QaAnalysis',
  props: {
    queryForm: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      completionTrendDescription: '',
      errorDistributionDescription: '',
      departmentComparisonDescription: '',
      loading: false,
      completionTrendChart: null,
      errorDistributionChart: null,
      departmentComparisonChart: null
    }
  },

  computed: {
    // 计算属性：检查是否为STATION类型
    isStationType() {
      const roles = this.$store.state?.user?.roles || []


      return roles.includes('zhijianke') || roles.includes('test')
    }
  },

  mounted() {
    this.loadData()
    this.$nextTick(() => {
      this.initCharts()
    })
  },

  beforeDestroy() {
    this.disposeCharts()
  },

  watch: {
    queryForm: {
      handler() {
        this.loadData()
      },
      deep: true
    },

  },

  methods: {
    // 初始化图表
    initCharts() {
      // 答题完成趋势折线图
      if (this.$refs.completionTrendChartRef) {
        this.initCompletionTrendChart()
      }

      // 错题分布饼图
      if (this.$refs.errorDistributionChartRef) {
        this.initErrorDistributionChart()
      }

      // 各科错题分布对比雷达图
      if (this.$refs.departmentComparisonChartRef) {
        this.initDepartmentComparisonChart()
      }
    },

    // 初始化答题完成趋势折线图
    initCompletionTrendChart() {
      const completionTrendOptions = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: []
        },
        grid: {
          left: '10%',
          right: '8%',
          top: '45%',
          bottom: '10%',
          // containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: []
        },
        yAxis: {
          type: 'value'
        },
        series: []
      }

      this.completionTrendChart = this.createEChartsInstance(this.$refs.completionTrendChartRef, completionTrendOptions)
    },

    // 初始化错题分布饼图
    initErrorDistributionChart() {
      const errorDistributionOptions = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'horizontal',

          top: 0
        },
        series: [
          {
            name: '错题分布',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 12,
                fontWeight: 'bold'
              }
            },
            label: {
              show: true,
              formatter: '{b}\n{c} ({d}%)',
              fontSize: 12,
              fontWeight: 'normal'
            },
            labelLine: {
              show: true,
              length: 10,
              length2: 20
            },
            data: []
          }
        ]
      }

      this.errorDistributionChart = this.createEChartsInstance(this.$refs.errorDistributionChartRef, errorDistributionOptions)
    },

    // 初始化各科错题分布对比雷达图
    initDepartmentComparisonChart() {
      const departmentComparisonOptions = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          show: true,
          orient: 'horizontal',
          top: 0
        },
        // grid: {
          
     
        //   top: '30%',
         
          
        // },
        radar: {
          indicator: [],
          radius: '50%', // 缩小雷达图半径
          center: ['50%', '65%'] // 调整雷达图位置
        },
        series: [
          {
            type: 'radar',
            data: [],
            areaStyle: {}
          }
        ]
      }

      this.departmentComparisonChart = this.createEChartsInstance(this.$refs.departmentComparisonChartRef, departmentComparisonOptions)
    },

    // 创建ECharts实例（适配uni-app环境）
    createEChartsInstance(chartRef, options) {
      if (!chartRef) return null

      // 获取DOM元素
      const chartDom = chartRef.$el || chartRef
      if (!chartDom) return null

      // 创建ECharts实例
      const chartInstance = echarts.init(chartDom)

      // 设置初始选项
      if (options) {
        chartInstance.setOption(options)
      }

      return chartInstance
    },

    // 销毁图表
    disposeCharts() {
      if (this.completionTrendChart) {
        this.completionTrendChart.dispose()
        this.completionTrendChart = null
      }
      if (this.errorDistributionChart) {
        this.errorDistributionChart.dispose()
        this.errorDistributionChart = null
      }
      if (this.departmentComparisonChart) {
        this.departmentComparisonChart.dispose()
        this.departmentComparisonChart = null
      }
    },

    // 加载数据
    async loadData() {
      if (this.loading) return

      this.loading = true
      try {
        // 检查是否为站类型
        this.checkStationType()

        // 加载答题完成趋势数据
        await this.fetchCompletionTrendData()

        // 加载错题分布数据
        await this.fetchWrongAnalysisOverviewData()

        // 如果是站类型，加载各科错题分布对比数据
        if (this.isStationType) {
          await this.fetchWrongAnalysisRadarData()
        }

      } catch (error) {
        console.error('加载抽问抽答数据失败:', error)
      
      } finally {
        this.loading = false
      }
    },

    // 检查是否为站类型（已废弃，使用computed属性替代）
    checkStationType() {
      // 此方法已废弃，角色判断现在通过computed属性实现
    },

    // 处理查询参数
    processQueryParams() {
      const processedParams = { ...this.queryForm }



      return {
        ...processedParams,
        scopeType: processedParams.scopedType == 'TEAMS' ? 'TEAM' : processedParams.scopedType,
        scopeId: processedParams.scopedId,
        yearOnYear: '',
        chainRatio: ''
      }
    },

    // 获取答题完成趋势数据
    async fetchCompletionTrendData() {
      try {
        const processedParams = this.processQueryParams()
        const response = await getCompletionTrend(processedParams)

        if (response.code === 200) {
          const { processedData, xAxisData } = this.processApiData(response || {})

          // 生成描述文本
          this.completionTrendDescription = this.generateCompletionTrendDescription(processedData, xAxisData)

          // 更新图表
          this.updateCompletionTrendChart(processedData, xAxisData)
        }

      } catch (error) {
        console.error('获取答题完成趋势数据失败:', error)
        throw error
      }
    },

    // 获取错题分布数据
    async fetchWrongAnalysisOverviewData() {
      try {
        const processedParams = this.processQueryParams()
        const response = await getWrongAnalysisOverview(processedParams)


        const pieData = this.processOverviewData(response || {})

        // 生成描述文本
        this.errorDistributionDescription = this.generateErrorDistributionDescription(pieData)

        // 更新图表
        this.updateErrorDistributionChart(pieData)

      } catch (error) {
        console.error('获取错题分布数据失败:', error)
        throw error
      }
    },

    // 获取各科错题分布对比数据
    async fetchWrongAnalysisRadarData() {
      try {
        const processedParams = this.processQueryParams()
        const response = await getWrongAnalysisRadar(processedParams)

        // if (response.code === 200) {
        const radarData = this.processRadarData(response || {})

        // 生成描述文本
        this.departmentComparisonDescription = this.generateDepartmentComparisonDescription(radarData)

        // 更新图表
        this.updateDepartmentComparisonChart(radarData)
        // }

      } catch (error) {
        console.error('获取各科错题分布对比数据失败:', error)
        throw error
      }
    },

    // 处理API数据
    processApiData(apiData) {
      if (!apiData || !apiData.model) {
        return { processedData: [], xAxisData: [] }
      }

      const { xAxis, series } = apiData.model

      // 处理x轴数据
      const xAxisData = xAxis || []

      // 处理系列数据
      const processedData = []

      if (series && series.length > 0) {
        for (let i = 0; i < series.length; i++) {
          const numericData = series[i].data.map(item => {
            if (typeof item === 'string') {
              return parseFloat(item) || 0
            }
            return Number(item) || 0
          })

          processedData.push({
            name: series[i].name,
            type: 'line',
            data: numericData,
            symbol: 'circle',
            symbolSize: 6,
            smooth: true,
            lineStyle: {
              width: 3
            }
          })
        }
      }

      return { processedData, xAxisData }
    },

    // 处理总体问题分布数据
    processOverviewData(apiData) {
      const { categories } = apiData.model

      if (!categories || !categories.length) return []

      return categories.map(category => ({
        id: category.id,
        value: category.count,
        name: category.name
      }))
    },

    // 处理雷达图数据
    processRadarData(apiData) {
      const { indicators, series } = apiData.model

      if (!apiData || !indicators || !series) return { indicators: [], series: [] }

      return { indicators, series }
    },

    // 生成答题完成趋势描述
    generateCompletionTrendDescription(processedData, xAxisData) {
      if (!processedData.length || !xAxisData.length) {
        return '暂无数据'
      }



      // 找到全站数据
      let stationData = processedData.find(item => item.name === '全站')?.data || []

      // 找到除了全站之外的其他主管数据
      const otherDepartments = processedData.filter(item => item.name !== '全站')

      let maxData = null
      let maxDataPercent = '0.00'

      if (otherDepartments.length > 0) {
        // 如果有其他主管数据，找出完成人数最多的主管
        maxData = otherDepartments.reduce((max, item) => {
          if (item.data[item.data.length - 1] > max.data[max.data.length - 1]) {
            return item
          }
          return max
        }, otherDepartments[0])

        // 防止除数为0或NaN
        const stationLastValue = stationData[stationData.length - 1] || 0
        if (stationLastValue > 0) {
          maxDataPercent = ((maxData.data[maxData.data.length - 1] / stationLastValue) * 100).toFixed(2)
        } else {
          maxDataPercent = '0.00'
        }
      }

      // 安全获取数组元素，防止NaN
      const lastValue = stationData[stationData.length - 1] || 0
      const firstValue = stationData[0] || 0
      const secondValue = stationData[1] || 0

      // 计算同比
      let tongValue = 0
      if (firstValue > 0) {
        tongValue = ((lastValue - firstValue) / firstValue) * 100
      }
      let tong = firstValue === 0 ? '--' : (tongValue > 0 ? '+' : '') + tongValue.toFixed(2)

      // 计算环比
      let huanValue = 0
      if (secondValue > 0) {
        huanValue = ((lastValue - secondValue) / secondValue) * 100
      }
      let huan = secondValue === 0 ? '--' : (huanValue > 0 ? '+' : '') + huanValue.toFixed(2)

      // 安全获取maxData数组元素，防止NaN
      let maxDataLastValue = 0
      let maxDataFirstValue = 0
      let maxDataSecondValue = 0
      let maxDataTong = '--'
      let maxDataHuan = '--'

      if (maxData && maxData.data) {
        maxDataLastValue = maxData.data[maxData.data.length - 1] || 0
        maxDataFirstValue = maxData.data[0] || 0
        maxDataSecondValue = maxData.data[1] || 0

        // 计算maxData同比
        let maxDataTongValue = 0
        if (maxDataFirstValue > 0) {
          maxDataTongValue = ((maxDataLastValue - maxDataFirstValue) / maxDataFirstValue) * 100
        }
        maxDataTong = maxDataFirstValue === 0 ? '--' : (maxDataTongValue > 0 ? '+' : (maxDataTongValue < 0 ? '' : '')) + maxDataTongValue.toFixed(2)

        // 计算maxData环比
        let maxDataHuanValue = 0
        if (maxDataSecondValue > 0) {
          maxDataHuanValue = ((maxDataLastValue - maxDataSecondValue) / maxDataSecondValue) * 100
        }
        maxDataHuan = maxDataSecondValue === 0 ? '--' : (maxDataHuanValue > 0 ? '+' : (maxDataHuanValue < 0 ? '' : '')) + maxDataHuanValue.toFixed(2)
      }

      // 根据查询条件决定显示内容
      let descriptionText = ''
      let totalPerson = stationData[stationData.length - 1] || 0

      if (maxData) {
        // 有其他主管数据时显示主管信息
        if (this.queryForm.dateRangeQueryType === 'YEAR') {
          const firstYearStr = this.isStationType ? `${maxData.name}共答题${totalPerson}人次，同比${tong}%，` : ''
          const secondYearStr = this.isStationType ? `${maxData.name}共答题${maxData.data[maxData.data.length - 1]}人次，占比最高为${maxDataPercent}%。` : `${maxData.name}完成${maxDataLastValue}人次，同比${maxDataTong}%。`
          // 年查询：只显示同比，隐藏环比
          descriptionText = `${firstYearStr}${secondYearStr}`
        } else {
          const firstNotYearStr = this.isStationType ? `${maxData.name}共答题${totalPerson}人次，同比${tong}%，环比${huan}%，` : ''
          const secondNotYearStr = this.isStationType ? `${maxData.name}共答题${maxData.data[maxData.data.length - 1]}人次，占比最高为${maxDataPercent}%。` : `${maxData.name}完成${maxDataLastValue}人次，同比${maxDataTong}%，环比${maxDataHuan}%。`
          // 季度或月查询：显示同比和环比
          descriptionText = `${firstNotYearStr}${secondNotYearStr}`
        }
      } else {
        // 只有全站数据时显示简化的描述
        if (this.queryForm.dateRangeQueryType === 'YEAR') {
          descriptionText = `${maxData.name}共答题${totalPerson}人次，同比${tong}%。`
        } else {
          descriptionText = `${maxData.name}共答题${totalPerson}人次，同比${tong}%，环比${huan}%。`
        }
      }

      return descriptionText
    },

    // 生成错题分布描述
    generateErrorDistributionDescription(pieData) {
      if (!pieData.length) {
        return '暂无数据'
      }

      const sortedData = pieData.sort((a, b) => b.value - a.value)
      const total = pieData.reduce((acc, cur) => acc + cur.value, 0)

      const firstPercentage = total > 0 ? ((sortedData[0]?.value / total) * 100).toFixed(2) : '0.00'
      const secondPercentage = total > 0 ? ((sortedData[1]?.value / total) * 100).toFixed(2) : '0.00'

      return `错题主要集中于：${sortedData[0]?.name || '--'}，占比：${firstPercentage}%；其次为：${sortedData[1]?.name || '--'}，占比：${secondPercentage}%，为靶向培训、题库优化提供核心依据。`
    },

    // 生成各科错题分布对比描述
    generateDepartmentComparisonDescription(radarData) {
      if (!radarData.series || !radarData.series.length) {
        return '暂无数据'
      }

      const series = radarData.series.map(ele => {
        if (ele.data.every(item => item === 0)) {
          return ''
        }
        let maxIndex = ele.data.indexOf(Math.max(...ele.data))
        return `${ele.name}：问题主要集中于${radarData.indicators[maxIndex]}`
      }).filter(element => !!element).join('；')

      return `${series}${series.length > 0 ? '，' : '暂无问题'}，可精准识别主管管理短板，分配质控资源。`
    },

    // 更新答题完成趋势图表
    updateCompletionTrendChart(processedData, xAxisData) {
      if (this.completionTrendChart) {
        const newOptions = {
          legend: {
            data: processedData.map(item => item.name)
          },
          xAxis: {
            data: xAxisData
          },
          series: processedData
        }

        this.completionTrendChart.setOption(newOptions)
      }
    },

    // 更新错题分布图表
    updateErrorDistributionChart(pieData) {
      if (this.errorDistributionChart) {
        const newOptions = {
          series: [
            {
              data: pieData
            }
          ]
        }

        this.errorDistributionChart.setOption(newOptions)
      }
    },

    // 更新各科错题分布对比图表
    updateDepartmentComparisonChart(radarData) {

      if (this.departmentComparisonChart) {
        const maxValue = this.calculateRadarMaxValue(radarData.series)

        const newOptions = {
          radar: {
            indicator: radarData.indicators.map(indicator => ({
              name: indicator,
              max: maxValue || 100
            }))
          },
          series: [
            {
              type: 'radar',
              data: radarData.series.map(seriesItem => ({
                value: seriesItem.data,
                name: seriesItem.name
              })),
              areaStyle: {}
            }
          ]
        }

        this.departmentComparisonChart.setOption(newOptions)
      }
    },

    // 计算雷达图数据的最大值
    calculateRadarMaxValue(radarData) {
      if (!radarData || radarData.length === 0) return 100

      let maxValue = 0

      radarData.forEach(series => {
        if (series.data && Array.isArray(series.data)) {
          const seriesMax = Math.max(...series.data)
          if (seriesMax > maxValue) {
            maxValue = seriesMax
          }
        }
      })

      return maxValue
    },

   
  }
}
</script>

<style lang="scss" scoped>
.qa-analysis {
  // padding: 24rpx;
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
}

.section-title {
  margin-bottom: 24rpx;

  .title-text {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
}

.three-panel-layout {
  display: flex;
  flex-direction: column;
  gap: 32rpx;
}

.panel-item {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 16rpx;
}

.panel-header {
  margin-bottom: 16rpx;

  .header-text {
    font-size: 28rpx;
    font-weight: 600;
    color: #333;
  }
}

.describe-card {
  background: #f8f9fa;
  border-radius: 8rpx;
  padding: 16rpx;
  margin-bottom: 16rpx;

  .describe-content {
    font-size: 24rpx;
    line-height: 1.5;
    color: #666;
  }
}

.chart-container {
  background: #fff;
  border-radius: 8rpx;
  padding: 16rpx;
  height: 500rpx;

  .echarts-chart {
    width: 100%;
    height: 100%;
  }
}

@media (min-width: 768px) {
  .three-panel-layout {
    flex-direction: row;
    flex-wrap: wrap;
  }

  .panel-item {
    flex: 1 1 calc(33.333% - 32rpx);
    min-width: 300rpx;
  }
}
</style>