<template>
  <div class="apaas-custom-check-data custom-page">
    <!-- Tab切换区域 -->
    <div class="tab-header">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="机型参数查询" name="model-query"></el-tab-pane>
        <el-tab-pane label="对标报告查询" name="benchmark-report"></el-tab-pane>
        <el-tab-pane label="统计分析" name="statistics"></el-tab-pane>
      </el-tabs>
    </div>

    <!-- Tab组件内容 -->
    <ModelQuery v-if="activeTab === 'model-query'" />
    <BenchmarkReport v-if="activeTab === 'benchmark-report'" />
    <div v-if="activeTab === 'statistics'" class="statistics-tab tab-content">
      <!-- 顶部筛选区域 -->
      <!-- <div class="page-search-panel check-data-panel">
        <div class="panel-header">
          <h2 class="panel-title">
            查询分析
          </h2>
          <div class="header-right">
            <span class="favorites-label">我的常用:</span>
            <el-select v-model="favoritesValue" placeholder="请选择" class="favorites-select">
              <el-option
                v-for="item in favoritesOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-button class="update-favorite-button" @click="handleUpdateFavorite">
              更新常用
            </el-button>
            <el-button type="primary" class="add-favorite-button" @click="handleAddFavorite">
              新增常用
            </el-button>
          </div>
        </div>
      </div> -->

      <div class="page-search-panel">
        <div class="search-fields">
          <div class="search-row">
            <div class="search-field">
              <span class="field-label">项目名称</span>
              <el-input v-model="searchPanelValue.projectName" placeholder="请输入" />
            </div>
            <div class="search-field">
              <span class="field-label">产品型号</span>
              <el-input v-model="searchPanelValue.modelName" placeholder="请输入" />
            </div>
            <div class="search-field">
              <span class="field-label">板块</span>
              <el-input v-model="searchPanelValue.plate" placeholder="请输入" />
            </div>
            <div class="search-field">
              <span class="field-label">平台</span>
              <el-select v-model="searchPanelValue.platform" placeholder="请选择" clearable>
                <el-option label="选项1" value="1" />
                <el-option label="选项2" value="2" />
              </el-select>
            </div>
          </div>
          <div class="search-row">
            <div class="search-field">
              <span class="field-label">系列</span>
              <!-- <el-select v-model="searchPanelValue.series" placeholder="请选择" clearable>
                <el-option label="选项1" value="1" />
                <el-option label="选项2" value="2" />
              </el-select> -->
              <el-input v-model="searchPanelValue.series" placeholder="请输入" />
            </div>
            <div class="search-field">
              <span class="field-label">燃烧类型</span>
              <!-- <el-select v-model="searchPanelValue.burnType" placeholder="请选择" clearable>
                <el-option label="选项1" value="1" />
                <el-option label="选项2" value="2" />
              </el-select> -->
              <el-input v-model="searchPanelValue.burnType" placeholder="请输入" />
            </div>
            <div class="search-field">
              <span class="field-label">排放</span>
              <el-input v-model="searchPanelValue.emission" placeholder="请输入" />
              <!-- <el-select v-model="searchPanelValue.emission" placeholder="请选择" clearable>
                <el-option label="选项1" value="1" />
                <el-option label="选项2" value="2" />
              </el-select> -->
            </div>
          </div>
          <div class="search-row">
            <div class="search-field range-field">
              <span class="field-label">排量</span>
              <div class="range-input-group">
                <el-input
                  v-model="searchPanelValue.engineCapacityMin"
                  placeholder="请输入"
                  class="range-input"
                />
                <span class="range-separator">~</span>
                <el-input
                  v-model="searchPanelValue.engineCapacityMax"
                  placeholder="请输入"
                  class="range-input"
                />
              </div>
            </div>
            <div class="search-actions">
              <el-button type="primary" @click="handleSearch">
                查询
              </el-button>
              <el-button @click="resetSearch">
                重置
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 图表管理区域 -->
      <div class="chart-management-panel">
        <el-button type="primary" @click="handleAddChart">
          新增图表
        </el-button>
        <el-button v-if="chartList.length > 0" @click="handleClearAllCharts">
          清空
        </el-button>
      </div>

      <!-- 图表区域列表 -->
      <div v-for="(chart, index) in chartList" :key="chart.id" class="chart-area">
        <div class="chart-header">
          <div class="chart-title-section">
            <span v-if="!chart.isEditingTitle" class="chart-title" @click="startEditTitle(index)">{{ chart.title }}</span>
            <el-input
              v-else
              :ref="`titleInput-${index}`"
              v-model="chart.title"
              class="title-input"
              @blur="chart.isEditingTitle = false"
              @keyup.enter.native="chart.isEditingTitle = false"
            />
            <i class="el-icon-edit title-edit-icon" @click="startEditTitle(index)"></i>
          </div>
        </div>

        <div class="chart-config">
          <div class="config-item">
            <span class="config-label">图表类型:</span>
            <el-select v-model="chart.chartType" @change="updateChart(index)">
              <el-option label="散点图" value="scatter" />
              <el-option label="折线图" value="line" />
              <el-option label="柱状图" value="bar" />
            </el-select>
          </div>
          <div class="config-item">
            <span class="config-label">X轴:</span>
            <el-select v-model="chart.xAxis" @change="updateChart(index)">
              <el-option
                v-for="option in xAxisOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </div>
          <div class="config-item">
            <span class="config-label">Y轴(参数):</span>
            <el-select v-model="chart.yAxisParam" multiple collapse-tags clearable @change="updateChart(index)">
              <el-option
                v-for="option in yAxisParamOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </div>
          <div class="config-item">
            <span class="config-label">Y轴(公式):</span>
            <el-select v-model="chart.yAxisFormula" clearable @change="handleFormulaSelectChange(index)">
              <el-option
                v-for="formula in savedFormulas"
                :key="formula.id"
                :label="formula.name"
                :value="formula.id"
              />
            </el-select>
            <el-button type="primary" size="small" @click="handleEditFormula(index)">
              添加/修改公式
            </el-button>
          </div>
          <div v-if="chart.chartType === 'scatter'" class="config-item">
            <el-checkbox v-model="chart.scatterTrendline" @change="updateChart(index)">
              显示趋势线
            </el-checkbox>
          </div>
          <div v-if="chart.chartType !== 'pie'" class="config-item">
            <span class="config-label">Y轴范围:</span>
            <el-input
              v-model.number="chart.yAxisMin"
              placeholder="最小值"
              class="y-axis-range-input"
              @blur="updateChart(index)"
            />
            <span class="range-separator">~</span>
            <el-input
              v-model.number="chart.yAxisMax"
              placeholder="最大值"
              class="y-axis-range-input"
              @blur="updateChart(index)"
            />
          </div>
          <div v-if="chart.chartType !== 'pie'" class="config-item">
            <span class="config-label">坐标点:</span>
            <el-input
              v-model.number="chart.customPointX"
              :placeholder="getCustomPointXPlaceholder(chart)"
              class="y-axis-range-input"
              @blur="updateChart(index)"
            />
            <span class="range-separator">,</span>
            <el-input
              v-model.number="chart.customPointY"
              placeholder="Y坐标(百分比)"
              class="y-axis-range-input"
              @blur="updateChart(index)"
            />
          </div>
        </div>

        <div class="chart-wrapper">
          <div class="delete-button" @click="handleDeleteChart(index)">
            <i class="el-icon-delete"></i>
            <span>删除</span>
          </div>
          <div
            :ref="`chartContainer-${index}`"
            class="chart-container"
            :style="{ height: chart.chartHeight + 'px' }"
          ></div>
          <div
            class="chart-resize-handle"
            @mousedown="startResize(index, $event)"
          ></div>
        </div>
      </div>

      <!-- 公式设置弹窗 -->
      <el-dialog
        :title="currentFormulaId ? '修改公式' : '添加公式'"
        :visible.sync="formulaDialogVisible"
        width="600px"
        :close-on-click-modal="true"
        class="formula-dialog"
      >
        <div class="formula-dialog-content">
          <div class="formula-input-section">
            <el-form-item label="公式名称:" required>
              <el-input
                v-model="formulaName"
                placeholder="请输入公式名称"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
            <div class="formula-input-section">
              <span class="formula-label">*计算公式:</span>
              <div class="formula-editor">
                <div v-for="(item, index) in formulaItems" :key="index" class="formula-item">
                  <el-select
                    v-if="item.type === 'param'"
                    v-model="item.value"
                    class="formula-select"
                    placeholder="选择参数"
                    @change="updateFormula"
                  >
                    <el-option
                      v-for="opt in yAxisParamOptions"
                      :key="opt.value"
                      :label="opt.label"
                      :value="opt.value"
                    />
                  </el-select>
                  <el-select
                    v-else-if="item.type === 'operator'"
                    v-model="item.value"
                    class="formula-select"
                    placeholder="选择运算符"
                    @change="updateFormula"
                  >
                    <el-option
                      v-for="opt in operatorOptions"
                      :key="opt.value"
                      :label="opt.label"
                      :value="opt.value"
                    />
                  </el-select>
                  <i class="el-icon-delete formula-delete-icon" @click="removeFormulaItem(index)"></i>
                </div>
                <div v-if="formulaItems.length === 0" class="formula-empty-hint">
                  请添加参数和运算符
                </div>
              </div>
            </div>
          </div>
          <div class="formula-buttons">
            <el-button type="primary" :disabled="yAxisParamOptions.length === 0" @click="addFormulaParam">
              添加参数
            </el-button>
            <el-button type="primary" @click="addFormulaOperator">
              添加符号
            </el-button>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleFormulaDialogClose">
            取消
          </el-button>
          <el-button type="primary" :disabled="!formulaName || formulaItems.length === 0" @click="handleSaveFormula">
            确定
          </el-button>
        </span>
      </el-dialog>
    </div>
    <AnalysisReport v-if="activeTab === 'analysis-report'" />
  </div>
</template>

<script>
import * as echarts from 'echarts'
import api from '@/api/demo'
import ModelQuery from './model-query.vue'
import BenchmarkReport from './benchmark-report.vue'
import AnalysisReport from './analysis-report.vue'

export default {
  name: 'CheckData',
  components: {
    ModelQuery,
    BenchmarkReport,
    AnalysisReport
  },
  data() {
    return {
      activeTab: 'model-query', // 默认显示第一个tab
      favoritesValue: '',
      favoritesOptions: [
        { label: '常用1', value: '1' },
        { label: '常用2', value: '2' }
      ],
      searchPanelValue: {
        projectName: '',
        modelName: '',
        plate: '',
        platform: '',
        series: '',
        emission: '',
        burnType: '',
        engineCapacityMin: '',
        engineCapacityMax: ''
      },
      // X轴选项（来自搜索区域的筛选项）
      xAxisOptions: [
        { label: '项目名称', value: 'projectName' },
        { label: '产品型号', value: 'modelName' },
        { label: '板块', value: 'plate' },
        { label: '平台', value: 'platform' },
        { label: '系列', value: 'series' },
        { label: '排放', value: 'emission' },
        { label: '燃烧类型', value: 'burnType' },
        { label: '排量', value: 'engineCapacity' }
      ],
      // Y轴参数选项（通过接口获取，目前使用假数据）
      yAxisParamOptions: [],
      // 查询结果数据
      chartDataList: [], // 保存查询返回的 pojos 数据
      chartList: [],
      chartIdCounter: 0,
      formulaDialogVisible: false,
      currentFormulaChartIndex: -1,
      currentFormulaId: null, // 当前编辑的公式ID（如果为null则是新增）
      formulaName: '', // 公式名称
      isResizing: false,
      resizingChartIndex: -1,
      resizeStartY: 0,
      resizeStartHeight: 0,
      formulaItems: [],
      // 已保存的公式列表
      savedFormulas: [], // 格式: [{ id: 'formula1', name: '公式1', formulaItems: [...] }]
      formulaIdCounter: 0, // 公式ID计数器
      operatorOptions: [
        { label: '+', value: '+' },
        { label: '-', value: '-' },
        { label: '*', value: '*' },
        { label: '/', value: '/' }
      ]
    }
  },
  watch: {
    activeTab: {
      immediate: true,
      handler(newVal, oldVal) {
        if (newVal === 'statistics') {
          window.addEventListener('resize', this.handleResize)
          // 加载Y轴参数选项
          this.loadYAxisParams()
          this.$nextTick(() => {
            this.chartList.forEach((chart, index) => {
              if (!chart.chartInstance) {
                this.initChart(index)
              } else {
                chart.chartInstance.resize()
              }
            })
          })
        } else if (oldVal === 'statistics') {
          window.removeEventListener('resize', this.handleResize)
          this.cleanupResizeListeners()
          this.disposeAllCharts()
        }
      }
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    this.cleanupResizeListeners()
    this.disposeAllCharts()
  },
  mounted() {
    this.handleSearch()
  },
  methods: {
    // 加载Y轴参数选项（目前使用假数据，后续改为接口调用）
    loadYAxisParams() {
      // TODO: 后续改为接口调用
      // const request = {
      //   ...api.GET_Y_AXIS_PARAMS,
      //   params: {}
      // }
      // this.$request(request)
      //   .asyncThen((resp) => {
      //     if (resp && resp.data) {
      //       this.yAxisParamOptions = resp.data.map(item => ({
      //         label: item.name || item.label,
      //         value: item.value || item.id
      //       }))
      //     }
      //   })
      //   .asyncErrorCatch((err) => {
      //     console.error('获取Y轴参数失败:', err)
      //   })

      // 目前使用假数据
      this.yAxisParamOptions = [
        { label: '参数1', value: 'param1' },
        { label: '参数2', value: 'param2' },
        { label: '参数3', value: 'param3' },
        { label: '参数4', value: 'param4' },
        { label: '参数5', value: 'param5' }
      ]
    },
    handleTabClick(tab) {
      // Tab切换时的处理逻辑
      console.log('切换到tab:', tab.name)
    },
    handleAddChart() {
      const newChart = {
        id: this.chartIdCounter++,
        title: '自定义标题',
        isEditingTitle: false,
        chartType: 'line',
        xAxis: this.xAxisOptions.length > 0 ? this.xAxisOptions[0].value : '',
        yAxisParam: this.yAxisParamOptions.length > 0 ? [this.yAxisParamOptions[0].value] : [],
        yAxisFormula: '',
        yAxisMin: 0,
        yAxisMax: 100,
        chartHeight: 400,
        customPointX: null,
        customPointY: null,
        scatterTrendline: false,
        chartInstance: null,
        formulaItems: []
      }
      this.chartList.push(newChart)
      this.$nextTick(() => {
        this.initChart(this.chartList.length - 1)
      })
    },
    handleDeleteChart(index) {
      const chart = this.chartList[index]
      if (chart?.chartInstance) {
        chart.chartInstance.dispose()
        chart.chartInstance = null
      }
      this.chartList.splice(index, 1)
    },
    handleClearAllCharts() {
      this.disposeAllCharts()
      this.chartList = []
    },
    // handleAddFavorite() {
    //   this.$message.info('新增常用功能')
    // },
    // handleUpdateFavorite() {
    //   this.$message.info('更新常用功能')
    // },
    handleSearch() {
      const request = {
        ...api.GET_CHECK_DATA_CHARTS,
        params: {
          projectName: this.searchPanelValue.projectName,
          modelName: this.searchPanelValue.modelName,
          plate: this.searchPanelValue.plate,
          platform: this.searchPanelValue.platform,
          series: this.searchPanelValue.series,
          emission: this.searchPanelValue.emission,
          burnType: this.searchPanelValue.burnType ? this.searchPanelValue.burnType : undefined,
          engineCapacityMin: this.searchPanelValue.engineCapacityMin ? this.searchPanelValue.engineCapacityMin : undefined,
          engineCapacityMax: this.searchPanelValue.engineCapacityMax ? this.searchPanelValue.engineCapacityMax : undefined
        },
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          console.log(resp)
          // 处理返回的数据
          if (resp && resp.data) {
            // 更新Y轴参数选项
            if (resp.data.paramList && Array.isArray(resp.data.paramList)) {
              this.yAxisParamOptions = resp.data.paramList.map(paramName => ({
                label: paramName,
                value: paramName
              }))
            }

            // 保存查询结果数据
            this.chartDataList = resp.data.pojos || []

            // 查询后更新所有图表
            this.chartList.forEach((chart, index) => {
              this.updateChart(index)
            })
          }
        })
        .asyncErrorCatch((err) => {
          console.error('查询失败:', err)
        })
    },
    resetSearch() {
      this.searchPanelValue = {
        projectName: '',
        modelName: '',
        plate: '',
        platform: '',
        series: '',
        emission: '',
        burnType: '',
        engineCapacityMin: '',
        engineCapacityMax: ''
      }
      // 清空查询结果数据
      this.chartDataList = []
      this.yAxisParamOptions = []
    },
    initChart(index) {
      const chart = this.chartList[index]
      if (!chart) return
      if (!chart.chartHeight) {
        chart.chartHeight = 400
      }
      const refName = `chartContainer-${index}`
      const containerRef = this.$refs[refName]
      if (!containerRef || (Array.isArray(containerRef) && !containerRef[0])) return
      const container = Array.isArray(containerRef) ? containerRef[0] : containerRef
      chart.chartInstance = echarts.init(container)
      this.updateChart(index)
    },
    handleResize() {
      this.chartList.forEach((chart) => {
        if (chart.chartInstance) {
          chart.chartInstance.resize()
        }
      })
    },
    updateChart(index) {
      const chart = this.chartList[index]
      if (!chart || !chart.chartInstance) return

      if (typeof chart.scatterTrendline === 'undefined') {
        this.$set(chart, 'scatterTrendline', false)
      }

      // 根据选择的X轴获取数据
      const xAxisValue = chart.xAxis || ''
      const xAxisOption = this.xAxisOptions.find(opt => opt.value === xAxisValue)
      const xAxisLabel = xAxisOption ? xAxisOption.label : ''

      // 从查询结果中获取X轴数据
      let xAxisData = []
      const xAxisDataMap = new Map() // 用于去重和合并数据

      if (this.chartDataList && this.chartDataList.length > 0) {
        // 遍历查询结果，提取X轴数据
        this.chartDataList.forEach(model => {
          let xAxisValueItem = ''
          if (xAxisValue === 'projectName') {
            xAxisValueItem = model.projectName || ''
          } else if (xAxisValue === 'modelName') {
            xAxisValueItem = model.modelName || ''
          } else if (xAxisValue === 'plate') {
            xAxisValueItem = model.plate || ''
          } else if (xAxisValue === 'platform') {
            xAxisValueItem = model.platform || ''
          } else if (xAxisValue === 'series') {
            xAxisValueItem = model.series || ''
          } else if (xAxisValue === 'emission') {
            xAxisValueItem = model.emission || ''
          } else if (xAxisValue === 'burnType') {
            xAxisValueItem = model.burnType || ''
          } else if (xAxisValue === 'engineCapacity') {
            xAxisValueItem = model.engineCapacity || ''
          }

          if (xAxisValueItem) {
            // 如果还没有这个X轴值，创建新的数据项
            if (!xAxisDataMap.has(xAxisValueItem)) {
              xAxisDataMap.set(xAxisValueItem, {
                xValue: xAxisValueItem,
                parameters: model.pojos || []
              })
            } else {
              // 如果已存在，合并参数数据
              const existing = xAxisDataMap.get(xAxisValueItem)
              existing.parameters = existing.parameters.concat(model.pojos || [])
            }
          }
        })

        // 转换为数组并排序
        xAxisData = Array.from(xAxisDataMap.keys())
      }

      // 如果没有数据，使用默认数据
      if (xAxisData.length === 0) {
        if (xAxisValue === 'engineCapacity') {
          // 排量是范围值，需要特殊处理
          const min = this.searchPanelValue.engineCapacityMin || 0
          const max = this.searchPanelValue.engineCapacityMax || 100
          const step = (max - min) / 10
          xAxisData = []
          for (let i = 0; i <= 10; i++) {
            const value = min + step * i
            xAxisData.push(value.toFixed(1))
          }
        } else {
          xAxisData = this.getDefaultXAxisData(xAxisValue)
        }
      }

      // 生成Y轴数据（从查询结果中提取）
      const selectedParams = Array.isArray(chart.yAxisParam) ? chart.yAxisParam : []
      const paramDataMap = {}

      selectedParams.forEach(paramName => {
        // 为每个参数生成数据数组
        const paramData = []
        xAxisData.forEach(xValue => {
          // 查找该X轴值对应的参数值
          let paramValue = null
          if (xAxisDataMap.has(xValue)) {
            const dataItem = xAxisDataMap.get(xValue)
            // 在参数列表中查找匹配的parameterName
            const matchedParam = dataItem.parameters.find(p => p.parameterName === paramName)
            if (matchedParam && matchedParam.parameterValue !== undefined && matchedParam.parameterValue !== null) {
              // 尝试转换为数字，如果失败则使用原值
              const numValue = parseFloat(matchedParam.parameterValue)
              paramValue = isNaN(numValue) ? matchedParam.parameterValue : numValue
            }
          }
          paramData.push(paramValue)
        })
        paramDataMap[paramName] = paramData
      })

      const series = []
      const legendData = []
      const chartType = chart.chartType
      const isScatter = chartType === 'scatter'
      const isBar = chartType === 'bar'
      const isPie = chartType === 'pie'
      const showScatterTrendline = isScatter && !!chart.scatterTrendline

      // 如果选择了公式，计算公式结果
      let formulaData = null
      if (chart.yAxisFormula) {
        const selectedFormula = this.savedFormulas.find(f => f.id === chart.yAxisFormula)
        if (selectedFormula && selectedFormula.formulaItems && selectedFormula.formulaItems.length > 0) {
          formulaData = this.calculateFormula(selectedFormula.formulaItems, xAxisData, xAxisDataMap)
        }
      }

      // 获取参数名称映射
      const getParamLabel = (paramValue) => {
        const paramOption = this.yAxisParamOptions.find(opt => opt.value === paramValue)
        return paramOption ? paramOption.label : paramValue
      }

      if (isPie) {
        const pieData = []
        const pieColors = ['#67C23A', '#E6A23C', '#F56C6C', '#409EFF', '#909399']

        selectedParams.forEach((paramValue, index) => {
          const paramData = paramDataMap[paramValue] || []
          const avgValue = paramData.length > 0
            ? paramData.reduce((sum, val) => sum + (val || 0), 0) / paramData.length
            : 0
          const paramLabel = getParamLabel(paramValue)
          pieData.push({ value: avgValue, name: paramLabel })
          legendData.push(paramLabel)
        })

        const pieOption = {
          title: { show: false },
          tooltip: {
            trigger: 'item',
            formatter(params) {
              const value = parseFloat(params.value).toFixed(2)
              const percent = parseFloat(params.percent).toFixed(2)
              return `${params.seriesName}<br/>${params.name}: ${value}% (${percent}%)`
            }
          },
          legend: {
            data: legendData,
            top: 0,
            left: 'center'
          },
          series: [{
            name: '数据分布',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter(params) {
                return `${params.name}: ${parseFloat(params.value).toFixed(2)}%`
              }
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '16',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: true
            },
            data: pieData.map((item, idx) => ({
              ...item,
              itemStyle: {
                color: pieColors[idx % pieColors.length]
              }
            }))
          }]
        }

        chart.chartInstance.setOption(pieOption, true)
        return
      }

      // 参数颜色配置
      const paramColors = ['#67C23A', '#E6A23C', '#F56C6C', '#409EFF', '#909399', '#E4E7ED', '#C0C4CC']
      const paramSymbols = ['circle', 'rect', 'triangle', 'diamond', 'pin', 'arrow']

      // 为每个选中的参数创建系列
      selectedParams.forEach((paramValue, index) => {
        const paramData = paramDataMap[paramValue] || []
        const paramLabel = getParamLabel(paramValue)
        const color = paramColors[index % paramColors.length]
        const symbol = paramSymbols[index % paramSymbols.length]

        const paramSeries = {
          name: paramLabel,
          type: isBar ? 'bar' : isScatter ? 'scatter' : 'line',
          data: paramData,
          symbol: isScatter ? symbol : 'circle',
          symbolSize: isScatter ? 8 : 6,
          itemStyle: { color: color },
          lineStyle: { color: color, width: 2 }
        }

        if (chartType === 'line') {
          paramSeries.areaStyle = {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: this.hexToRgba(color, 0.3) },
                { offset: 1, color: this.hexToRgba(color, 0.05) }
              ]
            }
          }
        }

        series.push(paramSeries)
        legendData.push(paramLabel)

        // 添加趋势线（仅散点图）
        if (showScatterTrendline) {
          series.push({
            name: `趋势线 (${paramLabel})`,
            type: 'line',
            data: paramData,
            lineStyle: {
              color: color,
              type: 'solid',
              width: 2
            },
            symbol: 'none',
            smooth: true
          })
          legendData.push(`趋势线 (${paramLabel})`)
        }
      })

      // 如果选择了公式，添加公式计算结果系列
      if (formulaData && formulaData.length > 0) {
        const selectedFormula = this.savedFormulas.find(f => f.id === chart.yAxisFormula)
        const formulaName = selectedFormula ? selectedFormula.name : '公式'
        series.push({
          name: formulaName,
          type: 'line',
          data: formulaData,
          lineStyle: {
            color: '#F56C6C',
            type: 'dashed',
            width: 2
          },
          symbol: 'circle',
          symbolSize: 6,
          itemStyle: { color: '#F56C6C' }
        })
        legendData.push(formulaName)
      }

      // 自定义点处理
      if (
        chart.customPointX !== null &&
        chart.customPointX !== '' &&
        chart.customPointY !== null &&
        chart.customPointY !== ''
      ) {
        const xValue = chart.customPointX
        const yValue = chart.customPointY
        // 查找X轴数据中对应的索引
        const xIndex = xAxisData.findIndex(item => {
          if (xAxisValue === 'engineCapacity') {
            return Math.abs(parseFloat(item) - parseFloat(xValue)) < 0.1
          }
          return item === xValue || item.toString() === xValue.toString()
        })
        const yMin = chart.yAxisMin !== null && chart.yAxisMin !== '' ? chart.yAxisMin : 0
        const yMax = chart.yAxisMax !== null && chart.yAxisMax !== '' ? chart.yAxisMax : 100

        if (xIndex !== -1 && yValue >= yMin && yValue <= yMax) {
          const customPointData = []
          for (let i = 0; i < xAxisData.length; i++) {
            if (i === xIndex) {
              customPointData.push(yValue)
            } else {
              customPointData.push(null)
            }
          }

          series.push({
            name: '自定义点',
            type: 'scatter',
            data: customPointData,
            symbol: 'circle',
            symbolSize: 12,
            itemStyle: {
              color: '#F56C6C'
            },
            zlevel: 10
          })
          legendData.push('自定义点')
        }
      }

      const option = {
        title: { show: false },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          formatter(params) {
            if (Array.isArray(params)) {
              let result = `${params[0].axisValue}<br/>`
              params.forEach((item) => {
                if (item.value !== undefined && item.value !== null && item.value !== '') {
                  result += `${item.marker}${item.seriesName}: ${item.value}%<br/>`
                }
              })
              return result
            }
            if (params.value !== undefined && params.value !== null && params.value !== '') {
              return `${params.seriesName}<br/>${params.marker}${params.name}: ${params.value}%`
            }
            return ''
          }
        },
        legend: {
          data: legendData,
          top: 0,
          left: 'center'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: legendData.length > 0 ? '15%' : '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: xAxisData,
          name: xAxisLabel,
          boundaryGap: false,
          axisLine: {
            lineStyle: {
              color: '#DCDFE6'
            }
          },
          axisTick: {
            show: false
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dashed',
              color: '#E4E7ED'
            }
          }
        },
        yAxis: {
          type: 'value',
          min: chart.yAxisMin !== null && chart.yAxisMin !== '' ? chart.yAxisMin : 0,
          max: chart.yAxisMax !== null && chart.yAxisMax !== '' ? chart.yAxisMax : 100,
          interval: 20,
          axisLabel: {
            formatter: '{value}%'
          },
          axisLine: {
            lineStyle: {
              color: '#DCDFE6'
            }
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dashed',
              color: '#E4E7ED'
            }
          }
        },
        series
      }

      chart.chartInstance.setOption(option, true)
    },
    // 获取默认X轴数据（当没有搜索值时使用）
    getDefaultXAxisData(xAxisValue) {
      // 根据不同的X轴选项返回默认数据
      switch (xAxisValue) {
        case 'projectName':
          return ['项目1', '项目2', '项目3', '项目4', '项目5']
        case 'modelName':
          return ['型号1', '型号2', '型号3', '型号4', '型号5']
        case 'plate':
          return ['板块1', '板块2', '板块3', '板块4', '板块5']
        case 'platform':
          return ['平台1', '平台2', '平台3', '平台4', '平台5']
        case 'series':
          return ['系列1', '系列2', '系列3', '系列4', '系列5']
        case 'emission':
          return ['排放1', '排放2', '排放3', '排放4', '排放5']
        case 'burnType':
          return ['类型1', '类型2', '类型3', '类型4', '类型5']
        case 'engineCapacity':
          return ['1.0', '1.5', '2.0', '2.5', '3.0', '3.5', '4.0', '4.5', '5.0']
        default:
          return ['数据1', '数据2', '数据3', '数据4', '数据5']
      }
    },
    // 生成参数数据（假数据）
    generateParamData(length, paramValue) {
      // 根据参数值生成不同的假数据模式
      const baseValue = paramValue.charCodeAt ? paramValue.charCodeAt(0) % 100 : 50
      const data = []
      for (let i = 0; i < length; i++) {
        // 生成随机但有一定规律的数据
        const value = baseValue + Math.sin(i * 0.5) * 20 + Math.random() * 10
        data.push(Math.round(value * 100) / 100)
      }
      return data
    },
    // 将十六进制颜色转换为rgba
    hexToRgba(hex, alpha) {
      const r = parseInt(hex.slice(1, 3), 16)
      const g = parseInt(hex.slice(3, 5), 16)
      const b = parseInt(hex.slice(5, 7), 16)
      return `rgba(${r}, ${g}, ${b}, ${alpha})`
    },
    // 获取自定义点X坐标的占位符文本
    getCustomPointXPlaceholder(chart) {
      if (!chart || !chart.xAxis) {
        return 'X坐标'
      }
      const xAxisOption = this.xAxisOptions.find(opt => opt.value === chart.xAxis)
      const label = xAxisOption ? xAxisOption.label : ''
      return `X坐标(${label})`
    },
    handleFormulaSelectChange(index) {
      const chart = this.chartList[index]
      if (!chart) return

      // 如果选择了公式，加载该公式的内容并更新图表
      if (chart.yAxisFormula) {
        const selectedFormula = this.savedFormulas.find(f => f.id === chart.yAxisFormula)
        if (selectedFormula) {
          // 将公式应用到当前图表
          chart.formulaItems = JSON.parse(JSON.stringify(selectedFormula.formulaItems))
          this.updateChart(index)
        }
      } else {
        // 如果清空选择，清空公式
        chart.formulaItems = []
        this.updateChart(index)
      }
    },
    startEditTitle(index) {
      const chart = this.chartList[index]
      if (chart) {
        chart.isEditingTitle = true
        this.$nextTick(() => {
          const refName = `titleInput-${index}`
          const inputRef = this.$refs[refName]
          if (inputRef) {
            const input = Array.isArray(inputRef) ? inputRef[0] : inputRef
            if (input && input.$el && input.$el.querySelector('input')) {
              input.$el.querySelector('input').focus()
            }
          }
        })
      }
    },
    handleEditFormula(index) {
      this.currentFormulaChartIndex = index
      const chart = this.chartList[index]
      if (!chart) return

      // 如果图表已选择了公式，则编辑该公式；否则创建新公式
      if (chart.yAxisFormula) {
        // 编辑已存在的公式
        const existingFormula = this.savedFormulas.find(f => f.id === chart.yAxisFormula)
        if (existingFormula) {
          this.currentFormulaId = existingFormula.id
          this.formulaName = existingFormula.name
          this.formulaItems = JSON.parse(JSON.stringify(existingFormula.formulaItems))
        } else {
          // 如果找不到公式，创建新的
          this.currentFormulaId = null
          this.formulaName = ''
          this.formulaItems = JSON.parse(JSON.stringify(chart.formulaItems || []))
        }
      } else {
        // 创建新公式
        this.currentFormulaId = null
        this.formulaName = ''
        this.formulaItems = JSON.parse(JSON.stringify(chart.formulaItems || []))
      }

      this.formulaDialogVisible = true
    },
    addFormulaParam() {
      // 使用第一个可用的Y轴参数作为默认值
      const defaultParam = this.yAxisParamOptions.length > 0 ? this.yAxisParamOptions[0].value : ''
      this.formulaItems.push({ type: 'param', value: defaultParam })
      this.updateFormula()
    },
    addFormulaOperator() {
      this.formulaItems.push({ type: 'operator', value: '+' })
      this.updateFormula()
    },
    removeFormulaItem(index) {
      this.formulaItems.splice(index, 1)
      this.updateFormula()
    },
    updateFormula() {
      // 更新公式显示
    },
    handleSaveFormula() {
      // 验证公式名称
      if (!this.formulaName || this.formulaName.trim() === '') {
        this.$message.warning('请输入公式名称')
        return
      }

      // 验证公式内容
      if (this.formulaItems.length === 0) {
        this.$message.warning('请至少添加一个参数')
        return
      }

      // 验证公式格式（至少需要一个参数）
      const paramCount = this.formulaItems.filter(item => item.type === 'param').length
      if (paramCount < 1) {
        this.$message.warning('公式至少需要包含一个参数')
        return
      }

      let formulaId = this.currentFormulaId

      if (formulaId) {
        // 修改已存在的公式
        const formulaIndex = this.savedFormulas.findIndex(f => f.id === formulaId)
        if (formulaIndex >= 0) {
          this.savedFormulas[formulaIndex].name = this.formulaName.trim()
          this.savedFormulas[formulaIndex].formulaItems = JSON.parse(JSON.stringify(this.formulaItems))
        }
      } else {
        // 创建新公式
        formulaId = `formula_${this.formulaIdCounter++}`
        this.savedFormulas.push({
          id: formulaId,
          name: this.formulaName.trim(),
          formulaItems: JSON.parse(JSON.stringify(this.formulaItems))
        })
      }

      // 将公式应用到当前图表
      if (this.currentFormulaChartIndex >= 0) {
        const chart = this.chartList[this.currentFormulaChartIndex]
        if (chart) {
          chart.yAxisFormula = formulaId
          chart.formulaItems = JSON.parse(JSON.stringify(this.formulaItems))
          this.updateChart(this.currentFormulaChartIndex)
        }
      }

      this.handleFormulaDialogClose()
    },
    // 关闭公式弹窗
    handleFormulaDialogClose() {
      this.formulaDialogVisible = false
      this.currentFormulaChartIndex = -1
      this.currentFormulaId = null
      this.formulaName = ''
      this.formulaItems = []
    },
    // 计算公式结果
    calculateFormula(formulaItems, xAxisData, xAxisDataMap) {
      if (!formulaItems || formulaItems.length === 0) {
        return []
      }

      // 将公式转换为可执行的表达式
      const formulaData = []

      xAxisData.forEach(xValue => {
        // 为每个X轴值计算公式结果
        let result = null

        try {
          // 构建计算栈
          const stack = []

          formulaItems.forEach(item => {
            if (item.type === 'param') {
              // 参数：从数据中获取值
              const paramValue = this.getParamValueFromData(item.value, xValue, xAxisDataMap)
              if (paramValue !== null && paramValue !== undefined) {
                const numValue = parseFloat(paramValue)
                if (!isNaN(numValue)) {
                  stack.push(numValue)
                } else {
                  stack.push(null)
                }
              } else {
                stack.push(null)
              }
            } else if (item.type === 'operator') {
              // 运算符：执行计算
              if (stack.length >= 2) {
                const b = stack.pop()
                const a = stack.pop()

                if (a !== null && b !== null && !isNaN(a) && !isNaN(b)) {
                  let calcResult = null
                  switch (item.value) {
                    case '+':
                      calcResult = a + b
                      break
                    case '-':
                      calcResult = a - b
                      break
                    case '*':
                      calcResult = a * b
                      break
                    case '/':
                      calcResult = b !== 0 ? a / b : null
                      break
                    default:
                      calcResult = null
                  }
                  stack.push(calcResult)
                } else {
                  stack.push(null)
                }
              }
            }
          })

          // 栈顶元素就是结果
          if (stack.length === 1) {
            result = stack[0]
          }
        } catch (err) {
          console.error('计算公式失败:', err)
          result = null
        }

        formulaData.push(result)
      })

      return formulaData
    },
    // 从数据中获取参数值
    getParamValueFromData(paramName, xValue, xAxisDataMap) {
      if (!xAxisDataMap || !xAxisDataMap.has(xValue)) {
        return null
      }

      const dataItem = xAxisDataMap.get(xValue)
      if (!dataItem || !dataItem.parameters) {
        return null
      }

      // 在参数列表中查找匹配的parameterName
      const matchedParam = dataItem.parameters.find(p => p.parameterName === paramName)
      if (matchedParam && matchedParam.parameterValue !== undefined && matchedParam.parameterValue !== null) {
        return matchedParam.parameterValue
      }

      return null
    },
    startResize(index, event) {
      event.preventDefault()
      event.stopPropagation()
      this.isResizing = true
      this.resizingChartIndex = index
      this.resizeStartY = event.clientY
      const chart = this.chartList[index]
      this.resizeStartHeight = chart?.chartHeight || 400

      document.addEventListener('mousemove', this.doResize)
      document.addEventListener('mouseup', this.stopResize)
      document.body.style.cursor = 'row-resize'
      document.body.style.userSelect = 'none'
    },
    doResize(event) {
      if (!this.isResizing) return

      const deltaY = event.clientY - this.resizeStartY
      const newHeight = this.resizeStartHeight + deltaY
      const minHeight = 200

      const chart = this.chartList[this.resizingChartIndex]
      if (chart) {
        chart.chartHeight = Math.max(newHeight, minHeight)
        this.$nextTick(() => {
          if (chart.chartInstance) {
            chart.chartInstance.resize()
          }
        })
      }
    },
    stopResize() {
      this.cleanupResizeListeners()
    },
    cleanupResizeListeners() {
      document.removeEventListener('mousemove', this.doResize)
      document.removeEventListener('mouseup', this.stopResize)
      document.body.style.cursor = ''
      document.body.style.userSelect = ''
      this.isResizing = false
      this.resizingChartIndex = -1
    },
    disposeAllCharts() {
      this.chartList.forEach((chart) => {
        if (chart.chartInstance) {
          chart.chartInstance.dispose()
          chart.chartInstance = null
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.apaas-custom-check-data {
  overflow-y: auto;
  height: 100%;
  display: flex;
  flex-direction: column;

  // Tab头部样式
  .tab-header {
    background: white;
    padding: 0 20px;
    border-bottom: 1px solid #ebeef5;
    flex-shrink: 0;

    ::v-deep .el-tabs {
      .el-tabs__header {
        margin: 0;
        border-bottom: none;
      }

      .el-tabs__nav-wrap::after {
        height: 1px;
        background-color: #ebeef5;
      }

      .el-tabs__item {
        height: 48px;
        line-height: 48px;
        font-size: 14px;
        color: #606266;

        &.is-active {
          color: #409EFF;
          font-weight: 500;
        }

        &:hover {
          color: #409EFF;
        }
      }

      .el-tabs__active-bar {
        background-color: #409EFF;
      }
    }
  }

  .tab-content {
    flex: 1;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
  }
}

.statistics-tab {
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;

  .page-search-panel {
    background: white;
    padding: 16px 24px;
    border-bottom: 1px solid #ebeef5;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;

    .search-fields {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      gap: 12px;
      width: 100%;
    }

    .search-row {
      display: flex;
      align-items: flex-end;
      gap: 24px;
      width: 100%;
    }

    .search-field,
    .search-actions {
      flex: 1 1 calc((100% - 48px) / 3);
      min-width: 0;
      display: flex;
      align-items: center;
      gap: 12px;
    }

    .search-field {
      .field-label {
        font-size: 14px;
        font-weight: 600;
        color: #303133;
        white-space: nowrap;
        min-width: 64px;
        text-align: right;
      }

      .el-input,
      .el-select {
        flex: 1;
      }

      :deep(.el-input__inner),
      :deep(.el-select .el-input__inner) {
        height: 32px;
        line-height: 32px;
      }
    }

    .range-field {
      .range-input-group {
        display: flex;
        align-items: center;
        gap: 8px;
        flex: 1;
      }

      .range-input {
        flex: 1;
      }

      .range-separator {
        color: #606266;
        line-height: 32px;
        font-size: 14px;
      }
    }

    .search-actions {
      justify-content: flex-end;
    }

    :deep(.el-button) {
      padding: 0 16px;
      font-size: 14px;
      border-radius: 4px;
      height: 32px;
      line-height: 32px;
    }
  }

  .check-data-panel {
    padding: 16px 20px;
    margin-bottom: 0;
    border-bottom: 1px solid #cbccce;

    .panel-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;

      .panel-title {
        font-size: 18px;
        font-weight: 500;
        color: #303133;
        margin: 0;
        line-height: 1;
      }

      .header-right {
        display: flex;
        align-items: center;
        gap: 12px;
        flex-shrink: 0;

        .favorites-label {
          font-size: 14px;
          color: #303133;
          white-space: nowrap;
        }

        .favorites-select {
          width: 200px;
        }

        .update-favorite-button {
          background: white;
          border: 1px solid #409EFF;
          color: #409EFF;
          padding: 8px 16px;
          border-radius: 4px;
          font-size: 14px;

          &:hover {
            background: #ecf5ff;
            border-color: #66b1ff;
            color: #66b1ff;
          }

          &:active {
            background: #409eff;
            color: white;
          }
        }

        .add-favorite-button {
          padding: 8px 16px;
          border-radius: 4px;
          font-size: 14px;
        }
      }
    }
  }

  .chart-management-panel {
    background: transparent;
    margin-top: 16px;
    margin-left: 20px;
    border-radius: 4px;
    display: flex;
    gap: 8px;
    flex-shrink: 0;
    min-height: 56px;
    align-items: center;
  }

  .chart-area {
    background: white;
    margin: 20px;
    margin-top: 10px;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    flex-shrink: 0;

    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      padding-bottom: 16px;
      border-bottom: 1px solid #ebeef5;
      position: relative;

      .chart-title-section {
        display: flex;
        align-items: center;
        flex: 1;

        .title-edit-icon {
          margin-left: 8px;
          cursor: pointer;
          color: #909399;
          font-size: 14px;
        }

        .title-input {
          width: 200px;

          ::v-deep .el-input__inner {
            border: none;
            border-bottom: 1px solid #409eff;
            border-radius: 0;
            padding-left: 0;
          }
        }

        .chart-title {
          font-size: 16px;
          font-weight: 500;
          cursor: pointer;
          padding: 4px 8px;

          &:hover {
            color: #409eff;
            background: #f5f7fa;
            border-radius: 4px;
          }
        }
      }
    }

    .chart-config {
      display: flex;
      flex-wrap: wrap;
      gap: 16px 24px;
      margin-bottom: 20px;
      padding: 16px;
      background: #f5f7fa;
      border-radius: 4px;
      align-items: center;

      .config-item {
        display: flex;
        align-items: center;
        gap: 8px;
        flex-shrink: 0;

        .config-label {
          font-size: 14px;
          white-space: nowrap;
          min-width: 70px;
          color: #606266;
        }

        ::v-deep .el-select {
          width: 150px;
          height: 32px;
        }
        ::v-deep .el-select .el-input__inner {
          height: 32px;
        }
        ::v-deep .el-button {
          margin-left: 0;
        }

        .y-axis-range-input {
          width: 100px;
        }

        .range-separator {
          margin: 0 8px;
          color: #606266;
        }
      }
    }

    .chart-wrapper {
      position: relative;

      .delete-button {
        position: absolute;
        top: 0;
        right: 0;
        z-index: 10;
        display: flex;
        align-items: center;
        gap: 4px;
        cursor: pointer;
        color: #909399;
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 14px;
        background: rgba(255, 255, 255, 0.9);

        &:hover {
          color: #f56c6c;
          background: #f5f7fa;
        }
      }

      .chart-resize-handle {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        height: 8px;
        cursor: row-resize;
        z-index: 5;
        background: transparent;
        transition: background 0.2s;

        &:hover {
          background: rgba(64, 158, 255, 0.2);
        }

        &::before {
          content: '';
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          width: 40px;
          height: 4px;
          background: #dcdfe6;
          border-radius: 2px;
          transition: background 0.2s;
        }

        &:hover::before {
          background: #409eff;
        }
      }
    }

    .chart-container {
      width: 100%;
      min-height: 200px;
    }
  }

  .formula-dialog-content {
    .formula-note {
      color: #f56c6c;
      font-size: 12px;
      margin-bottom: 16px;
    }

    .formula-input-section {
      .formula-label {
        display: block;
        margin-bottom: 8px;
        font-size: 14px;
        font-weight: 500;
      }

      .formula-editor {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        padding: 12px;
        background: #f5f7fa;
        border-radius: 4px;
        min-height: 50px;
        align-items: center;
        border: 1px solid #dcdfe6;

        .formula-item {
          display: flex;
          align-items: center;
          gap: 4px;

          .formula-select {
            width: 120px;

            ::v-deep .el-input__inner {
              background: white;
            }
          }

          .formula-delete-icon {
            cursor: pointer;
            color: #909399;
            font-size: 16px;
            margin-left: 4px;
            padding: 4px;

            &:hover {
              color: #f56c6c;
            }
          }
        }
      }
    }

    .formula-buttons {
      margin-top: 16px;
      display: flex;
      gap: 8px;
    }
  }
}
</style>

<style lang="scss">
.formula-dialog {
  .el-dialog__body {
    position: relative;
  }
}
</style>
