<template>
  <div class="go-border-box">
    <!-- timeshow 按钮，添加点击事件和 ref -->
    <div class="buttonContent">

      <span class="title">{{ configData.title }}</span>

      <button v-if="isShowButton" class="timeShow" @click="toggleDropdown" ref="buttonRef">
        {{ configData.dataSource[selectedIndex]?.dataname || '选择数据' }}
      </button>
    </div>

    <div v-if="showDropdown" class="dropdown-list" ref="dropdownRef">
      <div v-for="(item, index) in configData.dataSource" :key="index" class="dropdown-item"
        :class="{ 'is-active': index === selectedIndex }" @click="selectDataSource(index)">
        {{ item.dataname }}
      </div>
    </div>

    <div class="textContent">
      <div class="textInContent">
        <span class="smallText">{{ configData.names[0] }} </span>
        <span class="bigText">{{ configData.dataSource[selectedIndex].values[0]?.toLocaleString('en-US')
        }}</span>
      </div>
      <div class="textInContent">
        <span class="smallText">{{ configData.names[1] }}</span>
        <span class="bigText">{{ configData.dataSource[selectedIndex].values[1]?.toLocaleString('en-US')
        }}</span>
      </div>
      <div class="textInContent">
        <span class="smallText">{{ configData.names[2] }}</span>
        <span class="bigText">{{ configData.dataSource[selectedIndex].values[2]?.toLocaleString('en-US')
        }}</span>
      </div>
    </div>
    <div class="chartsContent">
      <span class="smallText Tips">
        <img class="icon" src="./icon01.png" alt="">
        {{ configData.tip }}</span>
      <v-chart ref="vChartRef" :init-options="initOptions" :theme="themeColor" :option="chartOption" :update-options="{
        replaceMerge: replaceMergeArr
      }" autoresize>
      </v-chart>
    </div>
  </div>
</template>

<script setup lang="ts">
import { PropType, computed, watch, ref, nextTick, onMounted, onUnmounted } from 'vue'
import VChart from 'vue-echarts'
import { useCanvasInitOptions } from '@/hooks/useCanvasInitOptions.hook'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import Config, { DatasType, includes, seriesItem } from './config'
import { mergeTheme } from '@/packages/public/chart'
import { useChartEditStore } from '@/store/modules/chartEditStore/chartEditStore'
import { useChartDataFetch } from '@/hooks'
import { DatasetComponent, GridComponent, TooltipComponent, LegendComponent } from 'echarts/components'
import isObject from 'lodash/isObject'

const isShowButton = false;

const props = defineProps({
  themeSetting: {
    type: Object,
    required: true
  },
  themeColor: {
    type: Object,
    required: true
  },
  chartConfig: {
    type: Object as PropType<Config>,
    required: true
  }
})

const initOptions = useCanvasInitOptions(props.chartConfig.option, props.themeSetting)

use([DatasetComponent, CanvasRenderer, LineChart, GridComponent, TooltipComponent, LegendComponent])

const replaceMergeArr = ref<string[]>()


const showDropdown = ref(false); // 控制下拉列表显示/隐藏
const selectedIndex = ref(0); // 当前选中的数据源索引

const buttonRef = ref<HTMLElement | null>(null);
const dropdownRef = ref<HTMLElement | null>(null);


// 辅助函数：解析 mockData
const parseMockData = (mockData: any): DatasType => {
  const DEFAULT_MOCK_DATA: DatasType = {
    title: '默认标题',
    names: ['项1', '项2', '项3'],
    tip: "默认提示",
    dataIndex: 0,
    dataSource: [{
      dataname: '默认数据',
      values: [0, 0, 0],
      datavalues: [
        ['维度', '数值'],
        ['0', 0],
        ['1', 0],
        ['2', 0]
      ]
    }]
  };

  let parsedData: DatasType;
  if (typeof mockData === 'string') {
    try {
      const tempParsed = JSON.parse(mockData);
      parsedData = (typeof tempParsed === 'object' && tempParsed !== null) ? tempParsed : DEFAULT_MOCK_DATA;
    } catch (e) {
      console.error('解析 mockData 字符串失败:', e);
      parsedData = DEFAULT_MOCK_DATA;
    }
  } else if (typeof mockData === 'object' && mockData !== null) {
    parsedData = mockData;
  } else {
    parsedData = DEFAULT_MOCK_DATA;
  }

  if (parsedData.dataIndex === undefined || parsedData.dataIndex < 0 || parsedData.dataIndex >= parsedData.dataSource.length) {
    parsedData.dataIndex = 0;
  }

  if (!parsedData.dataSource || parsedData.dataSource.length === 0) {
    parsedData.dataSource = DEFAULT_MOCK_DATA.dataSource;
  }

  if (!parsedData.names || parsedData.names.length === 0) parsedData.names = DEFAULT_MOCK_DATA.names;


  return parsedData;
};


const configData = computed<DatasType>(() => {
  return parseMockData(props.chartConfig.mockData);
});

// 监听 mockData 变化，并初始化 selectedIndex
watch(
  () => props.chartConfig.mockData,
  (newMockData) => {
    const parsedData = parseMockData(newMockData);
    selectedIndex.value = parsedData.dataIndex;
  },
  { immediate: true, deep: true }
);



const chartOption = computed(() => {
  const mergedOption = mergeTheme(props.chartConfig.option, props.themeSetting, includes);


  const currentDataSourceItem = configData.value.dataSource[selectedIndex.value];
  const currentDatavalues = currentDataSourceItem ? currentDataSourceItem.datavalues : [];


  if (!mergedOption.dataset) {
    mergedOption.dataset = {};
  }
  mergedOption.dataset.source = currentDatavalues;

  return mergedOption;
});

const wrapperStyle = computed(() => ({
  width: props.chartConfig.attr.w + 'px',
  height: "16%"
}))


// dataset 无法变更条数的补丁 (保持不变)
watch(
  () => props.chartConfig.option.dataset,
  (newData: { dimensions: any }, oldData) => {
    try {
      if (!isObject(newData) || !('dimensions' in newData)) return
      if (Array.isArray(newData?.dimensions)) {
        const seriesArr = []
        for (let i = 0; i < newData.dimensions.length - 1; i++) {
          seriesArr.push(seriesItem)
        }
        replaceMergeArr.value = ['series']
        props.chartConfig.option.series = seriesArr
        nextTick(() => {
          replaceMergeArr.value = []
        })
      }
    } catch (error) {
      console.log(error)
    }
  },
  {
    deep: false
  }
)

const { vChartRef } = useChartDataFetch(props.chartConfig, useChartEditStore, (newData: any) => {

});


const toggleDropdown = () => {
  showDropdown.value = !showDropdown.value;
};


const selectDataSource = (index: number) => {
  selectedIndex.value = index;
  showDropdown.value = false;
};

const handleClickOutside = (event: MouseEvent) => {
  if (showDropdown.value && dropdownRef.value && buttonRef.value &&
    !dropdownRef.value.contains(event.target as Node) &&
    !buttonRef.value.contains(event.target as Node)) {
    showDropdown.value = false;
  }
};

onMounted(() => {
  document.addEventListener('click', handleClickOutside);
});


onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside);
});
</script>

<script lang="ts">
export default {
  name: 'Componentz01'
}
</script>

<style lang="scss" scoped>
@include go(border-box) {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  height: 100%;
  padding: 0;


}

.textContent {
  padding-top: 20px;
  /* background-color: brown; */
  display: flex;
  justify-content: space-around;
  align-items: center;
  width: 100%;
  height: 30%;
  box-sizing: border-box;
}

.textInContent {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.chartsContent {
  width: 100%;
  height: 80%;
  /* background-color: blue; */
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
}

.textInContent .smallText {
  font-size: 11px;
  color: #a9a9a9;
}

.textInContent .bigText {
  font-size: 18px;
  font-weight: 800;
  letter-spacing: 0.08em;
  color: transparent;
  margin-top: 0.3em;

}

.textContent :nth-child(1) .bigText {
  background: linear-gradient(to right, #ffdc92, #F7BDA7);
  -webkit-background-clip: text;
  background-clip: text;
}

.textContent :nth-child(2) .bigText {
  background: linear-gradient(to right, #86D8F3, #6CDEDF);
  -webkit-background-clip: text;
  background-clip: text;
}

.textContent :nth-child(3) .bigText {
  background: linear-gradient(to right, #6CDFBE, #A2E9D9);
  -webkit-background-clip: text;
  background-clip: text;
}

.Tips {
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  font-size: 10px;
  margin-top: 9px;
  margin-bottom: 8px;
  margin-left: 10px;
  height: 1.6em;
  /* width: 8em; */
  width: fit-content;
  padding: 0.23em 0.4em;
  color: rgb(210, 210, 210);
  background-color: #273F40;
  border-radius: 7px;
  letter-spacing: 0.1em;
}

.icon {
  margin-right: 0.5em;
}

.border {
  position: relative;
}

.timeShow {
  background-color: #086C67;
  border-radius: 10px;
  // position: absolute;
  // right: 6px;
  // top: 12px;
  color: white;
  display: inline-flex;
  height: 1.5em;
  align-items: center;
  padding-right: 5px;
  border: 0;
  cursor: pointer;
  z-index: 10;
  white-space: nowrap;
}

.timeShow::after {
  content: "";
  display: inline-block;
  width: 0;
  height: 0;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 5px solid white;
  margin-left: 5px;

}

.dropdown-list {
  position: absolute;
  top: 45px;
  right: 6px;
  background-color: #1a2a3a;
  border: 1px solid #086C67;
  border-radius: 5px;
  z-index: 999;
  min-width: 100px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
  padding: 5px 0;
  max-height: 200px;
  overflow-y: auto;
  white-space: nowrap;
}

.dropdown-item {
  padding: 8px 12px;
  color: white;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s ease;

  &:hover {
    background-color: #0d4a46;
  }

  &.is-active {
    background-color: #086C67; // 选中项的背景色
    font-weight: bold;
  }


}

.buttonContent {
  margin-top: 5px;
  padding-right: 10px;
  padding-left: 5.2em;
  box-sizing: border-box;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  // background-color: #6CDEDF;
}


.buttonContent span {

  font-size: 15px;
  color: #ffffff;
  letter-spacing: 2px;
  font-weight: 550;
  text-shadow: -4px -4px 10px #3B8ED4;
  padding: 0;
  margin: 0;

}
</style>
