<template>
  <div class="qgjjdq">
    <div class="content">
      <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  same-select-com" placeholder="请选择" :class="[`select-adaptive-${inputID1}`]" @change="handleSearch" :popper-append-to-body='false'>
                <el-option v-for="(item, index) in yearOptions" :key="index" :label="item.year" :value="item.year" />
              </el-select>
            </el-form-item>
            <el-form-item prop="area">
              <el-cascader
                ref="address"
                :class="[`select-adaptive-${inputID2}`]"
                :options="addressList"
                :props="props"
                v-model="queryParams.address"
                @change="iptAdaptive(inputID2,true)"
                placeholder="地区选择"
                collapse-tags
                clearable></el-cascader>
            </el-form-item>
          </el-form>
        </div>
        <div class="flex-box query-ability">
          <router-link to="/macro/economies?activeName=four" tag="a" class="a-link"><span class="flex-box"><img src="@/assets/images/ability_vs.png">地区经济对比</span></router-link>
          <!--<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="table-item">
        <el-table
          class="fixed-table"
          :data="tableData"
          element-loading-text="Loading"
          @sort-change="sortChange"
          v-horizontal-scroll="'hover'"
          border
          highlight-current-row
          v-if="tableDataTotal > 0 && !isSkeleton"
          :default-sort = "{prop: 'gdp', order: 'descending'}"
        >
          <el-table-column label="序号" width="60" align="left" fixed>
            <template slot-scope="scope">{{ pageIndex * pageSize - pageSize + scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column label="地区" width="150" align="left" fixed>
            <template slot-scope="scope">
              <span @click="clickTo(scope.row,1)" style="cursor: pointer;" class="a-link" v-if="scope.row.province === '北京市' || scope.row.province === '上海市' || scope.row.province === '重庆市' || scope.row.province === '天津市'">
                {{ scope.row.province}}{{scope.row.area ? '-': ''}}{{ scope.row.area ? scope.row.city :''}}{{scope.row.area ? '-': ''}}{{ scope.row.area}}
              </span>
              <span @click="clickTo(scope.row,2)" style="cursor: pointer;" class="a-link" v-else>
                {{ scope.row.province}}{{scope.row.city ? '-': ''}}{{ scope.row.city}}{{scope.row.area ? '-': ''}}{{ scope.row.area}}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="年度明细" prop="id" width="90" align="center" fixed>
            <template slot-scope="scope">
              <img src="@/assets/images/icon_detailed.png" class="icon-detailed" @click="handleDetail(scope.row)">
            </template>
          </el-table-column>
          <el-table-column label="GDP（亿元）" prop="gdp" :formatter="formatStatus" sortable="custom" width="120" align="right"></el-table-column>
          <el-table-column label="GDP增速（%）" prop="gdpGrowth" :formatter="formatStatus" sortable="custom" width="130" align="right"></el-table-column>
          <el-table-column label="人均GDP（元）" prop="gdpPerCapita" :formatter="formatStatus" sortable="custom" width="130" align="right"></el-table-column>
          <el-table-column label="人口（万人）" prop="population" :formatter="formatStatus" sortable="custom" width="120" align="right"></el-table-column>
          <el-table-column label="一般公共预算收入（亿元）" prop="gbr" sortable="custom" :formatter="formatStatus" width="205" align="right"></el-table-column>
          <el-table-column label="一般公共预算收入增速（%）" prop="gbrGrowth" :formatter="formatStatus" sortable="custom" width="205" align="right"></el-table-column>
          <el-table-column label="一般公共预算收入：税收收入（亿元）" prop="taxIncome" :formatter="formatStatus" sortable="custom" width="260" align="right"></el-table-column>
          <el-table-column label="一般公共预算支出（亿元）" prop="gbe" :formatter="formatStatus" sortable="custom" width="195" align="right"></el-table-column>
          <el-table-column label="政府性基金收入（亿元）" width="180" prop="govFundIncome" :formatter="formatStatus" sortable="custom" align="right"></el-table-column>
          <el-table-column label="政府性基金收入：土地出让收入（亿元）" prop="landTransferIncome" sortable="custom" :formatter="formatStatus" width="275" align="right"></el-table-column>
          <el-table-column label="政府性基金支出（亿元）" prop="govFundExpenditure" :formatter="formatStatus" width="180" sortable="custom" align="right"></el-table-column>
          <el-table-column label="国有资本经营收入（亿元）" prop="soecoi" width="190" :formatter="formatStatus" align="right"></el-table-column>
          <el-table-column label="国有资本经营支出（亿元）" prop="soecoe" width="190" :formatter="formatStatus" align="right"></el-table-column>
          <el-table-column label="固定资产投资（亿元）" prop="fixedInvestment" :formatter="formatStatus" width="190" align="right"></el-table-column>
          <el-table-column label="财政自给率（%）" prop="fiscalSelfSufficiencyRate" :formatter="formatStatus" width="160" align="right"></el-table-column>
          <el-table-column label="地方政府债务余额（亿元）" prop="govDebtBalance" :formatter="formatStatus" width="190" align="right"></el-table-column>
          <el-table-column label="一般债余额（亿元）" prop="generalDebtBalance" :formatter="formatStatus" width="160" align="right"></el-table-column>
          <el-table-column label="专项债余额（亿元）" prop="specialDebtBalance" :formatter="formatStatus" width="180" align="right"></el-table-column>
          <el-table-column label="地方政府债务限额（亿元）" prop="govDebtLimit" :formatter="formatStatus" width="190" align="right"></el-table-column>
          <el-table-column label="城投平台有息债务（亿元）" prop="uipInterestBearingDebt" :formatter="formatStatus" width="200" align="right" >
            <template slot="header" slot-scope="scope">
            <span>城投平台有息债务（亿元）
              <el-tooltip popper-class="tips" effect="light" content="城投平台有息债务是该地区行政区划下所有的城投公司的短期债务与长期债务合计。其中，短期债务=短期借款+一年内到期的非流动负债+应付短期债券，长期债务=长期借款+应付长期债券。" placement="top">
                <i class="el-icon-warning-outline"></i>
              </el-tooltip>
            </span>
            </template>
          </el-table-column>
          <el-table-column label="负债率（%）" prop="govDebtToGdpRate" :formatter="formatStatus" width="160" align="right"></el-table-column>
          <el-table-column label="负债率（宽口径）（%）" prop="govDebtToGdpRateWild" :formatter="formatStatus" width="180" align="right"></el-table-column>
          <el-table-column label="债务率（%）" prop="govDebtRate" :formatter="formatStatus" width="160" align="right"></el-table-column>
          <el-table-column label="债务率（宽口径）（%）" prop="govDebtRateWild" :formatter="formatStatus" width="180" align="right"></el-table-column>
          <!--<el-table-column label="金融机构存款余额（本外币）（亿元）" prop="cgfs" width="160" align="left" />-->
          <!--<el-table-column label="金融机构贷款余额（本外币）（亿元）" prop="cgfs" width="160" align="left" />-->
          <el-table-column label="第一产业增加值（亿元）" prop="piAddValue" :formatter="formatStatus" width="180" align="right"></el-table-column>
          <el-table-column label="第二产业增加值（亿元）" prop="siAddValue" :formatter="formatStatus" width="180" align="right"></el-table-column>
          <el-table-column label="第三产业增加值（亿元）" prop="tiAddValue" :formatter="formatStatus" width="180" align="right"></el-table-column>
          <el-table-column label="工业增加值（亿元）" prop="industryAddValue" :formatter="formatStatus" width="160" align="right"></el-table-column>
          <el-table-column label="工业总产值（亿元）" prop="industryTotalValue" :formatter="formatStatus" width="160" align="right"></el-table-column>
          <el-table-column label="进出口总额（亿美元）" prop="eximTotalValue" :formatter="formatStatus" width="160" align="right"></el-table-column>
          <el-table-column label="社会消费品零售总额（亿元）" prop="trscg" :formatter="formatStatus" width="200" align="right"></el-table-column>
          <el-table-column label="城镇居民人均可支配收入（元）" prop="urbanPcdi" :formatter="formatStatus" width="210" align="right"></el-table-column>
        </el-table>
        <div class="empty" v-if="tableDataTotal === 0 && !isSkeleton">
          <img class="img" src="@/assets/images/project/empty.png">
          <div class="p1">抱歉，没找到相关数据</div>
          <div class="p2">建议调整关键词或筛选条件，重新搜索</div>
        </div>
      </div>
      <!--<template slot-scope="scope">-->
        <!--<router-link to="/purchaserDetail" target="_blank" tag="a" class="a-link">{{ scope.row.zbwj }}</router-link>-->
      <!--</template>-->
      <div class="pagination-box" v-if="show_page && tableDataTotal>pageSize">
        <el-pagination background :current-page="pageIndex" :page-size="pageSize" :total="tableDataTotal" layout="prev, pager, next, jumper" @current-change="handleCurrentChange" @size-change="handleSizeChange" />
      </div>
      <economies-detail ref="economiesDetail" />
    </div>
  </div>
</template>

<script>
  import { nationalPage,getYears } from '@/api/macro/macro'
  import dataRegion from '@/assets/json/dataRegion'
  import economiesDetail from './economies-detail'
  import skeleton from '../../component/skeleton'
  import { v4 } from "uuid";
  export default {
    name: 'NationalEconomies',
    components: {
      economiesDetail,skeleton
    },
    data() {
      return {
        queryParams: {
          year:'',
          address: ''
        },
        yearOptions: [],
        props: {
          value: 'id',
          multiple: true,
          expandTrigger: 'hover'
        },
        addressList: [],
        tableData: [],
        tableLoading: false,
        pageIndex: 1,
        pageSize: 50,
        tableDataTotal: null,
        show_page:true,
        MaxPage:500,
        isSkeleton:true,
        inputID1:this.getUid(),
        inputID2:this.getUid()
      }
    },
    created() {
      this.dataRegion()
      this.getYears()
    },
    mounted() {

    },
    beforeDestroy() {

    },
    methods: {
      getYears(){
        getYears({}).then(res => {
          this.yearOptions=res.data.reverse();
          this.queryParams.year=this.yearOptions[0].year;
          this.querySubmit()
        })
      },
      //地区
      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;
      },
      // 查询提交
      async querySubmit() {
        // this.isSkeleton = true
        const params = { pageNum: this.pageIndex, pageSize: this.pageSize, year: this.queryParams.year,type:1 }
        if(this.queryParams.address){
          let arr = this.$refs.address.getCheckedNodes();
          let provinceCode = [],cityCode = [],countyCode = [];
          for (var i in arr) {
            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
          }
        }else {
          if(params.provinceIds){
            delete params.provinceIds
          }
          if(params.cityIds){
            delete params.cityIds
          }
          if(params.areaIds){
            delete params.areaIds
          }

        }

        if(this.queryParams.field){
          params.field=this.queryParams.field
        }
        if(this.queryParams.order){
          params.order=this.queryParams.order
        }

        nationalPage(params).then(res => {
          this.isSkeleton = false
          this.tableData = res.data.list;
          this.tableDataTotal = res.data.totalCount
        })
        // 延迟关闭加载效果
        // setTimeout(() => {
        //   this.tableLoading = false
        // }, 200)
      },
      // 明细
      handleDetail(row) {
        this.$refs.economiesDetail.open(row)
      },
      // 重置页数
      handleSizeChange(val) {
        this.pageIndex = 1
        this.pageSize = val
        this.querySubmit()
      },
      // 跳转指定页数
      handleCurrentChange(val) {
        if(this.MaxPage<val){
          this.show_page = false
          this.$nextTick(() => {
            this.pageIndex = 1
            this.$message.warning(`对不起，最多只能访问${this.MaxPage}页`)
            this.show_page = true
          })
        }else {
          this.pageIndex = val
          this.querySubmit();
          this.scrollToTop();
        }
      },
      scrollToTop() {
        window.scrollTo(0, 0);
      },
      formatStatus: function(row, column, cellValue) {
        return cellValue? cellValue : '-'
      },
      sortChange({ column, prop, order }){
        this.queryParams.field = prop
        if(column.order === "ascending"){
          this.queryParams.order = 'asc'
        }else if(column.order === "descending"){
          this.queryParams.order = 'desc'
        }else {
          this.queryParams.order=''
          this.queryParams.field=''
        }
        this.pageIndex = 1;
        this.querySubmit()
      },
      handleSearch(){
        this.$nextTick(() => {
          this.pageIndex = 1
          this.querySubmit()
        })
      },
      handleMessage(){
        this.$message({
          message: '功能正在开发中',
          type: 'warning'
        });
      },
      clickTo(item,key){
        let params={
          province:item.area ? item.area : item.city ? item.city : item.province,
        };
        if(item.areaId){
          params.provinceId=item.provinceId
          params.cityId=item.cityId
          params.areaId=item.areaId
        }else if(item.cityId !=0 && key === 2){
          params.provinceId=item.provinceId
          params.cityId=item.cityId
        }else {
          params.provinceId=item.provinceId
        }
        this.$router.push({
          path: '/macro/economies',
          query:params
        })
      },
      iptAdaptive(uid, multiple = false) {
        multiple ? this.multipleAdaptiveHandle(uid) : this.iptAdaptiveHandle(uid);
      },
      getUid() {
        return v4();
      },
      // 多选处理
      async multipleAdaptiveHandle(uid) {
        try {
          await this.$nextTick();
          const dom = document.querySelector(`.select-adaptive-${uid}`);
          const iptChild = dom.querySelector(".el-input__inner");
          if (dom) {
            const textContainer = document.createElement("span");
            const textName = `text-${uid}`;
            textContainer.classList.add(textName);
            const selectChildren = dom.querySelectorAll(".el-tag");
            if (selectChildren.length) {
              let width = 0;
              selectChildren.forEach(item => {
                const text = item.textContent;
                const itemInfo = window.getComputedStyle(item);
                textContainer.style.setProperty("visibility", "hidden");
                textContainer.style.setProperty("display", "inline-block");
                textContainer.style.setProperty("font-size", "14px");
                textContainer.style.setProperty("padding", itemInfo.padding);
                textContainer.style.setProperty("box-sizing", "border-box");
                textContainer.textContent = text;
                document.body.append(textContainer);
                width += textContainer.offsetWidth + parseInt(itemInfo.marginLeft) + parseInt(itemInfo.marginRight);
                textContainer.remove();
              });
              dom.style.setProperty("width", `${width + 20}px`);
              this.handleSearch();
              return;
            }
            textContainer.style.setProperty("visibility", "hidden");
            textContainer.style.setProperty("display", "inline-block");
            textContainer.style.setProperty("font-size", "14px");
            textContainer.style.setProperty("padding", "0px 8px");
            textContainer.style.setProperty("box-sizing", "border-box");
            textContainer.textContent = iptChild.getAttribute("placeholder");
            document.body.append(textContainer);
            // let containerWidth = textContainer.offsetWidth + 12 + 8;
            let containerWidth = 150;
            textContainer.remove();
            dom.style.setProperty("width", `${containerWidth}px`);
            this.handleSearch();
          }

        } catch (error) {
          console.log(error);
        }
      },
      // 单选处理
      async iptAdaptiveHandle(uid) {
        try {
          await this.$nextTick();
          const dom = document.querySelector(`.select-adaptive-${uid}`);
          const realStyles = window.getComputedStyle(dom);
          if (dom) {
            const iptChild = dom.querySelector(".el-input__inner");
            const textContainer = document.createElement("span");
            const textName = `text-${uid}`;
            textContainer.classList.add(textName);
            textContainer.style.setProperty("visibility", "hidden");
            textContainer.style.setProperty("display", "inline-block");
            textContainer.style.setProperty("font-size", "14px");
            const hasPadding = (parseInt(realStyles.paddingLeft) || parseInt(realStyles.paddingRight)) ? true : false;
            hasPadding ? textContainer.style.setProperty("padding", "0px 8px") : null;
            textContainer.style.setProperty("box-sizing", "border-box");
            textContainer.textContent = iptChild.value ? iptChild.value : iptChild.getAttribute("placeholder");
            document.body.append(textContainer);
            let containerWidth = textContainer.offsetWidth + 12 + 8;
            textContainer.remove();
            dom.style.setProperty("width", `${containerWidth}px`);
          }
          this.handleSearch();
        } catch (error) {

        }
      },
    }
  }
</script>

<style lang="scss" scoped>

  .qgjjdq{
    @import "@/assets/styles/search-common.scss";
    .query-box{
      margin: -8px 0 8px 0;
      .a-link:hover{
        text-decoration:none;
      }
      .query-params{
        .el-form{
          /*margin-left: 24px;*/
        }
        ::v-deep .el-form{
          .el-form-item--small.el-form-item{
            margin-top: 0;
            margin-bottom: 0;
          }
          .el-form-item{
            height: 32px;
          }
          .el-form-item__content{
            line-height: 32px;
          }
          .el-input{
            line-height: 32px;
            .el-input__inner{
              height: 32px;
              line-height: 32px;
              border-radius: 4px;
              border: 0;
            }
          }
          .is-focus{
            .el-input__inner{
              background: #F4F6F9;
            }
          }

        }
        .form-content-width{
          width: 80px;
        }
        ::v-deep .el-cascader{
          width: 106px;
          .el-cascader__tags{
            flex-wrap: inherit;
            .el-tag{
              /*max-width: 130px;*/
            }
          }
        }
      }
    }
    ::v-deep .el-select-dropdown{
      left: 0 !important;
      .el-select-dropdown__item.hover{
        color: #0081FF;
      }
    }
    .content{
      background: #ffffff;
      padding: 16px 16px 0;
      margin-top: 12px;
      /*height: calc(100vh - 300px);*/
      .table-item{
        /*position: relative;*/
        .empty{
          margin: 0 auto;
          height: 600px;
          text-align: center;
          border-top: 1px solid #EFEFEF;
          .img{
            width: 108px;
            height: 108px;
            margin-bottom: 24px;
            margin-top: 150px;
          }
          .p1{
            color: #333333;
            font-size: 16px;
          }
          .p2{
            color: #999999;
            font-size: 14px;
            margin-top: 8px;
          }
        }
        ::v-deep .el-table{
          overflow:visible;
          .el-table__header-wrapper{
            position: sticky;
            top:102px;
            z-index: 9;
          }
          .el-table__fixed-header-wrapper{
            position: sticky;
            z-index: 9;
            top: 102px;
          }
          .el-table__fixed{
            overflow-x: clip;
            overflow-y: clip;
          }
          th{
            font-weight: 400 !important;
          }
          .el-table__fixed-header-wrapper th{
            background: #F0F3FA;
          }
          td.el-table__cell{
            border-bottom: 0;
          }
          .caret-wrapper{
            width: 10px;
          }
        }
        ::v-deep .fixed-table{

        }
      }
    }
  }
</style>
