<template>
  <div class="app-container">
    <!-- 筛选 -->
    <div class="filter-card">
      <div class="filter-section">
        <div class="filter-row">
          <div class="filter-item">
            <label>分类：</label>
            <el-select
              v-model="filters.category"
              placeholder="请选择分类"
              clearable
              filterable
              size="small"
            >
              <el-option
                v-for="category in filterOptions.categories"
                :key="category"
                :label="category"
                :value="category"
              />
            </el-select>
          </div>

          <div class="filter-item">
            <label>客户：</label>
            <el-select
              v-model="filters.customer"
              placeholder="请选择客户"
              clearable
              filterable
              size="small"
            >
              <el-option
                v-for="customer in filterOptions.customers"
                :key="customer"
                :label="customer"
                :value="customer"
              />
            </el-select>
          </div>
          <div class="filter-item">
            <label>店铺：</label>
            <el-select
              v-model="filters.shop"
              placeholder="请选择店铺"
              clearable
              filterable
              size="small"
            >
              <el-option
                v-for="shop in filterOptions.shops"
                :key="shop"
                :label="shop"
                :value="shop"
              />
            </el-select>
          </div>

          <div class="filter-item">
            <label>品牌：</label>
            <el-select
              v-model="filters.brand"
              placeholder="请选择品牌"
              clearable
              filterable
              size="small"
            >
              <el-option
                v-for="brand in filterOptions.brands"
                :key="brand"
                :label="brand"
                :value="brand"
              />
            </el-select>
          </div>

          <div class="filter-item">
            <label>规格：</label>
            <el-input
              v-model="filters.categorySpecs"
              placeholder="输入规格关键词"
              clearable
              size="small"
            />
          </div>

          
        </div>
        <div class="filter-row">
          <div class="filter-item" v-if="false">
            <label>商品编码：</label>
            <product-code-autocomplete
              v-model="filters.productCode"
              placeholder="请输入商品编码"
              width="465px"
              @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"
              @change="handleDateChange"
              style="width: 400px"
              size="small"
            />
            <el-button
              style="margin-left: 10px"
              type="primary"
              @click="fetchData"
              :loading="loading"
              size="small"
            >
              查询分析
            </el-button>
            <el-button @click="resetFilter" size="small">重置筛选</el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards" v-if="statsData.basicStats">
      <div class="stat-card">
        <div class="stat-icon">
          <i class="el-icon-money"></i>
        </div>
        <div class="stat-content">
          <div class="stat-title">销售额(日元)</div>
          <div class="stat-value">
            ￥{{ statsData.basicStats.totalAmount | jpMoney }} 
            <small>万</small>
          </div>
          <div
            class="stat-growth"
            :class="getGrowthClass(statsData.growthRates.amountYoY)"
          >
            同比 {{ statsData.growthRates.amountYoY }}%
          </div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon">
          <i class="el-icon-s-goods"></i>
        </div>
        <div class="stat-content">
          <div class="stat-title">销售数量</div>
          <div class="stat-value">
            {{ formatNumber(statsData.basicStats.totalQuantity) }}
          </div>
          <div
            class="stat-growth"
            :class="getGrowthClass(statsData.growthRates.quantityYoY)"
          >
            同比 {{ statsData.growthRates.quantityYoY }}%
          </div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon">
          <i class="el-icon-box"></i>
        </div>
        <div class="stat-content">
          <div class="stat-title">商品种类</div>
          <div class="stat-value">
            {{ formatNumber(statsData.basicStats.uniqueProducts) }}
          </div>
          <div class="stat-desc">不同商品数量</div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon">
          <i class="el-icon-user"></i>
        </div>
        <div class="stat-content">
          <div class="stat-title">客户数量</div>
          <div class="stat-value">
            {{ formatNumber(statsData.basicStats.uniqueCustomers) }}
          </div>
          <div class="stat-desc">不同客户数量</div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <!-- 销售趋势图 -->
      <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>

      <!-- TOP20商品销售 -->
      <div class="chart-card">
        <div class="card-header">
          <span>TOP20商品销售</span>
        </div>
        <div class="chart-container">
          <div id="topProductsChart" 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="brandChart" style="width: 100%; height: 500px"></div>
        </div>
      </div>
    </div>
  </div>
</template>

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

export default {
  name: "OverallAnalysis",
  components: {
    ProductCodeAutocomplete,
  },
  data() {
    return {
      loading: false,
      dateRange: null,
      filters: {
        category: "",
        categorySpecs: "",
        customer: "",
        shop: "",
        brand: "",
        productCode: "",
      },
      filterOptions: {
        categories: [],
        categorySpecs: [],
        customers: [],
        shops: [],
        brands: [],
      },
      statsData: {
        basicStats: null,
        growthRates: null,
        trendData: [],
        topProducts: [],
        brandData: [],
      },
      trendChart: null,
      topProductsChart: null,
      brandChart: null,
      resizeTimer: null, // 防抖定时器
      resizeObserver: null, // ResizeObserver 实例
    };
  },
  filters: {
    jpMoney(value) {
      if (value === 0 || value === null) {
        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.trendChart) {
      this.trendChart.dispose();
    }
    if (this.topProductsChart) {
      this.topProductsChart.dispose();
    }
    if (this.brandChart) {
      this.brandChart.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) {
      // 当选择商品编码时，可以进行一些额外处理
      console.log("选择了商品编码:", item);
    },

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

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

        if (response.code === 200) {
          this.filterOptions = response.data;
        } 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.category) {
          params.category = this.filters.category;
        }
        if (this.filters.categorySpecs) {
          params.categorySpecs = this.filters.categorySpecs;
        }
        if (this.filters.customer) {
          params.customer = this.filters.customer;
        }
        if (this.filters.shop) {
          params.shop = this.filters.shop;
        }
        if (this.filters.brand) {
          params.brand = this.filters.brand;
        }
        if (this.filters.productCode) {
          params.productCode = this.filters.productCode;
        }

        const response = await getOverallAnalysisReport(params);

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

    // 渲染趋势图
    renderTrendChart() {
      if (!this.statsData.trendData || this.statsData.trendData.length === 0) {
        const chartDom = document.getElementById("trendChart");
        if (chartDom && this.trendChart) {
          this.trendChart.clear();
        }
        return;
      }

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

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

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

      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",
            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)}`;
              } else {
                tooltipText += `${this.formatNumber(value)}`;
              }
              tooltipText += "<br/>";
            });
            return tooltipText;
          },
        },
        legend: {
          data: ["销售额", "销售数量"],
          top: "top",
          itemGap: 20,
          textStyle: {
            color: "#666",
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "15%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: dates,
            axisPointer: {
              type: "shadow",
            },
            axisTick: {
              show: false,
            },
            axisLine: {
              show: false,
            },
            axisLabel: {
              color: "#666",
            },
          },
        ],
        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,
          },
        ],
      };

      this.trendChart.setOption(option);
    },

    // 渲染TOP20商品图表
    renderTopProductsChart() {
      if (
        !this.statsData.topProducts ||
        this.statsData.topProducts.length === 0
      ) {
        const chartDom = document.getElementById("topProductsChart");
        if (chartDom && this.topProductsChart) {
          this.topProductsChart.clear();
        }
        return;
      }

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

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

      this.topProductsChart = echarts.init(chartDom);
      
      // 为图表添加 resize 监听
      this.topProductsChart.resize = this.topProductsChart.resize.bind(this.topProductsChart);
      
      const data = [...this.statsData.topProducts]
        .sort((a, b) => a.amount - b.amount)
        .map((item) => ({
          name: item.productCode,
          value: item.amount,
        }));

      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          formatter: (params) => {
            const param = params[0];
            return `${param.name}<br/>${
              param.marker
            }销售额: ￥${this.formatNumber(param.value)}
            `;
          },
        },
        grid: {
          left: "3%",
          right: "10%",
          bottom: "3%",
          top: "0",
          containLabel: true,
        },
        xAxis: {
          type: "value",
          boundaryGap: [0, 0.01],
          axisLabel: {
            formatter: "￥{value}",
            color: "#666",
          },
          axisLine: { show: false },
          axisTick: { show: false },
          splitLine: {
            show: true,
            lineStyle: {
              type: "dashed",
              color: "#e0e6f1",
            },
          },
        },
        yAxis: {
          type: "category",
          data: data.map((item) => item.name),
          axisTick: { show: false },
          axisLine: { show: false },
          axisLabel: {
            formatter: (value) => {
              return value.length > 30 ? value.substring(0, 30) + "..." : value;
            },
            inside: false,
            color: "#666",
          },
        },
        series: [
          {
            name: "销售额",
            type: "bar",
            data: data.map((item) => item.value),
            label: {
              show: true,
              position: "right",
              formatter: (params) =>
                `￥${this.formatNumber(params.value.toFixed(0))}`,
              color: "#464646",
              fontSize: 12,
            },
            itemStyle: {
              color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
                { offset: 0, color: "#83bff6" },
                { offset: 1, color: "#188df0" },
              ]),
            },
          },
        ],
      };

      this.topProductsChart.setOption(option);
    },

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

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

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

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

      const brands = this.statsData.brandData.map(
        (item) => item.brand
      );
      const amounts = this.statsData.brandData.map(
        (item) => item.amount
      );
      const quantities = this.statsData.brandData.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: brands,
            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: "#EE6666" },
                { offset: 1, color: "#F5A3A3" },
              ]),
            },
          },
          {
            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(115, 192, 222, 0.5)",
                },
                {
                  offset: 1,
                  color: "rgba(115, 192, 222, 0)",
                },
              ]),
            },
            itemStyle: {
              color: "#73C0DE",
            },
          },
        ],
        dataZoom: [
          {
            type: "inside",
            start: 0,
            end: 100,
          },
          {
            start: 0,
            end: 100,
            height: 20,
            bottom: 5,
          },
        ],
      };

      this.brandChart.setOption(option);
    },

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

    // 获取增长率样式类
    getGrowthClass(rate) {
      if (rate > 0) return "growth-positive";
      if (rate < 0) return "growth-negative";
      return "growth-neutral";
    },

    // 处理窗口大小变化
    handleResize() {
      console.log('窗口大小变化，触发 resize 处理');
      
      // 使用防抖处理，避免频繁调用
      if (this.resizeTimer) {
        clearTimeout(this.resizeTimer);
      }
      
      this.resizeTimer = setTimeout(() => {
        console.log('执行图表 resize');
        
        // 强制触发 DOM 重新计算
        this.$forceUpdate();
        
        // 检查图表是否存在且已初始化
        if (this.trendChart && this.trendChart.getDom()) {
          console.log('resize 趋势图');
          this.trendChart.resize();
        }
        if (this.topProductsChart && this.topProductsChart.getDom()) {
          console.log('resize TOP20商品图');
          this.topProductsChart.resize();
        }
        if (this.brandChart && this.brandChart.getDom()) {
          console.log('resize 品牌图');
          this.brandChart.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;
}

.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-growth {
  font-size: 12px;
  font-weight: 500;
}

.growth-positive {
  color: #67c23a;
}

.growth-negative {
  color: #f56c6c;
}

.growth-neutral {
  color: #909399;
}

.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>
