<template>
  <div class="app-container">
    <!-- 筛选 -->
    <div class="filter-card">
      <h1>{{ this.params.category }} 销量一览</h1>
      <div class="filter-item">
        <label>日期范围：</label>
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          style="width: 380px"
          size="small"
          :picker-options="datePickerOptions"
          @change="handleDateChange"
        />
      </div>
    </div>

    <div class="filter-section">
      <div v-for="(item, key) in filterOptions" :key="key" class="filter-cell">
        <div class="cell-header">
          <span class="filter-title">{{ key | formatTitle }}</span>
          <el-button size="mini" type="text" @click="resetFilter(key)">
            重置
          </el-button>
        </div>
        <div class="cell-content">
          <!-- 多选模式：复选框组 -->
          <div class="checkbox-group">
            <el-checkbox
              v-for="option in item"
              :key="option"
              v-model="selectedValues[key]"
              :label="option"
              :disabled="isOptionDisabled(key, option)"
              size="small"
              :class="{
                'available-option': !isOptionDisabled(key, option),
                'disabled-option': isOptionDisabled(key, option)
              }"
              @change="handleMultipleSelect(key, selectedValues[key])"
            >
              {{ option }}
            </el-checkbox>
          </div>
        </div>
      </div>
    </div>

    <div class="data-section">
      <div class="table-chart-data">
        <div class="table-chart-data-header">
          <span>月度数据</span>
          <div class="chart-metric-switch">
            <el-button-group>
              <el-button
                size="mini"
                :type="chartMetrics.monthSales === 'quantity' ? 'primary' : ''"
                @click="toggleChartMetric('monthSales', 'quantity')"
              >
                販売数量
              </el-button>
              <el-button
                size="mini"
                :type="chartMetrics.monthSales === 'amount' ? 'primary' : ''"
                @click="toggleChartMetric('monthSales', 'amount')"
              >
                販売金額
              </el-button>
            </el-button-group>
          </div>
        </div>
        <div class="table-chart-data-content">
          <div class="table-card">
            <el-table
              :data="monthData"
              style="width: 100%"
              show-summary
              :height="375"
              size="mini"
              border
            >
              <el-table-column prop="month" label="日付" />
              <el-table-column prop="totalQuantity" label="販売数量" />
              <el-table-column
                prop="totalAmount"
                label="販売金額"
                :formatter="formatAmount"
              />
            </el-table>
          </div>
          <div
            id="monthSalesBarChart"
            class="chart-card"
            style="height: 400px"
          />
        </div>
      </div>
      <div v-for="(item, key) in moreData" :key="key" class="table-chart-data">
        <div class="table-chart-data-header">
          <span>{{ key | formatTitle }}</span>
          <div class="chart-metric-switch">
            <el-button-group>
              <el-button
                size="mini"
                :type="chartMetrics[key] === 'quantity' ? 'primary' : ''"
                @click="toggleChartMetric(key, 'quantity')"
              >
                販売数量
              </el-button>
              <el-button
                size="mini"
                :type="chartMetrics[key] === 'amount' ? 'primary' : ''"
                @click="toggleChartMetric(key, 'amount')"
              >
                販売金額
              </el-button>
            </el-button-group>
          </div>
        </div>
        <div class="table-chart-data-content">
          <div class="table-card">
            <el-table
              :data="item"
              style="width: 100%"
              show-summary
              size="mini"
              border
              :height="375"
            >
              <el-table-column
                v-if="key === 'customer_name'"
                prop="customer_name"
                label="客户"
              />
              <el-table-column
                v-if="key === 'product_code'"
                prop="product_code"
                label="商品コード"
              />
              <el-table-column
                v-if="key === 'brand'"
                prop="brand"
                label="品牌"
              />
              <el-table-column
                v-if="key === 'shop_name'"
                prop="shop_name"
                label="販売店舗"
              />
              <el-table-column prop="totalQuantity" label="販売数量" />
              <el-table-column
                prop="totalAmount"
                label="販売金額"
                :formatter="formatAmount"
              />
            </el-table>
          </div>
          <div :id="getChartId(key)" class="chart-card" style="height: 400px" />
        </div>
      </div>
      <div
        v-for="(item, key, index) in specsData"
        :key="key"
        class="table-chart-data"
      >
        <div class="table-chart-data-header">
          <span>{{ key | formatTitle }}</span>
          <div class="chart-metric-switch">
            <el-button-group>
              <el-button
                size="mini"
                :type="
                  (chartMetrics.specs[key] || 'quantity') === 'quantity'
                    ? 'primary'
                    : ''
                "
                @click="toggleChartMetric('specs', 'quantity', key)"
              >
                販売数量
              </el-button>
              <el-button
                size="mini"
                :type="
                  (chartMetrics.specs[key] || 'quantity') === 'amount'
                    ? 'primary'
                    : ''
                "
                @click="toggleChartMetric('specs', 'amount', key)"
              >
                販売金額
              </el-button>
            </el-button-group>
          </div>
        </div>
        <div class="table-chart-data-content">
          <div class="table-card">
            <el-table
              :data="formatSpecsData(item)"
              style="width: 100%"
              show-summary
              :height="375"
              size="mini"
              border
            >
              <el-table-column prop="name" :label="key" />
              <el-table-column prop="totalQuantity" label="販売数量" />
              <el-table-column
                prop="totalAmount"
                label="販売金額"
                :formatter="formatAmount"
              />
            </el-table>
          </div>
          <div
            :id="getSpecsChartId(key, index)"
            class="chart-card"
            style="height: 400px"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import {
  getAnalysisAllFilterOptions,
  getAnalysisProductAnalysis,
  getAnalysisMonthlyAnalysis,
  getAnalysisComprehensiveAnalysis
} from '@/api/sales-analysis'
export default {
  name: 'RamAnalysis',
  components: {},
  filters: {
    formatTitle(key) {
      if (key === 'product_code') {
        return '商品コード'
      } else if (key === 'shop_name') {
        return '販売店舗'
      } else if (key === 'brand') {
        return '品牌'
      } else if (key === 'customer_name') {
        return '客户'
      }
      return key
    }
  },
  data() {
    return {
      loading: false,
      dateRange: null,
      filters: {
        productCode: ''
      },
      // 筛选选项
      filterOptions: {},
      // 绑定筛选选项
      filterBindOptions: [],
      // 所有筛选项都使用多选模式
      // 每个筛选项的选中值
      selectedValues: {},

      params: {
        startDate: '',
        endDate: '',
        category: ''
      },
      datePickerOptions: {},
      // 月度数据
      monthData: [],
      // 更多数据
      moreData: [],
      // 规格数据
      specsData: {},
      // 图表指标切换状态
      chartMetrics: {
        monthSales: 'quantity', // quantity 或 amount
        customer_name: 'quantity',
        product_code: 'quantity',
        shop_name: 'quantity',
        brand: 'quantity',
        specs: {} // 每个规格图表的独立状态
      }
    }
  },
  computed: {
    /**
     * 计算每个筛选项的可用选项
     * 根据当前选择和其他筛选项的绑定关系，确定哪些选项是可选的
     */
    availableOptions() {
      const result = {}

      // 获取当前所有筛选项的选择状态
      const currentSelections = {}
      Object.keys(this.filterOptions).forEach((key) => {
        const value = this.selectedValues[key]
        if (
          value !== null &&
          value !== undefined &&
          Array.isArray(value) &&
          value.length > 0
        ) {
          currentSelections[key] = value
        }
      })

      // 为每个筛选项计算可用选项
      Object.keys(this.filterOptions).forEach((filterKey) => {
        const options = this.filterOptions[filterKey]
        const available = []

        options.forEach((option) => {
          // 检查这个选项在当前选择下是否可用
          if (this.isOptionAvailable(filterKey, option, currentSelections)) {
            available.push(option)
          }
        })

        result[filterKey] = available
      })

      return result
    }
  },
  watch: {
    specsData: {
      handler(newVal) {
        console.log('specsData变化:', newVal)
        if (newVal && Object.keys(newVal).length > 0) {
          this.$nextTick(() => {
            setTimeout(() => {
              Object.keys(newVal).forEach((key, index) => {
                this.renderSpecsPieChart(key, `specsPieChart${index}`)
              })
            }, 200)
          })
        }
      },
      deep: true
    }
  },
  mounted() {
    if (this.$route.query.category) {
      if (this.$route.query.category === 'ssd') {
        this.params.category = 'SSD'
      } else if (this.$route.query.category === 'ram') {
        this.params.category = '内存'
      } else {
        this.params.category = this.$route.query.category
      }
    }
    this.buildDatePickerOptions()
    this.fetchData()
    this.getData()
  },

  methods: {
    // 转换为千位符
    formatAmount(row) {
      const amount = row && typeof row.totalAmount === 'number' ? row.totalAmount : Number(row && row.totalAmount) || 0
      return amount.toLocaleString('ja-JP')
    },

    // 安全数值格式化（数量）
    formatQuantitySafe(value) {
      const num = typeof value === 'number' ? value : Number(value) || 0
      return num.toLocaleString('ja-JP')
    },

    // 安全金额格式化（带货币符号）
    formatMoneySafe(value) {
      const num = typeof value === 'number' ? value : Number(value) || 0
      return '¥' + num.toLocaleString('ja-JP')
    },

    /**
     * 格式化规格数据，将嵌套对象转换为表格数据格式
     * @param {Object} specsData - 规格数据对象
     * @returns {Array} 格式化后的数组数据
     */
    formatSpecsData(specsData) {
      if (!specsData || typeof specsData !== 'object') {
        return []
      }

      return Object.keys(specsData).map((name) => ({
        name: name,
        totalQuantity: specsData[name].totalQuantity || 0,
        totalAmount: specsData[name].totalAmount || 0
      }))
    },
    /**
     * 构建日期选择器选项：禁用未来时间 + 快捷范围
     */
    buildDatePickerOptions() {
      const today = new Date()
      const startThisMonth = new Date(today.getFullYear(), today.getMonth(), 1)
      const startPrevMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1)
      const endPrevMonth = new Date(today.getFullYear(), today.getMonth(), 0)
      const year = today.getFullYear()
      const lastYear = year - 1

      const shortcuts = []
      const push = (text, start, end) => {
        shortcuts.push({ text, onClick: (picker) => picker.$emit('pick', [this.formatYmd(start), this.formatYmd(end)]) })
      }

      // 固定区间
      push('去年', new Date(lastYear, 0, 1), new Date(lastYear, 11, 31))
      push('本年', new Date(year, 0, 1), today)
      push('上半年', new Date(year, 0, 1), new Date(year, 5, 30))
      push('下半年', new Date(year, 6, 1), today)

      // 相对区间
      push('近1个月', this.addMonths(today, -1), today)
      push('近3个月', this.addMonths(today, -3), today)
      push('近半年', this.addMonths(today, -6), today)

      // 本年每月（至当前月）
      for (let m = 0; m <= today.getMonth(); m++) {
        const start = new Date(year, m, 1)
        const end = new Date(year, m + 1, 0)
        push(`本年${m + 1}月`, start, end)
      }

      this.datePickerOptions = {
        disabledDate(time) {
          return time.getTime() > today.getTime()
        },
        shortcuts
      }

      if (!this.dateRange || !this.params.startDate || !this.params.endDate) {
        // 默认：上一个整月
        this.dateRange = [this.formatYmd(startPrevMonth), this.formatYmd(endPrevMonth)]
        this.params.startDate = this.dateRange[0]
        this.params.endDate = this.dateRange[1]
      }
    },

    // 工具：格式化日期为 YYYY-MM-DD
    formatYmd(date) {
      const y = date.getFullYear()
      const m = String(date.getMonth() + 1).padStart(2, '0')
      const d = String(date.getDate()).padStart(2, '0')
      return `${y}-${m}-${d}`
    },

    // 工具：在日期上加减月份（保留同日，越界自动回退）
    addMonths(date, delta) {
      const d = new Date(date.getTime())
      const day = d.getDate()
      d.setDate(1)
      d.setMonth(d.getMonth() + delta)
      const last = new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate()
      d.setDate(Math.min(day, last))
      return d
    },
    handleDateChange(value) {
      this.params.startDate = value[0]
      this.params.endDate = value[1]
      this.fetchData()
      this.getData()
    },
    // 获取数据
    async fetchData() {
      try {
        this.loading = true

        const response = await getAnalysisAllFilterOptions(this.params)
        this.filterOptions = response

        const bindResponse = await getAnalysisProductAnalysis(this.params)
        this.filterBindOptions = bindResponse

        // 初始化筛选项状态
        this.initializeFilterStates()
      } catch (error) {
        console.error('获取数据失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },

    /**
     * 获取月度数据
     * 根据当前筛选条件获取月度分析数据
     */
    async getData() {
      try {
        // 构建筛选参数，转换为接口需要的重复参数名格式
        const filterParams = {}
        const categorySpecs = {}

        Object.keys(this.selectedValues).forEach((key) => {
          const value = this.selectedValues[key]
          if (
            value !== null &&
            value !== undefined &&
            Array.isArray(value) &&
            value.length > 0
          ) {
            // 检查是否是规格相关的筛选条件
            if (this.specsData && this.specsData[key]) {
              // 这是规格筛选条件，添加到categorySpecs中
              categorySpecs[key] = value
            } else {
              // 转换键名
              let newKey = ''
              if (key === 'product_code') {
                newKey = 'productCode'
              } else if (key === 'shop_name') {
                newKey = 'shopName'
              } else if (key === 'brand') {
                newKey = 'brand'
              } else if (key === 'customer_name') {
                newKey = 'customerName'
              } else {
                newKey = key
              }

              // 将数组转换为重复参数名格式
              filterParams[newKey] = value
            }
          }
        })

        // 如果有规格筛选条件，添加到filterParams中
        if (Object.keys(categorySpecs).length > 0) {
          filterParams.categorySpecs = categorySpecs
        }

        console.log('筛选参数:', filterParams)
        console.log('规格筛选条件:', categorySpecs)

        const resData = await getAnalysisComprehensiveAnalysis({
          ...this.params,
          ...filterParams
        })

        const response = await getAnalysisMonthlyAnalysis({
          ...this.params,
          ...filterParams
        })
        this.monthData = response

        // 处理规格数据
        if (resData.category_specs) {
          this.specsData = resData.category_specs
          console.log('规格数据:', this.specsData)
          delete resData.category_specs
        } else {
          this.specsData = {}
          console.log('未找到规格数据')
        }

        this.moreData = resData

        // 渲染图表
        this.renderAllCharts()

        // if (resData.length) {
        //   this.productData = resData[1].product_code
        //   this.shopData = resData[0].shop_name
        // } else {
        //   this.productData = []
        //   this.shopData = []
        // }
      } catch (error) {
        console.error(error)
      }
    },

    /**
     * 初始化筛选项状态
     * 为每个筛选项设置默认的多选模式和空数组
     */
    initializeFilterStates() {
      const values = {}

      Object.keys(this.filterOptions).forEach((key) => {
        values[key] = [] // 默认无选中值，使用空数组
      })

      this.selectedValues = values
    },

    /**
     * 重置筛选项选择
     * @param {string} filterKey - 筛选项的键名
     */
    resetFilter(filterKey) {
      this.selectedValues[filterKey] = []
    },

    /**
     * 处理多选值变化
     * @param {string} filterKey - 筛选项的键名
     * @param {Array} values - 选中的值数组
     */
    handleMultipleSelect(filterKey, values) {
      this.selectedValues[filterKey] = values
      this.onFilterChange()
    },

    /**
     * 筛选条件变化时的回调
     */
    onFilterChange() {
      console.log('筛选条件变化:', this.selectedValues)
      // 调用月度数据获取
      this.getData()
    },

    /**
     * 检查某个选项是否可用
     * @param {string} filterKey - 筛选项的键名
     * @param {string} option - 要检查的选项值
     * @param {Object} currentSelections - 当前所有筛选项的选择状态
     * @returns {boolean} 是否可用
     */
    isOptionAvailable(filterKey, option, currentSelections) {
      // 如果没有绑定数据或不是数组，所有选项都可用
      if (
        !this.filterBindOptions ||
        !Array.isArray(this.filterBindOptions) ||
        this.filterBindOptions.length === 0
      ) {
        return true
      }

      // 构建临时选择状态来测试这个选项
      const testSelections = { ...currentSelections }
      testSelections[filterKey] = [option]

      // 检查是否有任何绑定记录匹配这个选择组合
      return this.filterBindOptions.some((record) => {
        return this.isSelectionMatch(record, testSelections)
      })
    },

    /**
     * 检查选择状态是否匹配绑定记录
     * @param {Object} record - 绑定记录
     * @param {Object} selections - 选择状态
     * @returns {boolean} 是否匹配
     */
    isSelectionMatch(record, selections) {
      // 检查所有筛选项是否都匹配
      return Object.keys(selections).every((filterKey) => {
        const selectedValues = selections[filterKey]
        const recordValues = record[filterKey]

        // 如果记录中没有这个筛选项，跳过检查
        if (!recordValues) {
          return true
        }

        // 检查是否有交集
        return selectedValues.some((selected) =>
          recordValues.includes(selected)
        )
      })
    },

    /**
     * 检查选项是否被禁用
     * @param {string} filterKey - 筛选项的键名
     * @param {string} option - 选项值
     * @returns {boolean} 是否被禁用
     */
    isOptionDisabled(filterKey, option) {
      return !this.availableOptions[filterKey]?.includes(option)
    },

    /**
     * 渲染月度数据柱形图
     */
    renderMonthSalesChart() {
      this.$nextTick(() => {
        const chartDom = document.getElementById('monthSalesBarChart')
        if (!chartDom) return

        const myChart = echarts.init(chartDom)
        const option = {
          backgroundColor: 'transparent',
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow',
              shadowStyle: {
                color: 'rgba(0, 0, 0, 0.1)'
              }
            },
            backgroundColor: 'rgba(255, 255, 255, 0.95)',
            borderColor: '#e2e8f0',
            borderWidth: 1,
            textStyle: {
              color: '#374151',
              fontSize: 13
            },
            formatter: (params) => {
              let result =
                '<div style="font-weight: 600; margin-bottom: 8px;">' +
                params[0].name +
                '</div>'
              params.forEach((param) => {
                const isQuantity = this.chartMetrics.monthSales === 'quantity'
                const seriesName = isQuantity ? '販売数量' : '販売金額'
                const value = isQuantity
                  ? this.formatQuantitySafe(param && param.value)
                  : this.formatMoneySafe(param && param.value)
                result +=
                  '<div style="margin: 4px 0;"><span style="display: inline-block; width: 10px; height: 10px; background: ' +
                  param.color +
                  '; border-radius: 2px; margin-right: 8px;"></span>' +
                  seriesName +
                  ': <strong>' +
                  value +
                  '</strong></div>'
              })
              return result
            }
          },
          legend: {
            data: ['販売数量', '販売金額'],
            top: 10,
            textStyle: {
              color: '#6b7280',
              fontSize: 12,
              fontWeight: 500
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '12%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: this.monthData.map((item) => item.month),
            axisLine: {
              lineStyle: {
                color: '#e2e8f0'
              }
            },
            axisLabel: {
              color: '#6b7280',
              fontSize: 12
            },
            axisTick: {
              alignWithLabel: true
            }
          },
          yAxis: [
            {
              type: 'value',
              name: '販売数量',
              position: 'left',
              axisLine: {
                show: false
              },
              axisTick: {
                show: false
              },
              axisLabel: {
                color: '#6b7280',
                fontSize: 12
              },
              splitLine: {
                lineStyle: {
                  color: '#f1f5f9',
                  type: 'dashed'
                }
              }
            },
            {
              type: 'value',
              name: '販売金額',
              position: 'right',
              axisLine: {
                show: false
              },
              axisTick: {
                show: false
              },
              axisLabel: {
                color: '#6b7280',
                fontSize: 12,
                formatter: function(value) {
                  return '¥' + (value / 10000).toFixed(0) + '万'
                }
              },
              splitLine: {
                show: false
              }
            }
          ],
          series: [
            {
              name:
                this.chartMetrics.monthSales === 'quantity'
                  ? '販売数量'
                  : '販売金額',
              type: 'bar',
              data: this.monthData.map((item) =>
                this.chartMetrics.monthSales === 'quantity'
                  ? item.totalQuantity
                  : item.totalAmount
              ),
              barWidth: '10px',
              itemStyle: {
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    {
                      offset: 0,
                      color:
                        this.chartMetrics.monthSales === 'quantity'
                          ? '#3b82f6'
                          : '#10b981'
                    },
                    {
                      offset: 1,
                      color:
                        this.chartMetrics.monthSales === 'quantity'
                          ? '#1d4ed8'
                          : '#059669'
                    }
                  ]
                },
                borderRadius: [4, 4, 0, 0]
              }
            }
          ]
        }
        myChart.setOption(option)
        window.addEventListener('resize', () => myChart.resize())
      })
    },

    /**
     * 渲染客户销量占比饼图
     */
    renderCustomerPieChart() {
      this.$nextTick(() => {
        const chartDom = document.getElementById('customerPieChart')
        if (!chartDom) return

        const myChart = echarts.init(chartDom)
        const data = this.moreData.customer_name || []
        const option = {
          backgroundColor: 'transparent',
          tooltip: {
            trigger: 'item',
            backgroundColor: 'rgba(255, 255, 255, 0.95)',
            borderColor: '#e2e8f0',
            borderWidth: 1,
            textStyle: {
              color: '#374151',
              fontSize: 13
            },
            formatter: (params) => {
              const isQuantity = this.chartMetrics.customer_name === 'quantity'
              const metricName = isQuantity ? '販売数量' : '販売金額'
              const value = isQuantity
                ? this.formatQuantitySafe(params && params.value)
                : this.formatMoneySafe(params && params.value)
              return (
                '<div style="font-weight: 600; margin-bottom: 8px;">' +
                params.name +
                '</div>' +
                '<div style="margin: 4px 0;"><span style="display: inline-block; width: 10px; height: 10px; background: ' +
                params.color +
                '; border-radius: 50%; margin-right: 8px;"></span>' +
                metricName +
                ': <strong>' +
                value +
                '</strong></div>' +
                '<div style="margin: 4px 0;">占比: <strong>' +
                params.percent +
                '%</strong></div>'
              )
            }
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            top: 'center',
            textStyle: {
              color: '#6b7280',
              fontSize: 12,
              fontWeight: 500
            },
            itemGap: 8
          },
          series: [
            {
              name:
                this.chartMetrics.customer_name === 'quantity'
                  ? '客户销量占比'
                  : '客户销售额占比',
              type: 'pie',
              radius: ['35%', '65%'],
              center: ['55%', '50%'],
              data: data.map((item) => ({
                value:
                  this.chartMetrics.customer_name === 'quantity'
                    ? item.totalQuantity
                    : item.totalAmount,
                name: item.customer_name
              })),
              itemStyle: {
                borderRadius: 4,
                borderColor: '#ffffff',
                borderWidth: 2
              },
              label: {
                show: false
              },
              labelLine: {
                show: false
              },
              emphasis: {
                itemStyle: {
                  borderWidth: 3,
                  borderColor: '#ffffff'
                }
              }
            }
          ]
        }
        myChart.setOption(option)
        window.addEventListener('resize', () => myChart.resize())
      })
    },

    /**
     * 渲染商品销量排行柱形图
     */
    renderProductRankingChart() {
      this.$nextTick(() => {
        const chartDom = document.getElementById('productRankingChart')
        if (!chartDom) return

        const myChart = echarts.init(chartDom)
        const data = (this.moreData.product_code || [])
          .sort((a, b) => {
            const metric =
              this.chartMetrics.product_code === 'quantity'
                ? 'totalQuantity'
                : 'totalAmount'
            return b[metric] - a[metric]
          })
          .slice(0, 20) // 只取前20名

        // 为每个商品添加排名
        const rankedData = data.map((item, index) => ({
          ...item,
          rank: index + 1,
          displayName: `#${index + 1} ${item.product_code}`
        }))

        const option = {
          backgroundColor: 'transparent',
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow',
              shadowStyle: {
                color: 'rgba(0, 0, 0, 0.1)'
              }
            },
            backgroundColor: 'rgba(255, 255, 255, 0.95)',
            borderColor: '#e2e8f0',
            borderWidth: 1,
            textStyle: {
              color: '#374151',
              fontSize: 13
            },
            formatter: (params) => {
              const rank = rankedData[params[0].dataIndex].rank
              const isTop3 = rank <= 3
              const rankIcon = isTop3
                ? ['🥇', '🥈', '🥉'][rank - 1]
                : `#${rank}`
              const isQuantity = this.chartMetrics.product_code === 'quantity'
              const metricName = isQuantity ? '販売数量' : '販売金額'
              const value = isQuantity
                ? this.formatQuantitySafe(params && params[0] && params[0].value)
                : this.formatMoneySafe(params && params[0] && params[0].value)
              return (
                '<div style="font-weight: 600; margin-bottom: 8px;">' +
                rankIcon +
                ' ' +
                params[0].name +
                '</div>' +
                '<div style="margin: 4px 0;"><span style="display: inline-block; width: 10px; height: 10px; background: ' +
                params[0].color +
                '; border-radius: 2px; margin-right: 8px;"></span>' +
                metricName +
                ': <strong>' +
                value +
                '</strong></div>'
              )
            }
          },
          grid: {
            left: '3%',
            right: '5%',
            bottom: '3%',
            top: '5%',
            containLabel: true
          },
          xAxis: {
            type: 'value',
            show: false,
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              color: '#6b7280',
              fontSize: 12
            },
            splitLine: {
              lineStyle: {
                color: '#f1f5f9',
                type: 'dashed'
              }
            }
          },
          yAxis: {
            type: 'category',
            data: rankedData.map((item) => item.displayName),
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              color: '#6b7280',
              fontSize: 12,
              formatter: function(value) {
                return value
              }
            },
            inverse: true // 反转Y轴，让第一名显示在最上面
          },
          series: [
            {
              name:
                this.chartMetrics.product_code === 'quantity'
                  ? '販売数量'
                  : '販売金額',
              type: 'bar',
              data: rankedData.map((item, index) => ({
                value:
                  this.chartMetrics.product_code === 'quantity'
                    ? item.totalQuantity
                    : item.totalAmount,
                itemStyle: {
                  color: (() => {
                    if (index === 0) return '#ffd700' // 金色 - 第一名
                    if (index === 1) return '#c0c0c0' // 银色 - 第二名
                    if (index === 2) return '#cd7f32' // 铜色 - 第三名
                    return {
                      type: 'linear',
                      x: 0,
                      y: 0,
                      x2: 1,
                      y2: 0,
                      colorStops: [
                        { offset: 0, color: '#8b5cf6' },
                        { offset: 1, color: '#7c3aed' }
                      ]
                    }
                  })()
                }
              })),
              barWidth: '10px',
              itemStyle: {
                borderRadius: [0, 4, 4, 0]
              }
            }
          ]
        }
        myChart.setOption(option)
        window.addEventListener('resize', () => myChart.resize())
      })
    },

    /**
     * 渲染品牌销量占比饼图
     */
    renderBrandPieChart() {
      this.$nextTick(() => {
        const chartDom = document.getElementById('brandPieChart')
        if (!chartDom) return

        const myChart = echarts.init(chartDom)
        const data = this.moreData.brand || []
        const option = {
          backgroundColor: 'transparent',
          tooltip: {
            trigger: 'item',
            backgroundColor: 'rgba(255, 255, 255, 0.95)',
            borderColor: '#e2e8f0',
            borderWidth: 1,
            textStyle: {
              color: '#374151',
              fontSize: 13
            },
            formatter: (params) => {
              const isQuantity = this.chartMetrics.brand === 'quantity'
              const metricName = isQuantity ? '販売数量' : '販売金額'
              const value = isQuantity
                ? this.formatQuantitySafe(params && params.value)
                : this.formatMoneySafe(params && params.value)
              return (
                '<div style="font-weight: 600; margin-bottom: 8px;">' +
                params.name +
                '</div>' +
                '<div style="margin: 4px 0;"><span style="display: inline-block; width: 10px; height: 10px; background: ' +
                params.color +
                '; border-radius: 50%; margin-right: 8px;"></span>' +
                metricName +
                ': <strong>' +
                value +
                '</strong></div>' +
                '<div style="margin: 4px 0;">占比: <strong>' +
                params.percent +
                '%</strong></div>'
              )
            }
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            top: 'center',
            textStyle: {
              color: '#6b7280',
              fontSize: 12,
              fontWeight: 500
            },
            itemGap: 8
          },
          series: [
            {
              name:
                this.chartMetrics.brand === 'quantity'
                  ? '品牌销量占比'
                  : '品牌销售额占比',
              type: 'pie',
              radius: ['35%', '65%'],
              center: ['55%', '50%'],
              data: data.map((item) => ({
                value:
                  this.chartMetrics.brand === 'quantity'
                    ? item.totalQuantity
                    : item.totalAmount,
                name: item.brand
              })),
              itemStyle: {
                borderRadius: 4,
                borderColor: '#ffffff',
                borderWidth: 2
              },
              label: {
                show: false
              },
              labelLine: {
                show: false
              },
              emphasis: {
                itemStyle: {
                  borderWidth: 3,
                  borderColor: '#ffffff'
                }
              }
            }
          ]
        }
        myChart.setOption(option)
        window.addEventListener('resize', () => myChart.resize())
      })
    },

    /**
     * 渲染店铺销量占比饼图
     */
    renderShopPieChart() {
      this.$nextTick(() => {
        const chartDom = document.getElementById('shopPieChart')
        if (!chartDom) return

        const myChart = echarts.init(chartDom)
        const data = this.moreData.shop_name || []
        const option = {
          backgroundColor: 'transparent',
          tooltip: {
            trigger: 'item',
            backgroundColor: 'rgba(255, 255, 255, 0.95)',
            borderColor: '#e2e8f0',
            borderWidth: 1,
            textStyle: {
              color: '#374151',
              fontSize: 13
            },
            formatter: (params) => {
              const isQuantity = this.chartMetrics.shop_name === 'quantity'
              const metricName = isQuantity ? '販売数量' : '販売金額'
              const value = isQuantity
                ? this.formatQuantitySafe(params && params.value)
                : this.formatMoneySafe(params && params.value)
              return (
                '<div style="font-weight: 600; margin-bottom: 8px;">' +
                params.name +
                '</div>' +
                '<div style="margin: 4px 0;"><span style="display: inline-block; width: 10px; height: 10px; background: ' +
                params.color +
                '; border-radius: 50%; margin-right: 8px;"></span>' +
                metricName +
                ': <strong>' +
                value +
                '</strong></div>' +
                '<div style="margin: 4px 0;">占比: <strong>' +
                params.percent +
                '%</strong></div>'
              )
            }
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            top: 'center',
            textStyle: {
              color: '#6b7280',
              fontSize: 12,
              fontWeight: 500
            },
            itemGap: 8
          },
          series: [
            {
              name:
                this.chartMetrics.shop_name === 'quantity'
                  ? '店铺销量占比'
                  : '店铺销售额占比',
              type: 'pie',
              radius: ['35%', '65%'],
              center: ['55%', '50%'],
              data: data.map((item) => ({
                value:
                  this.chartMetrics.shop_name === 'quantity'
                    ? item.totalQuantity
                    : item.totalAmount,
                name: item.shop_name
              })),
              itemStyle: {
                borderRadius: 4,
                borderColor: '#ffffff',
                borderWidth: 2
              },
              label: {
                show: false
              },
              labelLine: {
                show: false
              },
              emphasis: {
                itemStyle: {
                  borderWidth: 3,
                  borderColor: '#ffffff'
                }
              }
            }
          ]
        }
        myChart.setOption(option)
        window.addEventListener('resize', () => myChart.resize())
      })
    },

    /**
     * 渲染规格销售占比饼图
     */
    renderSpecsPieChart(specKey, chartId) {
      this.$nextTick(() => {
        const chartDom = document.getElementById(chartId)
        if (!chartDom) {
          console.warn(`图表容器未找到: ${chartId}`)
          return
        }

        const myChart = echarts.init(chartDom)
        const data = this.formatSpecsData(this.specsData[specKey])

        console.log(`渲染规格图表: ${specKey}`, {
          chartId,
          data,
          specsData: this.specsData[specKey]
        })

        if (!data || data.length === 0) {
          console.warn(`规格数据为空: ${specKey}`)
          return
        }

        const option = {
          backgroundColor: 'transparent',
          tooltip: {
            trigger: 'item',
            backgroundColor: 'rgba(255, 255, 255, 0.95)',
            borderColor: '#e2e8f0',
            borderWidth: 1,
            textStyle: {
              color: '#374151',
              fontSize: 13
            },
            formatter: (params) => {
              const isQuantity =
                (this.chartMetrics.specs[specKey] || 'quantity') === 'quantity'
              const metricName = isQuantity ? '販売数量' : '販売金額'
              const value = isQuantity
                ? this.formatQuantitySafe(params && params.value)
                : this.formatMoneySafe(params && params.value)
              return (
                '<div style="font-weight: 600; margin-bottom: 8px;">' +
                params.name +
                '</div>' +
                '<div style="margin: 4px 0;"><span style="display: inline-block; width: 10px; height: 10px; background: ' +
                params.color +
                '; border-radius: 50%; margin-right: 8px;"></span>' +
                metricName +
                ': <strong>' +
                value +
                '</strong></div>' +
                '<div style="margin: 4px 0;">占比: <strong>' +
                params.percent +
                '%</strong></div>'
              )
            }
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            top: 'center',
            textStyle: {
              color: '#6b7280',
              fontSize: 12,
              fontWeight: 500
            },
            itemGap: 8
          },
          series: [
            {
              name:
                specKey +
                ((this.chartMetrics.specs[specKey] || 'quantity') === 'quantity'
                  ? '销量占比'
                  : '销售额占比'),
              type: 'pie',
              radius: ['35%', '65%'],
              center: ['55%', '50%'],
              data: data.map((item) => ({
                value:
                  (this.chartMetrics.specs[specKey] || 'quantity') ===
                  'quantity'
                    ? item.totalQuantity
                    : item.totalAmount,
                name: item.name
              })),
              itemStyle: {
                borderRadius: 4,
                borderColor: '#ffffff',
                borderWidth: 2
              },
              label: {
                show: false
              },
              labelLine: {
                show: false
              },
              emphasis: {
                itemStyle: {
                  borderWidth: 3,
                  borderColor: '#ffffff'
                }
              }
            }
          ]
        }
        myChart.setOption(option)
        window.addEventListener('resize', () => myChart.resize())
      })
    },

    /**
     * 获取图表ID
     * @param {string} key - 数据键名
     * @returns {string} 图表ID
     */
    getChartId(key) {
      if (key === 'customer_name') {
        return 'customerPieChart'
      } else if (key === 'product_code') {
        return 'productRankingChart'
      } else if (key === 'brand') {
        return 'brandPieChart'
      } else if (key === 'shop_name') {
        return 'shopPieChart'
      }
      return 'defaultChart'
    },

    /**
     * 获取规格图表ID
     * @param {string} key - 规格键名
     * @param {number} index - 索引
     * @returns {string} 图表ID
     */
    getSpecsChartId(key, index) {
      return `specsPieChart${index}`
    },

    /**
     * 切换图表指标
     * @param {string} chartType - 图表类型
     * @param {string} metric - 指标类型 (quantity 或 amount)
     */
    toggleChartMetric(chartType, metric, specKey = null) {
      if (chartType === 'specs' && specKey) {
        // 规格图表：为特定规格设置指标
        this.$set(this.chartMetrics.specs, specKey, metric)
        // 只重新渲染当前规格的图表
        this.$nextTick(() => {
          const index = Object.keys(this.specsData).indexOf(specKey)
          this.renderSpecsPieChart(specKey, `specsPieChart${index}`)
        })
      } else {
        // 其他图表：直接设置指标
        this.chartMetrics[chartType] = metric
        // 重新渲染对应的图表
        switch (chartType) {
          case 'monthSales':
            this.renderMonthSalesChart()
            break
          case 'customer_name':
            this.renderCustomerPieChart()
            break
          case 'product_code':
            this.renderProductRankingChart()
            break
          case 'shop_name':
            this.renderShopPieChart()
            break
          case 'brand':
            this.renderBrandPieChart()
            break
        }
      }
    },

    /**
     * 渲染所有图表
     */
    renderAllCharts() {
      // 先渲染基础图表
      this.renderMonthSalesChart()
      this.renderCustomerPieChart()
      this.renderProductRankingChart()
      this.renderBrandPieChart()
      this.renderShopPieChart()

      // 规格图表由watch监听器处理
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
  width: 100%;
  min-height: 100vh;
  box-sizing: border-box;
  background: #f8fafc;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC',
    'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial,
    sans-serif;
}
.filter-card {
  background: #ffffff;
  padding: 16px 20px;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
  position: relative;
}

.filter-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #3b82f6, #1d4ed8);
  border-radius: 12px 12px 0 0;
}

.filter-card h1 {
  font-size: 20px;
  font-weight: 600;
  color: #1e293b;
  margin: 0;
  letter-spacing: -0.025em;
}
.filter-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
  background: #ffffff;
  padding: 16px;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.filter-cell {
  background: #f8fafc;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
  overflow: hidden;
  display: flex;
  transition: all 0.2s ease;
}

.filter-cell:hover {
  border-color: #cbd5e1;
  background: #f1f5f9;
}

.cell-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #ffffff;
  border-right: 1px solid #e2e8f0;
  min-width: 140px;
  flex-shrink: 0;
}

.cell-content {
  padding: 12px 16px;
  flex-grow: 1;
  width: 0;
  display: flex;
  align-items: center;
  background: #ffffff;
}

.filter-title {
  font-weight: 600;
  color: #374151;
  font-size: 14px;
  letter-spacing: 0.025em;
}

.header-buttons {
  display: flex;
  gap: 8px;
}

.header-buttons .el-button {
  padding: 6px 12px;
  font-size: 12px;
  color: #6b7280;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  background: #ffffff;
  transition: all 0.2s ease;
}

.header-buttons .el-button:hover {
  color: #3b82f6;
  border-color: #3b82f6;
  background: #eff6ff;
}

.header-buttons .el-button.active-mode {
  color: #409eff;
  font-weight: 500;
}

.checkbox-group {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  gap: 8px 12px;
  padding: 4px 0;
}

.checkbox-group .el-checkbox {
  margin-right: 0;
  margin-bottom: 0;
  white-space: nowrap;
  flex-shrink: 0;
  min-width: 200px;
}

.checkbox-group .el-checkbox__label {
  font-size: 13px;
  color: #4b5563;
  font-weight: 500;
  padding-left: 8px;
}

/* 可用选项的高亮样式 */
.available-option .el-checkbox__label {
  color: #1f2937;
  font-weight: 600;
}

.available-option:hover .el-checkbox__label {
  color: #3b82f6;
}

/* 禁用选项的样式 */
.disabled-option .el-checkbox__label {
  color: #c0c4cc;
  text-decoration: line-through;
}

.disabled-option .el-checkbox__input.is-disabled .el-checkbox__inner {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
}

/* 选中状态的样式 */
.available-option.is-checked .el-checkbox__label {
  color: #3b82f6;
  font-weight: 700;
}
.filter-row {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}
.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}
.filter-item label {
  font-weight: 500;
  color: #333;
  white-space: nowrap;
}

.charts-section {
  width: 100%;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.chart-card {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
}
.card-header {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  padding: 15px 20px;
}
.chart-container {
  padding: 20px;
  width: 100%;
  height: auto;
  min-height: 0;
  overflow: hidden;
}
.data-section {
  display: grid;
  grid-template-columns: repeat(1, 1fr);
  gap: 16px;

  .table-chart-data {
    background: #ffffff;
    border-radius: 8px;
    border: 1px solid #e2e8f0;
    overflow: hidden;

    .table-chart-data-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 16px;
      font-weight: 600;
      color: #1e293b;
      padding: 12px 16px;
      background: #f8fafc;
      border-bottom: 1px solid #e2e8f0;
      letter-spacing: -0.025em;
    }

    .chart-metric-switch {
      .el-button-group {
        .el-button {
          padding: 4px 12px;
          font-size: 12px;
          border-radius: 4px;
        }
      }
    }

    .table-chart-data-content {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 0;
      height: 400px;

      .table-card {
        width: 100%;
        height: 100%;
        border-right: 1px solid #e2e8f0;
        padding: 12px;
        background: #ffffff;
      }

      .chart-card {
        width: 100%;
        height: 100%;
        min-height: 400px;
        padding: 12px;
        background: #ffffff;
      }
    }
  }
}

.no-data-section {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  flex-direction: column;
}
.no-data-content {
  text-align: center;
  color: #999;
}
.no-data-content i {
  font-size: 48px;
  margin-bottom: 20px;
  color: #ccc;
  display: block;
}
.no-data-content p {
  font-size: 16px;
  margin: 0 0 10px 0;
  color: #666;
}
.no-data-content small {
  font-size: 14px;
  color: #aaa;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e2e8f0;
}

:deep(.el-table th) {
  background: #f8fafc;
  color: #374151;
  font-weight: 600;
  font-size: 13px;
  border-bottom: 1px solid #e2e8f0;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f1f5f9;
  color: #4b5563;
  font-size: 13px;
}

:deep(.el-table tr:hover > td) {
  background: #f8fafc;
}

:deep(.el-table--mini td) {
  padding: 6px 0;
}

:deep(.el-table--mini th) {
  padding: 8px 0;
}

/* 自定义滚动条样式 */
.checkbox-group::-webkit-scrollbar {
  width: 6px;
}

.checkbox-group::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 3px;
}

.checkbox-group::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
}

.checkbox-group::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}
</style>
