<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>
    <skeleton v-if="isSkeleton" style="padding: 16px"></skeleton>
    <div class="content" v-if="data.length > 0 && !isSkeleton">
      <div class="content-left">
        <div id="echarts"  style="height: 400px"></div>
        <p class="tips">  注：数据均来源于统计公报、统计年鉴，实际披露中由于部分地区最新年度数据不全，导致年份间数据差距较大</p>
      </div>
      <div class="content-right table-item">
        <el-table
          v-loading="tableLoading"
          :data="tableData"
          border
          height="440px"
          highlight-current-row
          :summary-method="getSummaries"
          show-summary
          @sort-change="sortChange"
        >
          <el-table-column label="序号" width="55" 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="custom" :formatter="formatStatus" min-width="115"></el-table-column>
            <el-table-column prop="rate" label="占比（%）" :sort-method="(a,b)=>{return a.rate - b.rate}" sortable min-width="100"> </el-table-column>
          </el-table-column>
          <el-table-column :label="twoYear">
            <el-table-column prop="lastMoney" label="金额（亿元）" sortable="custom" :formatter="formatStatus" min-width="115"> </el-table-column>
            <el-table-column prop="lastRate" label="占比（%）" :sort-method="(a,b)=>{return a.lastRate - b.lastRate}"  sortable min-width="100"> </el-table-column>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="empty" v-if="data.length === 0 && !isSkeleton">
      <img class="img" src="@/assets/images/project/empty.png">
      <div class="p1">抱歉，暂无数据展示</div>
    </div>
  </div>
</template>

<script>
  import * as echarts from 'echarts';
  import { bidGroupCountByProjectType,bidMoneyGroupByProjectType,getYears } from '@/api/macro/macro'
  import skeleton from '../../component/skeleton'
export default {
  name: 'industrialStructure',
  props:['dataQuery','provinceId'],
  components: {
    skeleton
  },
  data() {
    return {
      queryParams: {
        year: '',
        address: ''
      },
      yearOptions: [],
      tableData:[],
      tabData:[],
      tableLoading: false,
      data:[],
      oneYear:'',
      twoYear:'',
      state:false,
      isSkeleton:true
    }
  },
  watch: {
    provinceId(newValue, oldValue){
      this.getData()
      this.getGroupCount()
    }
  },
  created() {
    getYears({}).then(res => {
      this.yearOptions=res.data.reverse();
      this.queryParams.year = this.yearOptions[0].year;
    })
    // setTimeout(() => {
    //   this.isSkeleton=false;
    //   this.getData()
    //   this.getGroupCount()
    // }, 1000);
    this.$nextTick(()=>{
      this.getData()
      this.getGroupCount()
    })
  },
  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 => {
        if(res.data.length > 0){
          let list=[]
          if(res.data.length > 1){
            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;
                }
              }
            }
          }else {
            list=res.data[0].type
            for (let i=0; i<list.length; i++){
              list[i].lastMoney=0;
              list[i].lastRate=0;
            }
          }
          for(let i=0; i<list.length; i++){
            // list[i].money=list[i].money ? Number(list[i].money).toFixed(2) : '-';
            list[i].rate=list[i].rate ? Number(list[i].rate).toFixed(2) : '-';
            // list[i].lastMoney=list[i].lastMoney ? Number(list[i].lastMoney).toFixed(2) : '-';
            list[i].lastRate=list[i].lastRate ? Number(list[i].lastRate).toFixed(2) : '-';
          }
          this.tableData=list.reverse()
          this.tabData=list.reverse()
        }else {
          this.tableData=[]
          this.tabData=[]
        }
      })
    },
    getGroupCount(){
      this.isSkeleton = true
      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';
      }
      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]
      }
      bidGroupCountByProjectType(params).then(res => {
        if(res.code === 200){
          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;
          if(list.length > 0){
            this.$nextTick(() => {
              this.initChart()
            })
          }
        }
        this.isSkeleton = false
      })
    },
    initChart() {
      this.$nextTick(() => {
        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;',
            backgroundColor:"rgba(255, 255, 255, 0.8)",
            borderWidth:'0',
            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(2)
          } else {
            return prev;
          }
        }, 0);

        // if (index === 1) {
        //   sums[index] = Number(sums[index]).toFixed(0);
        //   return;
        // }
      });
      return sums;
    },
    sortChange(column) {
      if (column.order !== null && column.prop) {
        let data1 = [];
        let data2 = [];
        for (let i = 0; i < this.tableData.length; i++) {
          this.tableData[i].money=this.tableData[i].money ? Number(this.tableData[i].money) : 0
          this.tableData[i].lastMoney=Number(this.tableData[i].lastMoney)
          let temp = null;
          temp = this.tableData[i][column.prop];
          if (temp === null || typeof temp == "undefined") {
            data2.push(this.tableData[i]);
          } else {
            data1.push(this.tableData[i]);
          }
        }
        if (column.order === "ascending") {
          data1 = data1.sort(this.compare(column.prop, "ascending"));
        } else {
          data1 = data1.sort(this.compare(column.prop, "descending"));
        }
        this.$nextTick(() => {
          this.tableData = data1.concat(data2);
        });
      }
      if (column.order === null) {
        this.tableData = this.tabData; // tabData存放的是list副本，不排序时恢复到初始状态
      }
      this.$forceUpdate()
    },
    compare(property, type, prop) {
      return function(obj1, obj2) {
        if (type === "ascending") {
          return obj1[property] - obj2[property];
        } else {
          return obj2[property] - obj1[property];
        }
      };
    },
    formatStatus: function(row, column, cellValue) {
      return cellValue? Number(cellValue).toFixed(2) : '-'
    },

  }
}
</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: 80px;
        }
        ::v-deep .el-input{
          .el-input__inner{
            border: 0;
          }
        }
        ::v-deep .is-focus{
          .el-input__inner{
            background: #F4F6F9;
          }
        }
      }
    }
    .content{
      margin-top: 16px;
      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;
          }
          th{
            font-size: 13px !important;
            font-weight: 400 !important;
          }
          .el-table__fixed-header-wrapper th{
            background: #F0F3FA;
          }
          td.el-table__cell{
            border-bottom: 0;
          }
          .caret-wrapper{
            width: 10px;
          }
          .has-gutter{
            tr{
              th:nth-child(4){
                border-right:0;
                .cell{
                  /*padding-right: 24px !important;*/
                }
              }
              td:nth-child(6){
                border-right:0;
              }
            }
          }
          .el-table__cell.gutter{
            background: #F5F7FA;
            width: 16px !important;
            border-top: 1px solid #dfe6ec;
          }
        }
      }
    }
    .empty{
      margin: 0 auto;
      height: 400px;
      text-align: center;
      .img{
        width: 108px;
        height: 108px;
        margin-bottom: 24px;
        margin-top: 150px;
      }
      .p1{
        color: #333333;
        font-size: 16px;
      }
    }
  }
</style>
