<template>
  <Module style="width:50%">
    <template #title>控股里程增长(km)</template>
    <template #end>
      <div class="type-select">
        <el-select  v-model="activeType" placeholder="请选择" size="mini" @change="updateData"
          :popper-append-to-body="false">
          <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div>
      <el-checkbox class="is-all-checkbox" v-model="isAll" @change="initEcharts" :disabled="selectRoadId.length">
        2020-2025</el-checkbox>
    </template>
    <div class="main-box">
      <Ect :options="ectOpts" class="mileage-canvas" />
    </div>
  </Module>
</template>

<script>
import * as echarts from 'echarts'
import { mileageIncreaseChild } from '@/api/businessOverview'
import { mapState } from 'vuex'
import moment from 'moment';
export default {
  data() {
    return {
      activeType: 'holding',
      typeList: [
        {
          label: '控股里程',
          value: 'holding'
        },
        {
          label: '投资里程',
          value: 'investment'
        },
      ],
      allData: null,
      isAll: true,
      allYear: {
        xAxisData: [],
        increaseData: [],
        currentData: [],
        sumData: [],
      },
      currentYear: {
        xAxisData: [],
        increaseData: [],
        currentData: [],
        sumData: [],
      },
      ectOpts: {},
      baseYear: '2019',
      axisYears: ['2020', '2021', '2022', '2023', '2024', '2025']
    }
  },
  computed: {
    ...mapState({
      selectRoadId: (state) => state.road.selectRoadId,
      appDate: state => state.appDate,
    }),
  },
  watch: {
    selectRoadId(newVal) {
      if (!newVal.length) {
        this.isAll = true
      } else {
        this.activeType = 'holding'
        this.isAll = false
      }
      this.updateData()
    },
    // 监听切换年份
    appDate(newVal) {
      this.currentYear = {
        xAxisData: [],
        increaseData: [],
        currentData: [],
        sumData: [],
      }
      this.formateProvinceChildData()
    },
  },
  mounted() {
    // this.updateData()
  },
  methods: {
    updateData() {
    //   this.reset()
      const level = this.selectRoadId.length

      const queryParam = {
        level, //0全国1省份2公司3路段
        dimension: level ? this.selectRoadId[level - 1] : null,
        cangu: this.activeType === 'investment' ? 1 : 0
      }
      this.getmileageIncrease(queryParam)
    },
    async getmileageIncrease(queryParam) {
      const { msgContent } = await mileageIncreaseChild(queryParam)
      this.reset()
      let result = {}

      const { baseYear, axisYears } = this
      const childrenNameList = [...new Set(msgContent.map(i => i.orgName))] // 所有下级省份/公司/路段名称

      childrenNameList.forEach(item => {
        let chidrenResult = []
        const baseData = msgContent.find(i => i.orgName === item && i.passYear === baseYear) || {}

        axisYears.forEach((element, k) => {
          const child = msgContent.find(i => i.orgName === item && i.passYear === element)
          const currentData = k === 0
            ? (baseData?.passLength || 0)
            : (chidrenResult[k - 1]?.sumData || 0)
          
          chidrenResult.push({
            orgName: item,
            year: element,
            increaseData: child?.passLength || 0,
            currentData,
            sumData: currentData + (child?.passLength || 0)
          })
        })
        console.log(116,chidrenResult);
        result[item] = chidrenResult
      })
      this.allData = result

      if (queryParam.level === 0) {
        // 全国
        this.formateProvinceChildData()
        this.formateCountryAllData()
      } else {
        // 省份
        this.formateProvinceChildData()
        this.formateProvinceAllData()
      }
    },
    formateCountryAllData() {
      const datas = Object.values(this.allData).flat(1)
  
      this.axisYears.forEach(item => {
        const list = datas.filter(i => i.year === item)
        this.allYear.xAxisData.push(item)
        this.allYear.increaseData.push(list.map(i => i.increaseData).reduce((a, b) => a + b))
        this.allYear.currentData.push(list.map(i => i.currentData).reduce((a, b) => a + b))
        this.allYear.sumData.push(list.map(i => i.sumData).reduce((a, b) => a + b))
      })
      this.initEcharts()
    },
    formateProvinceChildData() {
      const year = moment(new Date(this.appDate)).format('yyyy')
      for (const i in this.allData) {
        const { increaseData, currentData, sumData } = this.allData[i].find(i => i.year === year)
        this.currentYear.xAxisData.push(i)
        this.currentYear.increaseData.push(increaseData)
        this.currentYear.currentData.push(currentData)
        this.currentYear.sumData.push(sumData)
      }
      this.initEcharts()
    },
    formateProvinceAllData() {
      for (const i in this.allData) {
        let childSum = {
          increaseData: this.allData[i].map(i => i.increaseData).reduce((a, b) => a + b),
          currentData: this.allData[i].map(i => i.currentData).reduce((a, b) => a + b),
          sumData: this.allData[i].map(i => i.sumData).reduce((a, b) => a + b),
        }
        this.allYear.xAxisData.push(i)
        this.allYear.increaseData.push(childSum.increaseData)
        this.allYear.currentData.push(childSum.currentData)
        this.allYear.sumData.push(childSum.sumData)
      }

      this.initEcharts()

    },

    initEcharts() {
      const { xAxisData, increaseData, currentData, sumData } = this.isAll ? this.allYear : this.currentYear

      const xAxisItemWidth = xAxisData.length
        ? document.querySelector('.mileage-canvas').clientWidth * 0.8 / xAxisData.length
        : 0
      this.ectOpts = {
        legend: {
          // data: ['已开通运营', '新增运营里程'],
          textStyle: {
            fontSize: 11, //字体大小
            color: '#CBE7FF', //字体颜色
          },
          borderRadius: 0,
          selectedMode: true,
          itemHeight: 10,
        },
        tooltip: {
          show: true,
       
        },
        xAxis: {
          data: xAxisData,
          axisLabel: {
            color: '#fff',
            interval: 0,
            formatter: function (value) {
              const left = 12 * value.length - xAxisItemWidth
              if (left > 0 && !Number(value)) {
                return value.substr(0, Math.ceil(xAxisItemWidth / 12) - 2) + "..."
              }
              return value
            },
          },
          axisTick: {
            show: false,
          },
          axisLine: {
            show: false,
          },
          z: 10,
        },
        yAxis: {
          name: '运营里程数(km)',
          splitLine: {
            show: false,
          },
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            textStyle: {
              color: '#909FAC',
            },
          },
          nameTextStyle: {
            color: '#909FAC',
            fontSize: 12,
            fontWeight: 'bold',
          },
        },
        series: [
          {
            name: '已开通运营',
            type: 'bar',
            stack: 'total',
            showBackground: true,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgba(86, 106, 255, 1)',
                },
                {
                  offset: 0.5,
                  color: 'rgba(86, 106, 255, 0.7)',
                },
                {
                  offset: 1,
                  color: 'rgba(86, 106, 255, 0)',
                },
              ]),
            },
            label: {
              show: false,
              color: '#fff',
              position: 'insideBottom'
            },
            barWidth: '10',
            data: currentData.map(i => i.toFixed(2)),
            emphasis: {
              focus: 'series',
            },
            backgroundStyle: {
              color: 'rgba(59, 152, 219, 0)',
              borderWidth: 20,
              borderColor: 'rgba(59, 152, 219, 0.1)',
            },
            barWidth: 8,
          },

          {
            name: '新增运营里程',
            type: 'bar',
            stack: 'total',
            data: increaseData.map(i => i.toFixed(2)),
            label: {
              show: false,
              color: '#fff',
              position: 'top'
            },
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgba(60, 255, 207, 1)',
                },
                {
                  offset: 0.5,
                  color: 'rgba(60, 255, 207, 0.7)',
                },
                {
                  offset: 1,
                  color: 'rgba(60, 255, 207, 0)',
                },
              ]),
            },
            backgroundStyle: {
              color: 'rgba(59, 152, 219, 0)',
              borderWidth: 20,
              borderColor: 'rgba(59, 152, 219, 0.1)',
            },
            barWidth: 8,
          },
          {
            name: '',
            type: 'bar',
            stack: 'total',
            data: [0, 0, 0, 0, 0, 0],
            itemStyle: {
              // normal: {
              //   color: '#fff',
              //   borderWidth: 4,
              //   borderColor: '#fff',
              // },
            },
            barWidth: 20,
            tooltip: {
              show: false
            }
          },
          {
            name: '总运营里程',
            type: 'line',
            smooth: true,
            cursor: 'pointer',
            symbol: 'emptyCircle',
            lineStyle: {
              color: '#00E3FF',
            },
            itemStyle: {
              width: 2,
              borderColor: '#00E3FF',
              color: '#00E3FF',
            },
            label: {
              show: true,
              position: 'top'
            },
            data: sumData.map(i => i.toFixed(2)),
            emphasis: {
              focus: 'series',
            },
          },
        ],
      }
    },
    reset() {
      this.currentYear = {
        xAxisData: [],
        increaseData: [],
        currentData: [],
        sumData: [],
      }
      this.allYear = {
        xAxisData: [],
        increaseData: [],
        currentData: [],
        sumData: [],
      }
    }
  },
}
</script>

<style lang="scss" scoped >
.is-all-checkbox {
  margin-top: 5px;

  ::v-deep .el-checkbox__label {
    padding-left: 5px;
  }
}

.is-all-checkbox:not(.is-checked) {
  ::v-deep .el-checkbox__inner {
    background-color: #606266;
    border-color: #606266;
  }
}

.man-box {
  display: flex;
  flex-direction: column;
}

#main {
  widows: 100%;
  height: 100%;
}

.bar {
  margin: 0 20px;

  display: flex;
  justify-content: space-around;
  background: url('@/assets/images/scale.png') no-repeat;
  background-size: contain;
  /* background-position-x: 10%; */
}

.bar_items {
  cursor: pointer;
  padding-top: 20px;
}

.main-box {
  width: 100%;
}

::v-deep .dropdown {
  vertical-align: top;
  position: absolute;
  right: 0;
  top: 0;
  cursor: pointer;
  z-index: 999;
}

::v-deep .el-button--primary {
  color: rgba(61, 165, 255, 1);
  background: rgba(73, 153, 255, 0.1);
  border-color: transparent;
}

::v-deep .el-dropdown-menu__item {
  text-shadow: none;
}

::v-deep(.module-content) {
  z-index: 0 !important;
  display: block !important;

}

.type-select {
  width: 80px;
  height: 18px;
  margin-right: 5px;
  margin-top: 2px;

  ::v-deep(input::placeholder) {
    color: #94c2e2;
    font-size: 12px;
  }
  ::v-deep(.el-select-dropdown__item) {
    color: #fff;;
}
  ::v-deep(.el-select-dropdown__item):hover {
    color:  #3DA5FF;
}

  ::v-deep(.el-input__inner) {
    color: #3DA5FF;
    font-size: 12px;
    background-color: rgba(73, 153, 255, 0.1);
    border: 1px solid rgba(73, 153, 255, 0.35);
    border-radius: 2px;
    height: 18px;
    line-height: 18px;
    padding-left: 7px;
    padding-right: 20px;
  }

  ::v-deep(.el-input--mini) {
    line-height: 20px;
  }

  ::v-deep(.el-input__icon) {
    width: 16px;
    height: 20px;
    line-height: 20px;
  }

  ::v-deep(.el-select__popper.el-popper) {
    background: rgba(5, 15, 45, 0.7);
    color: white;
  }

}
</style>
