<template>
  <div class="market-container">
    <div class="market-title">
      <img src="@/assets/images/shb.png" class="title-icon" />
      市场拓展
    </div>
    <div class="legend">
      <div class="legend-item">上月</div>
      <div class="legend-item">本月</div>
    </div>
    <div id="marketChart" class="chart"></div>
  </div>
</template>

<script>
  import { mapState } from "vuex"
  import { api } from "@/api"
  import * as echarts from "echarts"

  export default {
    name: "MarketExpansion",
    data() {
      return {
        chartInstance: null,
        chartData: {
          categories: [
            "新增企业",
            "跟进项目",
            "新增联系人",
            "新增合同",
            "新增项目",
            "新增户数",
          ],
          lastMonthData: [-9, -9, -9, -9, -3, -12], // 上月数据
          thisMonthData: [9, 9, 1, 1, 9, 10], // 本月数据
        },
      }
    },
    computed: {
      ...mapState(["entCode", "communityId"]),
    },
    mounted() {
      this.init()
      window.addEventListener("resize", this.handleResize)
    },
    beforeDestroy() {
      if (this.chartInstance) {
        this.chartInstance.dispose()
      }
      window.removeEventListener("resize", this.handleResize)
    },
    methods: {
      // 初始化组件
      init() {
        this.initChart()
        this.loadData()
      },

      // 初始化图表
      initChart() {
        this.chartInstance = echarts.init(
          document.getElementById("marketChart")
        )

        const option = {
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "shadow",
            },
            backgroundColor: "rgba(17, 28, 49, 0.9)",
            borderColor: "rgba(64, 158, 255, 0.2)",
            textStyle: {
              color: "#ffffff",
            },
            formatter: (params) => {
              // 自定义tooltip格式
              let result = params[0].name + "<br/>"
              params.forEach((item) => {
                result +=
                  item.marker +
                  item.seriesName +
                  ": " +
                  Math.abs(item.value) +
                  "<br/>"
              })
              return result
            },
          },
          grid: {
            left: "25%",
            right: "25%",
            bottom: "3%",
            top: 50,
            containLabel: true,
          },
          xAxis: {
            type: "value",
            axisLabel: {
              formatter: (value) => {
                if (value < 0) return -value //这里是针对取负值
                else return value
              },
            },
            show: false, // 隐藏x轴
          },
          yAxis: [
            {
              type: "category",
              data: this.chartData.categories,
              axisLine: {
                show: false,
              },
              axisTick: {
                show: false,
              },
              axisLabel: {
                show: false,
              },
            },
            {
              type: "category",
              data: this.chartData.categories,
              axisLine: {
                show: false,
              },
              axisTick: {
                show: false,
              },
              axisLabel: {
                show: false,
                color: "#a0b3d6",
                fontSize: 14,
              },
            },
          ],
          series: [
            {
              name: "上月",
              type: "bar",
              //   stack: "sameStack",
              stack: "Total",
              emphasis: {
                focus: "series",
              },
              barMinHeight: 4,
              data: this.chartData.lastMonthData,
              barWidth: 16,
              itemStyle: {
                // 左侧渐变色：从#F66757到#FCE2B4
                color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
                  { offset: 0, color: "#FCE2B4" },
                  { offset: 1, color: "#F66757" },
                ]),
                borderRadius: [20, 0, 0, 20],
              },
              label: {
                show: true,
                position: "left",
                formatter: "{c}",
                color: "#ffffff",
                fontSize: 12,
                formatter: (value) => {
                  return -value.data
                },
              },
            },
            {
              name: "本月",
              type: "bar",
              //   stack: "sameStack",
              stack: "Total",
              emphasis: {
                focus: "series",
              },
              barMinHeight: 4,
              data: this.chartData.thisMonthData,
              barWidth: 16,
              itemStyle: {
                // 右侧渐变色：从#1620D4到#3AB3E3
                color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                  { offset: 0, color: "#3AB3E3" },
                  { offset: 1, color: "#1620D4" },
                ]),
                borderRadius: [0, 20, 20, 0],
              },
              label: {
                show: true,
                position: "right",
                formatter: "{c}",
                color: "#ffffff",
                fontSize: 12,
              },
            },
          ],
        }

        this.chartInstance.setOption(option)
        this.chartInstance.resize()
      },

      // 加载数据
      async loadData() {
        try {
          const params = {
            entCode: this.entCode,
            communityId: this.communityId,
          }
          // 这里应该调用实际的API获取数据
          // const res = await api.getMarketExpansionData(params)
          // this.chartData = res.data || this.chartData

          // 暂时使用模拟数据
          this.updateChart()
        } catch (error) {
          console.error("获取市场拓展数据失败:", error)
        }
      },

      // 更新图表
      updateChart() {
        if (this.chartInstance) {
          this.chartInstance.setOption({
            yAxis: [
              {
                data: this.chartData.categories,
              },
              {
                data: this.chartData.categories,
              },
            ],
            series: [
              {
                data: this.chartData.lastMonthData,
              },
              {
                data: this.chartData.thisMonthData,
              },
            ],
          })
        }
      },

      // 处理窗口大小变化
      handleResize() {
        if (this.chartInstance) {
          this.chartInstance.resize()
        }
      },
    },
  }
</script>

<style lang="scss" scoped>
  @import "@/assets/css/theme.scss";

  .market-container {
    background: #0d1629;
    border-radius: halfW(4);
    height: 100%;
    display: flex;
    flex-direction: column;
    background: var(--content-bg);
  }

  .market-title {
    border-radius: halfW(4);
    background: var(--title-bg);
    padding: halfH(4) halfW(10);
    font-size: halfW(18);
    font-weight: 500;
    color: var(--title-primary);
    display: flex;
    align-items: center;
  }
  .legend {
    display: flex;
    justify-content: space-around;
    align-items: center;
    padding: halfH(10) halfW(20);
    font-size: halfW(14);
    font-weight: 500;
    color: #fff;
    border-bottom: 1px solid rgba(64, 158, 255, 0.2);
  }

  .chart {
    width: 100%;
    height: 100%;
    background: var(--content-bg);
  }
</style>
