<template>
  <div class="chart-card">
    <a-row type="flex" align="middle" justify="center" :gutter="16">
      <a-col>
        分组条件：
        <a-select v-model="selectedGroup" style="width: 200px" @change="updateCharts">
          <a-select-option v-for="option in groupOptions" :key="option" :value="option">{{ option }}</a-select-option>
        </a-select>
      </a-col>
      <a-col>
        汇总数值列：
        <a-select v-model="selectedValues" mode="multiple" style="width: 200px" @change="updateCharts">
          <a-select-option v-for="option in valueOptions" :key="option" :value="option">{{ option }}</a-select-option>
        </a-select>
      </a-col>
      <a-col>
        对比项：
        <a-select v-model="selectedProjectColumn" style="width: 200px" @change="updateCharts">
          <a-select-option v-for="project in projectOptions" :key="project" :value="project">{{ project }}</a-select-option>
        </a-select>
      </a-col>

    </a-row>
    <a-divider/>
    <a-row align="middle" justify="space-around" :gutter="24">
      <a-col :span="24">
        <div ref="columnChart" class="chart-content"></div>
      </a-col>
    </a-row>
    <a-row align="middle" justify="space-around" :gutter="24">
      <a-col :span="12">
        <div ref="pieChart" class="chart-content"></div>
      </a-col>
      <a-col :span="12">
        <div id="lineChart" ref="lineChart" class="chart-content"></div>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  data () {
    return {
      selectedGroup: null,
      groupOptions: [],
      valueOptions: [],
      projectOptions: [],
      selectedValues: [], // 更新为数组，支持多选
      selectedProjects: [],
      selectedProjectColumn: undefined,
      pieChart: null,
      columnChart: null,
      lineChart: null,
      componentKey: 0,
      commonOptions: {
        tooltip: {
          trigger: 'item'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        legend: {},
      }
    }
  },
  mounted () {
    this.initData()
  },
  props: {
    rawData: {
      type: Array,
      required: true
    }
  },
  watch: {
    rawData: {
      deep: true,
      handler (newVal) {
        this.initData()
      }
    }
  },
  methods: {
    initData () {
      this.initializeOptions()
      if (this.groupOptions.includes('year')) {
        this.selectedGroup = 'year'
      } else {
        this.selectedGroup = this.groupOptions[0]
      }
      if (this.valueOptions.length > 0) {
        this.selectedValues = [this.valueOptions[0]] // 默认选择第一个数值列
      }
      this.updateCharts()
    },
    initializeOptions () {
      if (this.rawData.length > 0) {
        const row = this.rawData[0]
        const columns = Object.keys(row)
        this.groupOptions = columns.filter(key => typeof row[key] === 'string' ||
          this.isYearArray(this.rawData, key))
        this.valueOptions = columns.filter(key => {
          return !isNaN(parseFloat(row[key])) && isFinite(row[key]) && !this.isYear(row[key])
        })
        this.projectOptions = columns.filter(key => typeof row[key] === 'string')
      }
    },
    isYearArray (arr, key) {
      if (arr.some(item => this.isYear(item[key]))) {
        this.updateNonYearItems(arr, key)
        return true
      }
      return false
    },
    // 修改数组中不满足条件的元素的特定键值为1970
    updateNonYearItems (arr, key) {
      arr.forEach(item => {
        if (!this.isYear(item[key])) {
          item[key] = 1970
        }
      })
    },
    // 判断数值或者字符串是不是年份
    isYear (value) {
      return /^(19|20)\d{2}$/.test(value)
    },
    updateCharts () {
      this.renderPieChart()
      this.renderColumnChart()
      this.renderLineChart()
    },
    renderPieChart () {
      const transformedData = this.transformDataForChart('pie')
      const options = {
        series: [
          {
            type: 'pie',
            radius: '50%',
            data: transformedData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      if (!this.pieChart) {
        this.pieChart = echarts.init(this.$refs.pieChart)
      }
      this.pieChart.setOption(Object.assign({},
          this.commonOptions,
          options
        )
      )
    },
    getProjectList () {
      let selectedProjects
      if (this.selectedProjectColumn) {
        selectedProjects = [...new Set(this.rawData.map(item => item[this.selectedProjectColumn]))]
      } else {
        selectedProjects = []
      }
      return selectedProjects
    },
    renderColumnChart () {
      const selectedProjects = this.getProjectList()
      let items
      if (selectedProjects.length > 0) {
        items = selectedProjects
      } else {
        items = this.selectedValues
      }
      const transformedData = this.transformDataForChart()
      const options = {
        dataZoom: [
          {
            type: 'inside'
          },
          {
            type: 'slider'
          }
        ],
        legend: false,
        dataset: {
          dimensions: ['category', ...items],
          source: transformedData
        },
        xAxis: { type: 'category' },
        yAxis: {},
        series: items.map(item => {
          return { type: 'bar' }
        })
      }
      if (!this.columnChart) {
        this.columnChart = echarts.init(this.$refs.columnChart)
      }
      this.columnChart.clear()
      this.columnChart.setOption(Object.assign({},
          this.commonOptions,
          options
        )
      )
    },
    renderLineChart () {
      const transformedData = this.transformDataForChart('line')
      const options = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: this.selectedValues
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.rawData.map(item => item[this.selectedGroup])
        },
        yAxis: {
          type: 'value'
        },
        series: transformedData,
        animationDuration: 2000
      }
      if (!this.lineChart) {
        this.lineChart = echarts.init(this.$refs.lineChart)
      }
      this.lineChart.clear()
      this.lineChart.setOption(Object.assign({},
        this.commonOptions,
        options
      ), true)
    },
    transformDataForChart (type) {
      this.selectedGroup = this.selectedGroup || this.groupOptions[0]
      if (type === 'pie') {
        // 饼图数据转换逻辑：将选中的数值列汇总
        // 以 selectedGroup 分组求和
        const transformedData = {}
        this.rawData.forEach(item => {
          this.selectedValues.forEach(
            valueKey => {
              let key
              if (this.selectedValues.length > 1) {
                key = item[this.selectedGroup] + '_' + valueKey
              } else {
                key = item[this.selectedGroup]
              }
              if (transformedData[key]) {
                transformedData[key] += item[valueKey]
              } else {
                transformedData[key] = item[valueKey]
              }
            }
          )
        })
        return Object.keys(transformedData).map(key => ({
          name: key,
          value: transformedData[key]
        }))
      } else if (type === 'line') {
        // 饼图数据转换逻辑：将选中的数值列汇总
        return this.selectedValues.map(valueKey => ({
          name: valueKey,
          type: 'line',
          stack: 'Total',
          data: this.rawData.map(item => item[valueKey]),
        }))
      } else {
        const selectedProjects = this.getProjectList()
        const transformedData = []
        if (selectedProjects.length > 0 && this.selectedValues.length > 0) {
          // 柱状图的数据转换逻辑
          const categoryMap = {}
          this.rawData.forEach(item => {
            const category = item[this.selectedGroup]
            const key = item[this.selectedProjectColumn]
            if (item[this.selectedValues[0]] > 0) {
              if (!categoryMap[category]) {
                categoryMap[category] = {}
              }
              categoryMap[category][key] = item[this.selectedValues[0]]
            }
          })

          Object.keys(categoryMap).forEach(category => {
            const tempData = { category }
            Object.keys(categoryMap[category]).forEach(key => {
              tempData[key] = categoryMap[category][key]
            })
            transformedData.push(tempData)
          })
        } else {
          // 柱状图数据转换逻辑：为每个分组条件和选中的数值列创建条目
          this.rawData.forEach(item => {
            const tempData = {
              category: item[this.selectedGroup]
            }
            this.selectedValues.forEach(valueKey => {
              tempData[valueKey] = item[valueKey]
            })
            transformedData.push(tempData)
          })
        }
        return transformedData
      }
    },
  }
}
</script>
<style lang="less" scoped>
.chart-card {
  .chart-content {
    height: 400px;
  }
}
</style>
