<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="请选择">
              <el-option v-for="(item, index) in yearOptions" :key="index" :label="item.year" :value="item.year" @click.native='handleSelect(item.year)'/>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div class="flex-box query-ability">
        <!--<span class="flex-box"><img src="@/assets/images/ability_vs.png">地区经济对比</span>-->
        <!--<span class="flex-box" @click="handleMessage"><img src="@/assets/images/ability_excel.png">导出EXCEL</span>-->
      </div>
    </div>
    <div class="table-item" ref="regionalStyle" id="regionalStyle">
      <div class="table-title" :class="fixed == true ? 'fixed' : ''" :style="'width:' + StyWidth">
      <!--<div class="table-title">-->
        <span class="span-tit">指标</span>
        <span class="span-tit">
          <span class="address" v-if="value1Flag">{{addressValue1}}<i class="el-icon-circle-close" @click="handleDelete(1)"></i></span>
          <el-cascader
            v-else
            ref="address1"
            :options="addressList"
            :props="props"
            v-model="value1"
            @visible-change="handleVisibleChange($event,1)"
            @change="handleChange(1)"
            placeholder="添加地区"></el-cascader>
        </span>
        <span class="span-tit">
          <span class="address" v-if="value2Flag">{{addressValue2}}<i class="el-icon-circle-close" @click="handleDelete(2)"></i></span>
          <el-cascader
            v-else
            ref="address2"
            :options="addressList"
            :props="props"
            v-model="value2"
            @visible-change="handleVisibleChange($event,2)"
            @change="handleChange(2)"
            placeholder="添加地区"></el-cascader>
        </span>
        <span class="span-tit">
          <span class="address" v-if="value3Flag">{{addressValue3}}<i class="el-icon-circle-close" @click="handleDelete(3)"></i></span>
          <el-cascader
            v-else
            ref="address3"
            :options="addressList"
            :props="props"
            v-model="value3"
            @visible-change="handleVisibleChange($event,3)"
            @change="handleChange(3)"
            placeholder="添加地区"></el-cascader>
        </span>
        <span class="span-tit">
          <span class="address" v-if="value4Flag">{{addressValue4}}<i class="el-icon-circle-close" @click="handleDelete(4)"></i></span>
          <el-cascader
            v-else
            ref="address4"
            :options="addressList"
            :props="props"
            v-model="value4"
            @visible-change="handleVisibleChange($event,4)"
            @change="handleChange(4)"
            placeholder="添加地区"></el-cascader>
        </span>
        <span class="span-tit">
          <span class="address" v-if="value5Flag">{{addressValue5}}<i class="el-icon-circle-close" @click="handleDelete(5)"></i></span>
          <el-cascader
            v-else
            ref="address5"
            :options="addressList"
            :props="props"
            v-model="value5"
            @visible-change="handleVisibleChange($event,5)"
            @change="handleChange(5)"
            placeholder="添加地区"></el-cascader>
        </span>
      </div>
      <el-table
        :data="getValues"
        :show-header="false"
        :cell-style="rowStyle"
        border
      >
        <el-table-column
          v-for="(item, index) in getHeaders"
          :key="index"
          :prop="item"
          :label="item"
          width="16.7%"
          :formatter="formatStatus"
        >
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
  import dataRegion from '@/assets/json/dataRegion'
  import elementResizeDetectorMaker from "element-resize-detector"
  import { regionalCompare,getYears,multipleCompare } from '@/api/macro/macro'
export default {
  name: 'comparison',
  props:['dataQuery','provinceId'],
  components: {

  },
  data() {
    return {
      queryParams: {
        year: '',
      },
      yearOptions: [],
      tableData: [{},{},{},{},{}],
      headers: [
        {
          prop: 'name',
          label: '经济',
        },
        {
          prop: 'gdp',
          label: 'GDP（亿元）',
        },
        {
          prop: 'gdpGrowth',
          label: 'GDP增速（%）',
        },
        {
          prop: 'gdpPerCapita',
          label: '人均GDP（元）',
        },
        {
          prop: 'piAddValue',
          label: '第一产业增加值（亿元）',
        },
        {
          prop: 'siAddValue',
          label: '第二产业增加值（亿元）',
        },
        {
          prop: 'tiAddValue',
          label: '第三产业增加值（亿元）',
        },
        {
          prop: 'population',
          label: '人口（万人）',
        },
        {
          prop: 'industryAddValue',
          label: '工业增加值（亿元）',
        },
        {
          prop: 'industryTotalValue',
          label: '工业总产值（亿元）',
        },
        {
          prop: 'fixedInvestment',
          label: '固定资产投资（亿元）',
        },
        {
          prop: 'realEstateInvestment',
          label: '房地产开发投资（亿元）',
        },
        {
          prop: 'eximTotalValue',
          label: '进出口总额（亿美元）',
        },
        {
          prop: 'trscg',
          label: '社会消费品零售总额（亿元）',
        },
        {
          prop: 'urbanPcdi',
          label: '城镇居民人均可支配收入（元）',
        },
        {
          prop: 'name',
          label: '财政',
        },
        {
          prop: 'gbr',
          label: '一般公共预算收入（亿元）',
        },
        {
          prop: 'gbrGrowth',
          label: '一般公共预算收入增速(%)',
        },
        {
          prop: 'taxIncome',
          label: '税收收入（亿元）',
        },
        {
          prop: 'transferIncome',
          label: '转移性收入（亿元）',
        },
        {
          prop: 'superiorSubsidyIncome',
          label: '上级补助收入（亿元）',
        },
        {
          prop: 'gbe',
          label: '一般公共预算支出（亿元）',
        },
        {
          prop: 'govFundIncome',
          label: '政府性基金收入（亿元）',
        },
        {
          prop: 'landTransferIncome',
          label: '土地出让收入（亿元）',
        },
        {
          prop: 'govFundExpenditure',
          label: '政府性基金支出（亿元）',
        },
        {
          prop: 'soecoi',
          label: '国有资本经营收入（亿元）',
        },
        {
          prop: 'soecoe',
          label: '国有资本经营支出（亿元）',
        },
        {
          prop: 'name',
          label: '债务',
        },
        {
          prop: 'govDebtBalance',
          label: '地方政府债务余额（亿元）',
        },
        {
          prop: 'generalDebtBalance',
          label: '一般债余额（亿元）',
        },
        {
          prop: 'specialDebtBalance',
          label: '专项债余额（亿元）',
        },
        {
          prop: 'govDebtLimit',
          label: '地方政府债务限额（亿元）',
        },
        {
          prop: 'uipInterestBearingDebt',
          label: '城投平台有息债务（亿元）',
        },
        {
          prop: 'fiscalSelfSufficiencyRate',
          label: '财政自给率(%)',
        },
        {
          prop: 'govDebtToGdpRate',
          label: '负债率(%)',
        },
        {
          prop: 'govDebtToGdpRateWild',
          label: '负债率(宽口径)(%)',
        },
        {
          prop: 'govDebtRate',
          label: '债务率(%)',
        },
        {
          prop: 'govDebtRateWild',
          label: '债务率(宽口径)(%)',
        },
      ],
      props: {
        value: 'id',
        checkStrictly: true
      },
      addressList: [],
      value1:'',
      value2:'',
      value3:'',
      value4:'',
      value5:'',
      addressValue1:'',
      addressValue2:'',
      addressValue3:'',
      addressValue4:'',
      addressValue5:'',
      value1Flag:false,
      value2Flag:false,
      value3Flag:false,
      value4Flag:false,
      value5Flag:false,
      regionData:[],
      compareList:[{},{},{},{},{}],
      fixed: false,
      StyWidth:null,
      isSkeleton:true
    }
  },
  watch: {
    provinceId(newValue, oldValue){
      console.log(newValue)
    }
  },
  mounted(){
    window.addEventListener('scroll', this.handleScroll);
    const _this = this, erd = elementResizeDetectorMaker(), partBox = document.getElementById("regionalStyle")
    erd.listenTo(partBox, element => {
      _this.$nextTick(() => {
        this.StyWidth = partBox.offsetWidth + 'px';
      })
    })
  },
  destroyed () {
    window.removeEventListener('scroll', this.handleScroll)
  },
  created() {
    this.dataRegion();
    // this.getData();
    getYears({}).then(res => {
      this.yearOptions=res.data.reverse();
      this.queryParams.year = this.yearOptions[0].year;
      if(this.dataQuery.pId){
        let item={}
        if(this.provinceId.length >= 0){
          item.provinceId=this.provinceId[0]
        }
        if(this.provinceId.length >= 1){
          item.cityId=this.provinceId[1]
        }
        if(this.provinceId.length >= 2){
          item.areaId=this.provinceId[2]
        }
        // if(this.dataQuery.id){
        //   item.id=this.dataQuery.id
        // }
        this.compareList.splice(0,1,item);
        this.value1Flag=true
        this.addressValue1=this.dataQuery.province.join('-')

        let list=[];
        for (let i=0; i<this.compareList.length; i++){
          if(this.compareList[i].provinceId){
            list.push(this.compareList[i])
          }
        }
        let params={}
        params.compareList=list;
        this.getData(params)
      }
    })
  },
  computed: {
    getHeaders() {
      return this.tableData.reduce((pre, cur, index) => pre.concat(`value${index}`), ['title'])
    },
    getValues() {
      return this.headers.map(item => {
        return this.tableData.reduce((pre, cur, index) => Object.assign(pre, {['value' + index]: cur[item.prop]}), {'title': item.label,});
      });
    }
  },
  methods: {
    handleScroll () {
      let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
      if (scrollTop > 145) {
        this.fixed = true
      } else {
        this.fixed = false
      }
    },
    getData(params){
      params.year=this.queryParams.year;
      multipleCompare(params).then(res => {
        if(res.data){
          let arr=[]
          for (let i=0; i<this.compareList.length; i++){
            if(this.compareList[i].provinceId){
              arr.push(i)
            }
          }
          for (let j=0; j<res.data.length; j++){
            this.tableData.splice(arr[j],1,res.data[j])
          }
          this.$forceUpdate();
        }
      })
    },
    //地区
    async dataRegion() {
      // await axios.post("https://files.jiansheku.com/file/json/common/dataRegion.json", {}, {
      //   headers: {
      //     'Content-Type': 'application/json'
      //   }
      // }).then(res => {
      //   if (res.data.code == 200) {
      //     console.log(res.data.data)
      //   }
      // })
      var str = [];
      for (let x = 0; x < 3; x++) {
        for (let i = 0; i < dataRegion.length; i++) {
          if (dataRegion[i].regionLevel == x + 1 && x + 1 == 1) {
            str.push({
              'id': dataRegion[i].id,
              "label": dataRegion[i].regionName,
              "short": dataRegion[i].short,
              "value": dataRegion[i].parentId,
              "children": []
            });
          } else if (dataRegion[i].regionLevel == x + 1 && x + 1 == 2) {
            for (let j = 0; j < str.length; j++) {
              if (str[j].id == dataRegion[i].parentId) {
                str[j].children.push({
                  'id': dataRegion[i].id,
                  "label": dataRegion[i].regionName,
                  "short": dataRegion[i].short,
                  "value": dataRegion[i].parentId,
                  "children": []
                });
              }
            }
          } else if (dataRegion[i].regionLevel == x + 1 && x + 1 == 3) {
            for (let j = 0; j < str.length; j++) {
              for (let k = 0; k < str[j].children.length; k++) {
                if (str[j].children[k].id == dataRegion[i].parentId) {
                  str[j].children[k].children.push({
                    'id': dataRegion[i].id,
                    "label": dataRegion[i].regionName,
                    "short": dataRegion[i].short,
                    "value": dataRegion[i].parentId
                    // "children":[]
                  });
                }
              }
            }
          }
        }
      }
      this.addressList = str;
    },
    handleVisibleChange(flag,index){
      if(!flag){
        if((index === 1 && this.value1) || (index === 2 && this.value2) || (index === 3 && this.value3) || (index === 4 && this.value4) || (index === 5 && this.value5)){
          switch (index) {
            case 1:
              this.value1Flag=true
              break;
            case 2:
              this.value2Flag=true
              break;
            case 3:
              this.value3Flag=true
              break;
            case 4:
              this.value4Flag=true
              break;
            case 5:
              this.value5Flag=true
              break;
          }
          const params = {}
          let code=[];
          for (var i in this.regionData) {
            code=this.regionData[i].path
          }
          let item={}
          if(code.length >= 1){
            item.provinceId=code[0]
          }
          if(code.length >= 2){
            item.cityId=code[1]
          }
          if(code.length >= 3){
            item.areaId=code[2]
          }
          // if(this.dataQuery.id){
          //   item.id=this.dataQuery.id
          // }
          this.compareList.splice(index-1,1,item);

          let list=[];
          for (let i=0; i<this.compareList.length; i++){
            if(this.compareList[i].provinceId){
              list.push(this.compareList[i])
            }
          }
          params.compareList=list;
          this.getData(params)
        }
      }
    },
    handleChange(index) {
      let arr = '';
      switch (index) {
        case 1:
          arr = this.$refs.address1.getCheckedNodes()
          break;
        case 2:
          arr = this.$refs.address2.getCheckedNodes()
          break;
        case 3:
          arr = this.$refs.address3.getCheckedNodes()
          break;
        case 4:
          arr = this.$refs.address4.getCheckedNodes()
          break;
        case 5:
          arr = this.$refs.address5.getCheckedNodes()
          break;
      }

      for (var i in arr) {
        switch (index) {
          case 1:
            this.addressValue1=arr[i].pathLabels.join('-')
            break;
          case 2:
            this.addressValue2=arr[i].pathLabels.join('-')
            break;
          case 3:
            this.addressValue3=arr[i].pathLabels.join('-')
            break;
          case 4:
            this.addressValue4=arr[i].pathLabels.join('-')
            break;
          case 5:
            this.addressValue5=arr[i].pathLabels.join('-')
            break;
        }
      }

      this.regionData=arr;

      // const params = { pageNum: this.pageIndex, pageSize: this.pageSize, year: this.queryParams.year,type:3 }
      // let provinceCode = [],cityCode = [],countyCode = [];
      // let code=[];
      // for (var i in arr) {
      //   code=arr[i].path
        // if (arr[i].parent) {
        //   if (!arr[i].parent.checked) {
        //     arr[i].hasChildren && cityCode.push(arr[i].value);
        //     !arr[i].hasChildren && countyCode.push(arr[i].value);
        //   }
        // } else {
        //   provinceCode.push(arr[i].value)
        // }
      // }
      // if(provinceCode.length > 0){
      //   params.provinceIds=provinceCode
      // }
      // if(cityCode.length > 0){
      //   params.cityIds=cityCode
      // }
      // if(countyCode.length > 0){
      //   params.areaIds=countyCode
      // }
      // if(code.length >= 1){
      //   params.provinceId=code[0]
      // }
      // if(code.length >= 2){
      //   params.cityId=code[1]
      // }
      // if(code.length >= 3){
      //   params.areaId=code[2]
      // }

      // this.getData(params)

    },
    handleDelete(index){
      switch (index) {
        case 1:
          this.addressValue1='';
          this.value1='';
          this.value1Flag=false
          break;
        case 2:
          this.addressValue2='';
          this.value2='';
          this.value2Flag=false
          break;
        case 3:
          this.addressValue3='';
          this.value3='';
          this.value3Flag=false
          break;
        case 4:
          this.addressValue4='';
          this.value4='';
          this.value4Flag=false
          break;
        case 5:
          this.addressValue5='';
          this.value5='';
          this.value5Flag=false
          break;
      }
      this.tableData.splice(index-1,1,{})
      this.compareList.splice(index-1,1,{})
      this.$forceUpdate();
    },
    handleSelect(val){
      console.log(val)
      let list=[];
      for (let i=0; i<this.compareList.length; i++){
        if(this.compareList[i].provinceId){
          list.push(this.compareList[i])
        }
      }
      const params = {}
      params.compareList=list;
      this.getData(params)
    },
    formatStatus: function(row, column, cellValue) {
      if(row.title === '经济'||row.title === '财政'||row.title === '债务'){
        return cellValue
      }else {
        // return cellValue? cellValue : '-'
        return cellValue
      }
    },
    rowStyle(row){
      if (row.row.title === '经济'||row.row.title === '财政'||row.row.title === '债务'){
        return {
          // background: '#FAF5EB',
          color:'#232323',
          fontWeight: 'bold'
        }
      }
    },
    handleMessage(){
      this.$message({
        message: '功能正在开发中',
        type: 'warning'
      });
    }
  }
}
</script>

<style lang="scss" scoped>
  .regionalEconomy{
    width: 100%;
    background: #ffffff;
    padding: 16px 24px 16px 16px;
    margin-top: 12px;
    border-radius: 4px;
    .el-form{
      /*margin-left: 20px;*/
      .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;
          }
        }
      }
    }
    .table-item{
      margin-top: 16px;
      position: relative;
      ::v-deep .el-table{
        .el-table__body{
          width: 100% !important;
          /*.el-table__row:first-child{*/
            /*.el-table__cell{*/
              /*font-weight: bold;*/
              /*color: #232323;*/
            /*}*/
          /*}*/
        }
        th{
          font-size: 12px !important;
          font-weight: 400 !important;
        }
        .el-table__fixed-header-wrapper th{
          background: #F0F3FA;
        }
        td.el-table__cell{
          border-bottom: 0;
        }
        .caret-wrapper{
          width: 10px;
        }
      }
      .table-title{
        /*width: 100%;*/
        display: flex;
        /*justify-content:space-around;*/
        border: 1px solid #E6EAF1;
        border-bottom: 0;
        .span-tit{
          display: inline-block;
          width: 16.7%;
          height: 50px;
          background: #F0F3FA;
          color: rgba(35,35,35,0.8);
          font-size: 12px;
          line-height: 50px;
          padding:0 12px;
          border-right: 1px solid #E6EAF1;
          .address{
            color: rgba(35,35,35,0.8);
            i{
              float: right;
              color:#606163;
              font-size: 15px;
              line-height: 50px;
              cursor: pointer;
            }
          }
          ::v-deep .el-cascader{
            width: 120px;
          }
        }
        .title:last-child{
          border-right:0;
        }
      }
    }
    .fixed{
      position: fixed;
      z-index: 999;
      top: 56px;
    }
  }
</style>
