<template>
  <div class="app-container">
    <!-- 筛选 -->
    <div class="filter-card">
      <div class="filter-section">
        <div class="filter-row">
          <div class="filter-item" v-if="false">
            <label>店铺：</label>
            <el-select
              v-model="filters.shop"
              placeholder="请选择店铺（默认全部）"
              clearable
              filterable
              style="width: 180px"
              size="small"
            >
              <el-option label="全部店铺" value="" />
              <el-option
                v-for="shop in filterOptions.shops"
                :key="shop"
                :label="shop"
                :value="shop"
              />
            </el-select>
          </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"
              @change="handleDateChange"
              style="width: 380px"
              size="small"
            />
          </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">
      <el-row :gutter="10">
        <el-col :span="12">
          <!-- 各店铺销售金额占比 -->
          <div class="chart-card">
            <div class="card-header">
              <span>各店铺销售金额占比</span>
            </div>
            <div class="chart-container">
              <div
                id="shopAmountChart"
                style="width: 100%; height: 400px"
              ></div>
            </div>
          </div>
        </el-col>
        <el-col :span="12">
          <!-- 各店铺销售数量占比 -->
          <div class="chart-card">
            <div class="card-header">
              <span>各店铺销售数量占比</span>
            </div>
            <div class="chart-container">
              <div
                id="shopQuantityChart"
                style="width: 100%; height: 400px"
              ></div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 各品类销售趋势 -->
      <div class="chart-card">
        <div class="card-header">
          <span>各品类销售数量和销售额趋势</span>
        </div>
        <div class="chart-container">
          <div id="categoryTrendChart" style="width: 100%; height: 500px"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import {
  getReportFilterOptions,
  getShopAnalysisReport,
} from "@/api/sales-analysis";

export default {
  name: "ShopAnalysis",
  components: {},
  data() {
    return {
      loading: false,
      dateRange: null,
      filters: {
        shop: "",
      },
      filterOptions: {
        shops: [],
      },
      statsData: {
        basicStats: null,
        shopAmountData: [],
        shopQuantityData: [],
        categoryTrendData: [],
      },
      shopAmountChart: null,
      shopQuantityChart: null,
      categoryTrendChart: null,
      resizeTimer: null, // 防抖定时器
      resizeObserver: null, // ResizeObserver 实例
    };
  },
  filters: {
    jpMoney(value) {
      if (value === 0) {
        return "0";
      }
      if (value < 10000) {
        return value.toLocaleString("ja-JP", {
          style: "currency",
          currency: "JPY",
          minimumFractionDigits: 0,
          maximumFractionDigits: 0,
        });
      } else {
        // 将value转换为万日元
        const jpValue = (value / 10000).toFixed(0);
        return jpValue;
      }
    },
  },
  mounted() {
    this.initDateRange();
    this.fetchFilterOptions();
    this.fetchData();
    // 添加窗口大小变化监听
    window.addEventListener('resize', this.handleResize);
    
    // 使用 ResizeObserver 监听容器尺寸变化
    this.initResizeObserver();
  },
  beforeDestroy() {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', this.handleResize);
    
    // 清除防抖定时器
    if (this.resizeTimer) {
      clearTimeout(this.resizeTimer);
    }
    
    // 断开 ResizeObserver
    if (this.resizeObserver) {
      this.resizeObserver.disconnect();
    }
    
    if (this.shopAmountChart) {
      this.shopAmountChart.dispose();
    }
    if (this.shopQuantityChart) {
      this.shopQuantityChart.dispose();
    }
    if (this.categoryTrendChart) {
      this.categoryTrendChart.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;
    },

    // 重置筛选
    resetFilter() {
      this.initDateRange();
      this.filters = {
        shop: "",
      };
      this.fetchData();
    },

    // 获取筛选选项
    async fetchFilterOptions() {
      try {
        const response = await getReportFilterOptions();

        if (response.code === 200) {
          this.filterOptions = {
            shops: response.data.shops || [],
          };
        } else {
          console.error("获取筛选选项失败:", response.message);
        }
      } catch (error) {
        console.error("获取筛选选项失败:", error);
      }
    },

    // 获取数据
    async fetchData() {
      if (!this.dateRange || this.dateRange.length !== 2) {
        this.$message.warning("请选择日期范围");
        return;
      }

      try {
        this.loading = true;

        // 构建查询参数
        const params = {
          startDate: this.dateRange[0],
          endDate: this.dateRange[1],
        };

        // 添加店铺筛选条件（如果选择了特定店铺）
        if (this.filters.shop) {
          params.shop = this.filters.shop;
        }

        const response = await getShopAnalysisReport(params);

        if (response.code === 200) {
          this.statsData = response.data;

          this.$nextTick(() => {
            this.renderShopAmountChart();
            this.renderShopQuantityChart();
            this.renderCategoryTrendChart();
            
            // 数据更新后，确保图表能够响应 resize
            setTimeout(() => {
              this.handleResize();
            }, 200);
          });
        } else {
          this.$message.error(response.message || "获取数据失败");
        }
      } catch (error) {
        console.error("获取数据失败:", error);
        this.$message.error("获取数据失败");
      } finally {
        this.loading = false;
      }
    },

    // 渲染店铺销售金额占比图表
    renderShopAmountChart() {
      if (
        !this.statsData.shopAmountData ||
        this.statsData.shopAmountData.length === 0
      ) {
        const chartDom = document.getElementById("shopAmountChart");
        if (chartDom && this.shopAmountChart) {
          this.shopAmountChart.clear();
        }
        return;
      }

      const chartDom = document.getElementById("shopAmountChart");
      if (!chartDom) return;

      if (this.shopAmountChart) {
        this.shopAmountChart.dispose();
      }

      this.shopAmountChart = echarts.init(chartDom);
      
      // 为图表添加 resize 监听
      this.shopAmountChart.resize = this.shopAmountChart.resize.bind(this.shopAmountChart);

      const data = this.statsData.shopAmountData.map((item) => ({
        name: item.shopName,
        value: item.amount,
        percentage: item.percentage,
      }));

      const option = {
        tooltip: {
          trigger: "item",
          formatter: (params) => {
            return `${params.name}<br/>销售额: ￥${this.formatNumber(
              params.value
            )}<br/>占比: ${params.data.percentage}%`;
          },
        },
        legend: {
          type: "scroll",
          orient: "vertical",
          right: 10,
          top: 20,
          bottom: 20,
          data: data.map((item) => item.name),
          textStyle: {
            color: "#666",
          },
          formatter: (name) => {
            const item = data.find((p) => p.name === name);
            const displayName =
              name.length > 15 ? name.slice(0, 15) + "..." : name;

            if (item && item.percentage !== undefined) {
              return `${displayName}  ${item.percentage}%`;
            }
            return displayName;
          },
        },
        series: [
          {
            name: "销售金额",
            type: "pie",
            radius: ["50%", "70%"],
            center: ["40%", "50%"],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: "#fff",
              borderWidth: 2,
            },
            label: {
              show: false,
              position: "center",
            },
            emphasis: {
              label: {
                show: true,
                fontSize: "20",
                fontWeight: "bold",
              },
            },
            labelLine: {
              show: false,
            },
            data: data,
            color: [
              "#5470C6",
              "#91CC75",
              "#FAC858",
              "#EE6666",
              "#73C0DE",
              "#3BA272",
              "#FC8452",
              "#9A60B4",
              "#EA7CCC",
            ],
          },
        ],
      };

      this.shopAmountChart.setOption(option);
    },

    // 渲染店铺销售数量占比图表
    renderShopQuantityChart() {
      if (
        !this.statsData.shopQuantityData ||
        this.statsData.shopQuantityData.length === 0
      ) {
        const chartDom = document.getElementById("shopQuantityChart");
        if (chartDom && this.shopQuantityChart) {
          this.shopQuantityChart.clear();
        }
        return;
      }

      const chartDom = document.getElementById("shopQuantityChart");
      if (!chartDom) return;

      if (this.shopQuantityChart) {
        this.shopQuantityChart.dispose();
      }

      this.shopQuantityChart = echarts.init(chartDom);
      
      // 为图表添加 resize 监听
      this.shopQuantityChart.resize = this.shopQuantityChart.resize.bind(this.shopQuantityChart);

      const data = this.statsData.shopQuantityData.map((item) => ({
        name: item.shopName,
        value: item.quantity,
        percentage: item.percentage,
      }));

      const option = {
        tooltip: {
          trigger: "item",
          formatter: (params) => {
            return `${params.name}<br/>销售数量: ${this.formatNumber(
              params.value
            )}<br/>占比: ${params.data.percentage}%`;
          },
        },
        legend: {
          type: "scroll",
          orient: "vertical",
          right: 10,
          top: 20,
          bottom: 20,
          data: data.map((item) => item.name),
          textStyle: {
            color: "#666",
          },
          formatter: (name) => {
            const item = data.find((p) => p.name === name);
            const displayName =
              name.length > 15 ? name.slice(0, 15) + "..." : name;

            if (item && item.percentage !== undefined) {
              return `${displayName}  ${item.percentage}%`;
            }
            return displayName;
          },
        },
        series: [
          {
            name: "销售数量",
            type: "pie",
            radius: ["50%", "70%"],
            center: ["40%", "50%"],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: "#fff",
              borderWidth: 2,
            },
            label: {
              show: false,
              position: "center",
            },
            emphasis: {
              label: {
                show: true,
                fontSize: "20",
                fontWeight: "bold",
              },
            },
            labelLine: {
              show: false,
            },
            data: data,
            color: [
              "#91CC75",
              "#5470C6",
              "#FAC858",
              "#EE6666",
              "#73C0DE",
              "#3BA272",
              "#FC8452",
              "#9A60B4",
              "#EA7CCC",
            ],
          },
        ],
      };

      this.shopQuantityChart.setOption(option);
    },

    // 渲染品类销售趋势图表
    renderCategoryTrendChart() {
      if (
        !this.statsData.categoryTrendData ||
        this.statsData.categoryTrendData.length === 0
      ) {
        const chartDom = document.getElementById("categoryTrendChart");
        if (chartDom && this.categoryTrendChart) {
          this.categoryTrendChart.clear();
        }
        return;
      }

      const chartDom = document.getElementById("categoryTrendChart");
      if (!chartDom) return;

      if (this.categoryTrendChart) {
        this.categoryTrendChart.dispose();
      }

      this.categoryTrendChart = echarts.init(chartDom);
      
      // 为图表添加 resize 监听
      this.categoryTrendChart.resize = this.categoryTrendChart.resize.bind(this.categoryTrendChart);

      const categories = this.statsData.categoryTrendData.map(
        (item) => item.category
      );
      const amounts = this.statsData.categoryTrendData.map(
        (item) => item.amount
      );
      const quantities = this.statsData.categoryTrendData.map(
        (item) => item.quantity
      );

      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            crossStyle: {
              color: "#999",
            },
          },
          formatter: (params) => {
            let tooltipText = `${params[0].name}<br/>`;
            params.forEach((param) => {
              tooltipText += `${param.marker} ${param.seriesName}: `;
              const value = param.value || 0;
              if (param.seriesName === "销售额") {
                tooltipText += `￥${this.formatNumber(value.toFixed(0))}`;
              } else {
                tooltipText += `${this.formatNumber(value)}`;
              }
              tooltipText += "<br/>";
            });
            return tooltipText;
          },
        },
        legend: {
          data: ["销售额", "销售数量"],
          top: "top",
          itemGap: 20,
          textStyle: {
            color: "#666",
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "25%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: categories,
            axisPointer: {
              type: "shadow",
            },
            axisTick: {
              show: false,
            },
            axisLine: {
              show: false,
            },
            axisLabel: {
              color: "#666",
              interval: 0,
              rotate: 45,
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: "销售额",
            axisLabel: {
              formatter: "￥{value}",
              color: "#666",
            },
            nameTextStyle: {
              color: "#666",
              padding: [0, 0, 0, 40],
            },
            splitLine: {
              lineStyle: {
                type: "dashed",
                color: "#e0e6f1",
              },
            },
            axisLine: { show: false },
            axisTick: { show: false },
          },
          {
            type: "value",
            name: "销售数量",
            axisLabel: {
              formatter: "{value}",
              color: "#666",
            },
            nameTextStyle: {
              color: "#666",
              padding: [0, 40, 0, 0],
            },
            splitLine: { show: false },
            axisLine: { show: false },
            axisTick: { show: false },
          },
        ],
        series: [
          {
            name: "销售额",
            type: "bar",
            barWidth: "40%",
            data: amounts,
            itemStyle: {
              borderRadius: [5, 5, 0, 0],
              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,
            symbol: "circle",
            symbolSize: 8,
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: "rgba(91, 204, 189, 0.5)",
                },
                {
                  offset: 1,
                  color: "rgba(91, 204, 189, 0)",
                },
              ]),
            },
            itemStyle: {
              color: "#5BCCBD",
            },
          },
        ],
        dataZoom: [
          {
            type: "inside",
            start: 0,
            end: 100,
          },
          {
            start: 0,
            end: 100,
            height: 20,
            bottom: 5,
          },
        ],
      };

      this.categoryTrendChart.setOption(option);
    },

    // 格式化数字
    formatNumber(num) {
      if (!num) 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();
        
        // 检查图表是否存在且已初始化
        if (this.shopAmountChart && this.shopAmountChart.getDom()) {
          console.log('resize 店铺金额图');
          this.shopAmountChart.resize();
        }
        if (this.shopQuantityChart && this.shopQuantityChart.getDom()) {
          console.log('resize 店铺数量图');
          this.shopQuantityChart.resize();
        }
        if (this.categoryTrendChart && this.categoryTrendChart.getDom()) {
          console.log('resize 品类趋势图');
          this.categoryTrendChart.resize();
        }
      }, 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);
          });
        });
      }
    },
  },
};
</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: 10px;
}

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

.filter-item label {
  font-weight: 500;
  color: #333;
  white-space: nowrap;
  width: 70px;
}

.filter-item .el-select {
  width: 180px;
}

.filter-item .el-input {
  width: 180px;
}

.filter-actions {
  display: flex;
  gap: 10px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 10px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 15px;
  border: 1px solid #e8e8e8;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: #409eff;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
  flex-shrink: 0;
}

.stat-content {
  flex: 1;
}

.stat-title {
  font-size: 16px;
  color: #505050;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 32px;
  font-weight: 500;
  color: #333;
  margin-bottom: 5px;
}

.stat-value small {
  font-size: 15px;
  color: #505050;
}

.stat-desc {
  font-size: 12px;
  color: #999;
}

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

.chart-card {
  background: white;
}

.chart-container {
  width: 100%;
  height: auto;
  min-height: 0;
  overflow: hidden;
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: 500;
  font-size: 18px;
  padding: 20px;
  justify-content: center;
}

.chart-card {
  background-color: #fff;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
}
.chart-container {
  padding: 10px 0;
}
</style>
