<template>
  <div class="app-container">
    <!-- 筛选 -->
    <div class="filter-card">
      <div class="filter-section">
        <div class="filter-row">
          <div class="filter-item">
            <label>商品编码：</label>
            <product-code-autocomplete
              v-model="filters.productCode"
              placeholder="请选择要分析的商品编码"
              width="300px"
              @select="handleProductCodeSelect"
              size="small"
            />
          </div>

          <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"
              @change="handleDateChange"
            />
          </div>

          <div class="filter-item">
            <el-button type="primary" @click="fetchData" :loading="loading" size="small">
              查询分析
            </el-button>
            <el-button @click="resetFilter" size="small">重置筛选</el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section" v-if="!isDataEmpty">
      <!-- 商品销售排行 -->
      <div class="chart-card">
        <div class="card-header">
          <span>单品销售排行</span>
        </div>
        <div class="chart-container">
          <div id="rankingChart" style="width: 100%; height: 600px"></div>
        </div>
      </div>

      <!-- 商品销售趋势 -->
      <div class="chart-card">
        <div class="card-header">
          <span>单品销售趋势</span>
        </div>
        <div class="chart-container">
          <div id="trendChart" style="width: 100%; height: 400px"></div>
        </div>
      </div>
    </div>

    <!-- 无数据提示 -->
    <div v-if="!loading && isDataEmpty" class="no-data-section">
      <div class="no-data-content">
        <i class="el-icon-warning-outline"></i>
        <p>暂无数据</p>
        <small>请尝试调整筛选条件或检查数据</small>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import ProductCodeAutocomplete from "@/components/ProductCodeAutocomplete/index.vue";
import { getProductAnalysisReport } from '@/api/sales-analysis'

export default {
  name: "ProductAnalysis",
  components: {
    ProductCodeAutocomplete,
  },
  data() {
    return {
      loading: false,
      dateRange: null,
      filters: {
        productCode: "",
      },
      filterOptions: {},
      statsData: {
        rankingData: [],
        trendData: [],
      },
      trendChart: null,
      rankingChart: null,
      resizeTimer: null, // 防抖定时器
      resizeObserver: null, // ResizeObserver 实例
    };
  },
  computed: {
    isDataEmpty() {
      return (
        (!this.statsData.rankingData ||
          this.statsData.rankingData.length === 0) &&
        (!this.statsData.trendData || this.statsData.trendData.length === 0)
      );
    },
  },
  mounted() {
    this.initDateRange();
    this.fetchFilterOptions();
    // this.fetchData();
    
    // 添加窗口大小变化监听
    window.addEventListener('resize', this.handleResize);
    
    // 使用 ResizeObserver 监听容器尺寸变化
    this.initResizeObserver();
    
    // 初始化图表实例，即使没有数据也要创建
    this.$nextTick(() => {
      this.initCharts();
    });
  },
  beforeDestroy() {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', this.handleResize);
    
    // 清除防抖定时器
    if (this.resizeTimer) {
      clearTimeout(this.resizeTimer);
    }
    
    // 断开 ResizeObserver
    if (this.resizeObserver) {
      this.resizeObserver.disconnect();
    }
    
    if (this.trendChart) {
      this.trendChart.dispose();
    }
    if (this.rankingChart) {
      this.rankingChart.dispose();
    }
  },
  methods: {
    // 初始化日期范围（默认最近30天）
    initDateRange() {
      const endDate = new Date();
      const startDate = new Date();
      startDate.setDate(endDate.getDate() - 30);

      this.dateRange = [
        startDate.toISOString().split("T")[0],
        endDate.toISOString().split("T")[0],
      ];
    },

    // 日期变化处理
    handleDateChange(dates) {
      this.dateRange = dates;
    },

    // 商品编码选择处理
    handleProductCodeSelect(item) {
      this.filters.productCode = item.value;
    },

    // 重置筛选
    resetFilter() {
      this.initDateRange();
      this.filters = {
        productCode: "",
      };
      // 重置后不清空数据，等待新的查询
    },

    // 获取筛选选项 - 此处可以留空或用于其他目的
    async fetchFilterOptions() {},

    // 获取数据
    async fetchData() {
      if (!this.dateRange || this.dateRange.length !== 2) {
        this.$message.warning("请选择日期范围");
        return;
      }
      if (!this.filters.productCode) {
        this.$message.warning("请输入并选择一个商品编码");
        return;
      }

      this.loading = true;
      try {
        const params = {
          startDate: this.dateRange[0],
          endDate: this.dateRange[1],
          productCode: this.filters.productCode,
        };

        const response = await getProductAnalysisReport(params);

        if (response.code === 200) {
          this.statsData = response.data || { rankingData: [], trendData: [] };
          this.$nextTick(() => {
            this.renderTrendChart();
            this.renderRankingChart();
            
            // 数据更新后，确保图表能够响应 resize
            setTimeout(() => {
              this.handleResize();
            }, 200);
          });
        } else {
          this.$message.error(response.message || "获取数据失败");
          this.statsData = { rankingData: [], trendData: [] };
          this.$nextTick(() => {
            this.renderTrendChart();
            this.renderRankingChart();
          });
        }
      } catch (error) {
        console.error("获取数据失败:", error);
        this.$message.error("获取数据失败");
        this.statsData = { rankingData: [], trendData: [] };
        this.$nextTick(() => {
          this.renderTrendChart();
          this.renderRankingChart();
        });
      } finally {
        this.loading = false;
      }
    },

    // 渲染趋势图
    renderTrendChart() {
      const chartDom = document.getElementById("trendChart");
      if (!chartDom) return;

      // 如果图表实例不存在，先初始化
      if (!this.trendChart) {
        this.trendChart = echarts.init(chartDom);
        this.trendChart.resize = this.trendChart.resize.bind(this.trendChart);
      }

      if (!this.statsData.trendData || this.statsData.trendData.length === 0) {
        this.trendChart.clear();
        // 即使没有数据也要保持图表实例，以便 resize 功能正常工作
        return;
      }

      const dates = this.statsData.trendData.map((item) => item.date);
      const amounts = this.statsData.trendData.map((item) => item.amount);
      const quantities = this.statsData.trendData.map((item) => item.quantity);

      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: { type: "cross" },
        },
        legend: {
          data: ["销售额", "销售数量"],
          top: "top",
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "10%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: dates,
            axisPointer: { type: "shadow" },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: "销售额",
            axisLabel: {
              formatter: (value) => `￥${this.formatNumber(value)}`,
            },
          },
          {
            type: "value",
            name: "销售数量",
            axisLabel: { formatter: "{value}" },
          },
        ],
        series: [
          {
            name: "销售额",
            type: "bar",
            data: amounts,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "#5470C6" },
                { offset: 1, color: "#80A4F3" },
              ]),
            },
          },
          {
            name: "销售数量",
            type: "line",
            yAxisIndex: 1,
            smooth: true,
            data: quantities,
            itemStyle: { color: "#5BCCBD" },
          },
        ],
        dataZoom: [
          { type: "inside", start: 0, end: 100 },
          { start: 0, end: 100 },
        ],
      };

      this.trendChart.setOption(option);
    },

    // 渲染商品排行图
    renderRankingChart() {
      const chartDom = document.getElementById("rankingChart");
      if (!chartDom) return;

      // 如果图表实例不存在，先初始化
      if (!this.rankingChart) {
        this.rankingChart = echarts.init(chartDom);
        this.rankingChart.resize = this.rankingChart.resize.bind(this.rankingChart);
      }

      if (
        !this.statsData.rankingData ||
        this.statsData.rankingData.length === 0
      ) {
        this.rankingChart.clear();
        // 即使没有数据也要保持图表实例，以便 resize 功能正常工作
        return;
      }

      const data = [...this.statsData.rankingData].sort(
        (a, b) => a.totalAmount - b.totalAmount
      );

      const dates = data.map((item) => item.date);
      const amounts = data.map((item) => item.totalAmount);
      const quantities = data.map((item) => item.totalQuantity);

      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: { type: "shadow" },
          formatter: (params) => {
            const date = params[0].name;
            const amountParam = params.find((p) => p.seriesName === "销售额");
            const quantityParam = params.find(
              (p) => p.seriesName === "销售数量"
            );
            const amount = amountParam ? amountParam.value : 0;
            const quantity = quantityParam ? quantityParam.value : 0;
            return `日期: ${date}<br/>
                     <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${
                       amountParam.color
                     };"></span>销售额: ￥${this.formatNumber(amount)}<br/>
                     <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${
                       quantityParam.color
                     };"></span>销售数量: ${this.formatNumber(quantity)}`;
          },
        },
        legend: {
          data: ["销售额", "销售数量"],
          top: "top",
        },
        grid: {
          left: "3%",
          right: "10%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "value",
            name: "销售额",
            position: "bottom",
            splitLine: { show: true },
            axisLabel: {
              formatter: (value) => `￥${this.formatNumber(value)}`,
            },
          },
          {
            type: "value",
            name: "销售数量",
            position: "top",
            splitLine: { show: false },
            axisLine: { show: true, onZero: false },
            axisTick: { show: true },
            axisLabel: { formatter: "{value}" },
          },
        ],
        yAxis: {
          type: "category",
          data: dates,
          axisTick: { show: false },
          axisLabel: {
            formatter: (value) =>
              value.length > 30 ? value.substring(0, 30) + "..." : value,
          },
        },
        series: [
          {
            name: "销售额",
            type: "bar",
            xAxisIndex: 0,
            data: amounts,
            itemStyle: { color: "#5470C6" },
            label: {
              show: true,
              position: "right",
              formatter: (params) => `￥${this.formatNumber(params.value)}`,
            },
          },
          {
            name: "销售数量",
            type: "bar",
            xAxisIndex: 1,
            data: quantities,
            itemStyle: { color: "#91CC75" },
            label: {
              show: true,
              position: "right",
              formatter: (params) => `${this.formatNumber(params.value)}`,
            },
          },
        ],
      };

      this.rankingChart.setOption(option);
    },

    // 格式化数字
    formatNumber(num) {
      if (num === null || num === undefined) return "0";
      return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    },

    // 处理窗口大小变化
    handleResize() {
      console.log('窗口大小变化，触发 resize 处理');
      
      // 使用防抖处理，避免频繁调用
      if (this.resizeTimer) {
        clearTimeout(this.resizeTimer);
      }
      
      this.resizeTimer = setTimeout(() => {
        console.log('执行图表 resize');
        
        // 强制触发 DOM 重新计算
        this.$forceUpdate();
        
        // 延迟执行 resize，确保 DOM 更新完成
        this.$nextTick(() => {
          // 检查图表是否存在且已初始化
          if (this.trendChart && this.trendChart.getDom()) {
            console.log('resize 趋势图');
            this.trendChart.resize();
          } else {
            console.log('趋势图不存在或未初始化');
          }
          if (this.rankingChart && this.rankingChart.getDom()) {
            console.log('resize 排行图');
            this.rankingChart.resize();
          } else {
            console.log('排行图不存在或未初始化');
          }
          
          // 额外延迟执行强制 resize，确保大变小的情况也能处理
          setTimeout(() => {
            this.forceChartResize();
          }, 200);
        });
      }, 100);
    },

    // 初始化 ResizeObserver
    initResizeObserver() {
      if (window.ResizeObserver) {
        this.resizeObserver = new ResizeObserver((entries) => {
          console.log('容器尺寸变化检测到');
          this.handleResize();
        });
        
        // 监听图表容器
        this.$nextTick(() => {
          const chartContainers = document.querySelectorAll('.chart-container');
          chartContainers.forEach(container => {
            this.resizeObserver.observe(container);
          });
        });
      }
    },

    // 强制图表 resize
    forceChartResize() {
      console.log('强制图表 resize');
      
      // 强制所有图表重新计算尺寸
      if (this.trendChart && this.trendChart.getDom()) {
        const container = this.trendChart.getDom();
        // 临时改变容器尺寸，然后恢复，强制触发 resize
        const originalWidth = container.style.width;
        container.style.width = '99%';
        setTimeout(() => {
          container.style.width = originalWidth;
          this.trendChart.resize();
        }, 10);
      }
      
      if (this.rankingChart && this.rankingChart.getDom()) {
        const container = this.rankingChart.getDom();
        const originalWidth = container.style.width;
        container.style.width = '99%';
        setTimeout(() => {
          container.style.width = originalWidth;
          this.rankingChart.resize();
        }, 10);
      }
    },

    // 初始化图表实例
    initCharts() {
      console.log('初始化图表实例');
      
      // 初始化趋势图
      const trendChartDom = document.getElementById("trendChart");
      if (trendChartDom && !this.trendChart) {
        this.trendChart = echarts.init(trendChartDom);
        this.trendChart.resize = this.trendChart.resize.bind(this.trendChart);
        console.log('趋势图实例已创建');
      }
      
      // 初始化排行图
      const rankingChartDom = document.getElementById("rankingChart");
      if (rankingChartDom && !this.rankingChart) {
        this.rankingChart = echarts.init(rankingChartDom);
        this.rankingChart.resize = this.rankingChart.resize.bind(this.rankingChart);
        console.log('排行图实例已创建');
      }
    },
  },
};
</script>

<style scoped>
.app-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 10px;
  width: 100%;
  min-height: 100vh;
  box-sizing: border-box;
}
.filter-card {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
}
.filter-section {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.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;
  border: 1px solid #e8e8e8;
  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;
}
.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;
}
</style>
