<script setup>
import { onMounted, ref, inject, computed, watch } from 'vue'
import * as echarts from 'echarts'
import TextSelector from '/@/components/TextSelector/index.vue'
import { getAdStructureData } from '/@/views/adManage/sp/targets/api'
import { createDisabledOptions } from '../../../utils/dropdowndisable'
import { barOptions1, barOptions2, barOptionsMap } from '/@/views/adManage/utils/enum'
import { useShopInfo } from '/@/stores/shopInfo'

const shopInfo = useShopInfo()
let barChart = ref()
const pie = ref()
const bar = ref()
const loading = ref(true)

const dateRange = inject('dateRange')

// 下拉框相关
let barModelValue1 = ref(barOptions1[0].value)
let barModelValue2 = ref(barOptions2[2].value)

onMounted(async () => {
  barChart = echarts.init(bar.value)

  window.addEventListener('resize', resizeChart) // 监听窗口大小变化，调整图表大小
  setTimeout(() => {
    resizeChart()
  }, 0)

  await initBarData()
  initChart()
})

// 获取总数据
let allData = null

async function setAdStructureData() {
  allData = await getAdStructureData({ startDate: dateRange.value[0], endDate: dateRange.value[1], profileId: shopInfo.profile.profile_id })
  return allData.data
}

// 柱状图总数据
let barData = null
let responseData = null
// 柱状图初始数据
let ACOSList
let SpendList
let xAxisList
let xAxisMapList

async function initBarData() {
  responseData = await setAdStructureData()
  barData = responseData
  // 柱状图初始化数据
  ACOSList = barData.map((item) => item.ACOS)
  SpendList = barData.map((item) => item.Spend)
  // 将x轴映射为中文
  xAxisList = barData.map((item) => item.Classification)
  const classificationMap = {
    BROAD: '关键词-广泛',
    category: '品类',
    EXACT: '关键词-精准',
    asin: '商品',
    PHRASE: '关键词-词组',
    'close-match': '紧密匹配',
    'loose-match': '广泛匹配',
    substitutes: '同类商品',
    complements: '关联商品',
  }
  xAxisMapList = xAxisList.map((item) => classificationMap[item])
  loading.value = false
}

// 重置图像
let flag = ref()
let option
let option2

// 点击下拉框后重新渲染柱状图
function changeBarOne(newValue) {
  barModelValue1.value = newValue
  updateBarChart()
}

function changeBarTwo(newValue) {
  barModelValue2.value = newValue
  updateBarChart()
}

function updateBarChart() {
  const barValues1 = barData.map((item) => item[barModelValue1.value])
  const barValues2 = barData.map((item) => item[barModelValue2.value])

  option.series[0].data = barValues1
  option.series[1].data = barValues2
  // 同时更新系列的name属性，以确保鼠标悬停时显示的文本正确
  option.series[0].name = barOptionsMap[barModelValue1.value] || barModelValue1.value
  option.series[1].name = barOptionsMap[barModelValue2.value] || barModelValue2.value
  barChart.setOption(option)
}

// 监听时间变化重新渲染表格
watch(dateRange, async () => {
  if (dateRange.value) {
    loading.value = true
    const resp = await setAdStructureData()
    updateBarChartData(resp)
    loading.value = false
  }
})

// 根据新数据和当前下拉框选择更新 柱状图数据
function updateBarChartData(resp) {
  const barValues1 = resp.map((item) => item[barModelValue1.value])
  const barValues2 = resp.map((item) => item[barModelValue2.value])

  option.series[0].data = barValues1
  option.series[1].data = barValues2
  barChart.setOption(option)
}

const computedBarOptions1 = computed(() => createDisabledOptions(barOptions1, barModelValue2.value, barModelValue1.value))
const computedBarOptions2 = computed(() => createDisabledOptions(barOptions2, barModelValue1.value, barModelValue2.value))

// 初始化图表
function initChart() {
  // 柱状图配置
  option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        label: {
          backgroundColor: '#6a7985',
        },
      },
    },
    // legend: {data: ['数据1', '数据2'],},
    toolbox: {
      feature: {
        saveAsImage: { yAxisIndex: 'none' },
      },
    },
    grid: { top: 50, right: 60, bottom: 50, left: 60 },
    xAxis: [
      {
        type: 'category',
        boundaryGap: true,
        data: xAxisMapList,
      },
    ],
    yAxis: [
      {
        type: 'value',
        axisLine: {
          show: true,
          lineStyle: {
            color: '#3a83f7', // 第一个 Y 轴的颜色
          },
        },
      },
      {
        type: 'value',
        splitLine: {
          show: false,
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#f19a37', // 第一个 Y 轴的颜色
          },
        },
      },
    ],
    series: [
      {
        name: barOptionsMap[barModelValue1.value],
        type: 'bar',
        barWidth: '3%',
        data: ACOSList,
        yAxisIndex: 0,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#3a83f7' }, // 起始的鲜亮蓝色
            { offset: 0.5, color: '#5a9ef4' }, // 中间色，中度蓝色
            { offset: 1, color: '#8ab6f1' }, // 结束的浅蓝色
          ]),
          // 柱状图圆角
          borderRadius: [6, 6, 6, 6],
        },
      },
      {
        name: barOptionsMap[barModelValue2.value],
        type: 'bar',
        barWidth: '3%',
        data: SpendList,
        yAxisIndex: 1,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#f19a37' },
            { offset: 0.5, color: '#f7b96c' }, // 中间色，浅橙色
            { offset: 1, color: 'rgb(234, 207, 135)' }, // 结束的浅黄色
          ]),
          // 柱状图圆角
          borderRadius: [6, 6, 6, 6],
        },
      },
    ],
  }
  barChart.setOption(option)
  resizeChart()
}

function resizeChart() {
  barChart.resize()
}
defineExpose({ resizeChart })
</script>

<template>
  <div v-loading="loading">
    <el-row :gutter="5">
      <el-col :span="24">
        <div style="margin-left: 45%">
          <span style="background: #3a83f7; width: 18px; height: 10px; margin-top: 8px; display: inline-block; border-radius: 3px"></span>
          <TextSelector v-model="barModelValue1" :options="computedBarOptions1" @change="changeBarOne" style="margin-top: 5px; margin-left: 8px" />
          <span
            style="
              background: #f19a37;
              width: 18px;
              height: 10px;
              margin-top: 8px;
              margin-left: 20px;
              display: inline-block;
              border-radius: 3px;
            "></span>
          <TextSelector v-model="barModelValue2" :options="computedBarOptions2" @change="changeBarTwo" style="margin-top: 5px; margin-left: 8px" />
        </div>
        <div ref="bar" style="height: 400px"></div>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped></style>
