<template>
  <div class="regionalEconomy">
    <div class="flex-box query-box">
      <div class="flex-box query-params">
        <span class="common-title">主要指标</span>
        <el-form ref="queryForm" :model="queryParams" :inline="true" size="small">
          <el-form-item prop="year">
            <el-select v-model="queryParams.year" filterable class="form-content-width" placeholder="请选择年度" @change="getGroupCount">
              <el-option v-for="(item, index) in yearOptions" :key="index" :label="item.year" :value="item.year" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div class="flex-box query-ability">
        <span class="flex-box" @click="handleMessage"><img src="@/assets/images/ability_excel.png">导出EXCEL</span>
      </div>
    </div>
    <div class="content">
      <div class="content-left">
        <div id="echarts"  style="height: 400px"></div>
        <p class="tips">  注：数据均来源于统计公报、统计年鉴，实际披露中由于部分地区最新年度数据不全，导致年份间数据差距较大</p>
      </div>
      <div class="content-right">
        <el-table
          v-loading="tableLoading"
          :data="tableData"
          border
          height="440px"
          highlight-current-row
          :summary-method="getSummaries"
          show-summary
        >
          <el-table-column label="序号" width="60" align="left">
            <template slot-scope="scope">{{ scope.$index + 2 }}</template>
          </el-table-column>
          <el-table-column label="产业类型" prop="projectType"></el-table-column>
          <el-table-column :label="oneYear">
            <el-table-column prop="money" label="金额（亿元）" sortable> </el-table-column>
            <el-table-column prop="rate" label="占比（%）"> </el-table-column>
          </el-table-column>
          <el-table-column :label="twoYear">
            <el-table-column prop="lastMoney" label="金额（亿元）"> </el-table-column>
            <el-table-column prop="lastRate" label="占比（%）" > </el-table-column>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
  import * as echarts from 'echarts';
  import { bidGroupCountByProjectType,bidMoneyGroupByProjectType,getYears } from '@/api/macro/macro'
export default {
  name: 'industrialStructure',
  props:['dataQuery','provinceId'],
  data() {
    return {
      queryParams: {
        year: '',
        address: ''
      },
      yearOptions: [],
      tableData:[],
      tableLoading: false,
      data:[],
      oneYear:'',
      twoYear:'',
    }
  },
  watch: {
    provinceId(newValue, oldValue){
      this.getData()
    }
  },
  created() {
    getYears({}).then(res => {
      this.yearOptions=res.data.reverse();
      this.queryParams.year = this.yearOptions[0].year;
    })
    this.getData()
    this.getGroupCount()

    this.$nextTick(()=>{

    })
  },
  methods: {
    getData(){
      let mydate=new Date();
      var startTime, endTime, Year
      Year = mydate.getFullYear();
      startTime=mydate.getFullYear()-2+'-01-01';
      endTime=mydate.getFullYear()-1+'-12-31';
      this.oneYear=mydate.getFullYear()-1+'年';
      this.twoYear=mydate.getFullYear()-2+'年';
      let params={startDate:startTime,endDate:endTime}
      if(this.provinceId.length >= 0){
        params.province=this.provinceId[0]
      }
      if(this.provinceId.length >= 1){
        params.city=this.provinceId[1]
      }
      if(this.provinceId.length >= 2){
        params.county=this.provinceId[2]
      }
      bidMoneyGroupByProjectType(params).then(res => {
        let list=res.data[1].type
        for (let i=0; i<res.data[0].type.length; i++){
          for (let j=0; j<list.length; j++){
            if(res.data[0].type[i].projectType === list[j].projectType){
              list[j].lastMoney=res.data[0].type[i].money;
              list[j].lastRate=res.data[0].type[i].rate;
            }
          }
        }
        this.tableData=list.reverse()
      })
    },
    getGroupCount(){
      let mydate=new Date();
      let startTime=''
      let endTime=''
      if(!this.queryParams.year){
        startTime=mydate.getFullYear()-1+'-01-01';
        endTime=mydate.getFullYear()-1+'-12-31';
      }else {
        startTime=this.queryParams.year+'-01-01';
        endTime=this.queryParams.year+'-12-31';
      }
      bidGroupCountByProjectType({startDate:startTime,endDate:endTime}).then(res => {
        let list=[]
        for(let i=0; i<res.data.length; i++){
          let item={};
          item.name=res.data[i].type
          item.value=res.data[i].count
          list.push(item);
        }
        this.data=list;
        this.initChart()
      })
    },
    initChart() {
      let myChart = echarts.init(document.getElementById("echarts"))
      let option ={
        label: {
          formatter: function (info) {
            var value = info.value
            var treePathInfo = info.treePathInfo
            var treePath = []
            for (var i = 1; i < treePathInfo.length; i++) {
              treePath.push(treePathInfo[i].name)
            }
            let arr=[treePath[0]]
            arr.push(value)
            return arr.join('\n');
          },
        },
        //鼠标悬停时显示的样式
        tooltip: {
          extraCssText:'width:120px!important;',
          formatter: function (params){
            var result = ''
            result+='<p style="color: rgba(35,35,35,0.8);padding: 0;margin: 0;">'+ params.name +'</p>'
            result+='<p style="color: rgba(35,35,35,0.8);padding: 0;margin: 0;">'+ params.value +'</p>'
            return result
          },
        },
        color:['#547FF7', '#63B6EA', '#93A1FF','#60C585','#FF956A','#F6BE5F','#946AFF','#36A860','#7781DD','#E372C6','#F7A396','#3BAAA9','#3F8DB1','#329857','#4A6DCD','#E75E5C','#BE59A4','#FFC094','#7B65DF','#FB8BA7','#CB9EFF'],
        series: [
          {
            type: 'treemap',
            top:'0',
            left:'0',
            right:'0',
            bottom:'20',
            breadcrumb: {
              show: false // 是否显示下面的面包屑导航
            },
            data: this.data
          }
        ]
      }
      myChart.setOption(option);
      window.addEventListener("resize", function () {
        myChart.resize();//图表跟随页面大小变化宽度
      });
    },
    handleMessage(){
      this.$message({
        message: '功能正在开发中',
        type: 'warning'
      });
    },
    getSummaries(param){
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '1';
          return;
        }
        if (index === 1) {
          sums[index] = '合计';
          return;
        }
        if (index === 3) {
          sums[index] = '100';
          return;
        }
        if (index === 5) {
          sums[index] = '100';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return Number(Number(prev) + Number(curr)).toFixed(3)
          } else {
            return prev;
          }
        }, 0);

        // if (index === 1) {
        //   sums[index] = Number(sums[index]).toFixed(0);
        //   return;
        // }
      });
      console.log(sums)
      return sums;
    },

  }
}
</script>

<style lang="scss" scoped>
  .regionalEconomy{
    width: 100%;
    background: #ffffff;
    padding: 16px;
    margin-top: 12px;
    border-radius: 4px;
    .el-form{
      margin-left: 24px;
      .el-form-item{
        margin: 0 !important;
        .form-content-width{
          width: 100px;
        }
      }
    }
    .content{
      margin-top: 22px;
      display: flex;
      justify-content: space-between;
      .content-left{
        width: 46%;
        .tips{
          color: rgba(35,35,35,0.4);
          font-size: 14px;
        }
      }
      .content-right{
        width: 50%;
        ::v-deep .el-table{
          display: flex;
          flex-direction: column;
          .el-table__body-wrapper {
            order: 1;
          }
          .el-table__fixed-footer-wrapper {
            z-index: 0;
            top: 46px;
          }
        }
      }
    }
  }
</style>
