<template>
  <div class="app-container qyzx">
    <Region v-if="province" :province="province" :dataQuery="dataQuery" @addressListbtn="addressListbtn"></Region>
    <div class="content">
      <div class="common-title">专项债项目</div>
      <div class="content-box" v-if="!state">
        <div class="box-left">
          <div id="echarts" style="height: 400px"></div>
        </div>
        <div class="box-right">
          <el-table
            :data="tableData"
            element-loading-text="Loading"
            border
            :summary-method="getSummaries"
            show-summary
            height="400"
            fit
            @sort-change="sortChange"
            highlight-current-row
            :default-sort = "{prop: 'value', order: 'descending'}"
          >
            <el-table-column prop="name" label="项目类型" width="160"/>
            <el-table-column prop="number" label="项目个数" align="right" sortable="custom" width="160" />
            <el-table-column prop="value" label="投资额（亿元）" align="right" sortable="custom" width="160" />
            <el-table-column prop="proportion" label="比例（%）" align="right" width="160" sortable="custom" />
          </el-table>
        </div>
      </div>
      <div class="content-box" v-else>
        <div class="empty">
          <img class="img" src="@/assets/images/project/empty.png">
          <div class="p1">抱歉，暂无专项债项目数据</div>
        </div>
      </div>
    </div>
    <div class="content">
      <div class="common-title flex-box">
        <div class="flex-box">项目明细</div>
        <div class="flex-box query-ability">
          <span class="flex-box">共 {{tableDataTotal}} 条</span>
          <span class="flex-box" @click="handleMessage"><img src="@/assets/images/ability_excel.png">导出EXCEL</span>
        </div>
      </div>
      <div class="table-item">
        <el-table
          v-loading="tableLoading"
          :data="listData"
          element-loading-text="Loading"
          @sort-change="sortChange1"
          border
          fit
          highlight-current-row
          :default-sort = "{prop: 'projectTotalInvestment', order: 'descending'}"
        >
          <el-table-column label="序号" width="55" align="left" fixed>
            <template slot-scope="scope">{{ pageIndex * pageSize - pageSize + scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column prop="projectName" label="项目名称">
            <template slot-scope="scope">
              <router-link :to="'/macro/financing/details/'+ scope.row.id" tag="a" class="a-link">{{ scope.row.projectName}}</router-link>
            </template>
          </el-table-column>
          <el-table-column prop="projectTotalInvestment" label="项目总投资（亿）" :formatter="formatStatus" align="right" sortable="custom" width="165" />
          <el-table-column prop="projectCapital" label="项目资本金（亿）" :formatter="formatStatus" align="right" sortable="custom"  width="160" />
          <el-table-column prop="econData007" label="项目收益倍数（倍）" :formatter="formatStatus" align="right" sortable="custom" width="160" />
          <!--<el-table-column prop="zxz" label="专项债金额（亿）" :formatter="formatStatus" sortable="custom" width="150" />-->
          <el-table-column prop="specialBondCapital" label="专项债用作资本金（亿）" align="right" sortable="custom" :formatter="formatStatus" width="180" />
          <el-table-column prop="projectEntity" :formatter="formatStatus" label="项目主体">
            <!--<template slot-scope="scope">-->
              <!--<router-link :to="'/macro/financing/details/'+ scope.row.projectEntityId" tag="a" class="a-link">{{ scope.row.projectEntity}}</router-link>-->
            <!--</template>-->
          </el-table-column>
        </el-table>
      </div>
      <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>

    </div>
  </div>
</template>

<script>
  import * as echarts from 'echarts';
  import { statistics,projectsPage,location } from '@/api/macro/macro'
  import Region from '../component/region'
export default {
  name: 'Financing',
  components: {
    Region
  },
  data() {
    return {
      queryParams:{},
      tableParams:{},
      tableData:[],
      listData:[],
      tableLoading: false,
      pageIndex: 1,
      pageSize: 10,
      tableDataTotal: 0,
      show_page:true,
      MaxPage:1000,
      dataQuery:{},
      province:'',
      provinceId:[],
      state:false,
    }
  },
  created() {
    location({}).then(res => {
      if(res.data.area){
        this.province=res.data.area
      }else {
        if(res.data.city){
          this.province=res.data.city
        }else {
          this.province=res.data.province
        }
      }
      if(!this.dataQuery.provinceId){
        if(res.data.areaId){
          this.dataQuery.provinceId=[res.data.provinceId,res.data.cityId,res.data.areaId]
          this.provinceId=[res.data.provinceId,res.data.cityId,res.data.areaId]
        }else {
          if(res.data.cityId){
            this.provinceId=[res.data.provinceId,res.data.cityId]
          }else {
            this.provinceId=[res.data.provinceId]
          }
        }
        let arr=[res.data.province]
        this.dataQuery.province=arr;
      }else {
        this.provinceId=this.dataQuery.provinceId
      }
      this.$nextTick(() => {
        this.getData()
        this.getStatistics()
      })
    })
  },
  mounted() {

  },
  methods: {
    getData(){
      this.tableLoading = true
      let params={ pageNum: this.pageIndex, pageSize: this.pageSize}
      if(this.tableParams.field){
        params.field=this.tableParams.field
      }
      if(this.tableParams.order){
        params.order=this.tableParams.order
      }
      if(this.provinceId.length > 0){
        params.provinceId=this.provinceId[0]
      }
      if(this.provinceId.length > 1){
        params.cityId=this.provinceId[1]
      }
      if(this.provinceId.length > 2){
        params.areaId=this.provinceId[2]
      }
      projectsPage(params).then(res => {
        this.tableLoading = false
        this.listData=res.data.list;
        this.tableDataTotal = res.data.totalCount
      })
      // 延迟关闭加载效果
      // setTimeout(() => {
      //   this.tableLoading = false
      // }, 200)
    },
    getStatistics(){
      let params={};
      if(this.provinceId.length > 0){
        params.provinceId=this.provinceId[0]
      }
      if(this.provinceId.length > 1){
        params.cityId=this.provinceId[1]
      }
      if(this.provinceId.length > 2){
        params.areaId=this.provinceId[2]
      }
      if(this.queryParams.field){
        params.field=this.queryParams.field
      }
      if(this.queryParams.order){
        params.order=this.queryParams.order
      }
      statistics(params).then(res => {
        var list=[];
        for(var i=0;i<res.data.length;i++){
          var obj={};
          obj.name=res.data[i].projectType;
          obj.value=res.data[i].totalInvestment;
          obj.number=res.data[i].count;
          // obj.totalInvestment=res.data[i].totalInvestment;
          obj.proportion=res.data[i].proportion;
          list.push(obj)
        }
        this.tableData=list;

        let arr=this.tableData.sort((old,New)=>{
          return  New.value - old.value
        })
        let data=[]
        if(arr.length >= 10){
          for(let i=0; i<10; i++){
            data.push(arr[i])
          }
        }else {
          for(let i=0; i<arr.length; i++){
            data.push(arr[i])
          }
        }
        this.total=this.tableData.length;
        if(this.tableData.length > 0){
          this.state=false;
          this.initChart(data)
        }else {
          this.state=true;
        }
      })
    },
    initChart(data) {
      this.$nextTick(() => {
        let myChart = echarts.init(document.getElementById("echarts"))
        let option ={
          tooltip: {
            trigger: 'item',
            borderWidth:0,
            backgroundColor:"rgba(255, 255, 255, 0.8)",
            formatter: function (params) {
              var result = ''
              result+='<h3 style="color: #232226;padding: 0 0 5px 0;margin: 0;">'+ params.data.name +'</h3>'
              result+='<p style="color: rgba(35,35,35,0.8);padding: 0;margin: 0;">'+ params.data.number +'个</p>'
              result+='<p style="color: rgba(35,35,35,0.8);padding: 0;margin: 0;">'+ params.data.value +'亿元</p>'
              result+='<p style="color: rgba(35,35,35,0.8);padding: 0;margin: 0;">'+ params.data.proportion +'%</p>'
              return result;
            },
            extraCssText:'width:150px!important;',
          },
          legend: {
            type: 'scroll',
            orient: 'horizontal',
            bottom: 0,
            data: data,
            itemHeight:8,
            itemWidth:12,
            pageButtonPosition: 'end',
          },
          color:['#8A82F3', '#93A1FF', '#63B6EA','#42B393','#8ECF95','#FFDC6B','#FFC08D','#FE9C77','#E8649B','#A151F5'],
          series: [
            {
              type: 'pie',
              radius: '55%',
              center: ['50%', '50%'],
              data: data,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        }
        myChart.setOption(option);
      })

    },
    formatStatus: function(row, column, cellValue) {
      return cellValue? cellValue : '-'
    },
    sortChange({ column, prop, order }){
      if(prop === 'number'){
        this.queryParams.field = 'count'
      }else if(prop === 'value'){
        this.queryParams.field = 'totalInvestment '
      }else {
        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=''
      }
      let params={
        field:this.queryParams.field,
        order:this.queryParams.order
      };
      statistics(params).then(res => {
        var list=[];
        for(var i=0;i<res.data.length;i++){
          var obj={};
          obj.name=res.data[i].projectType;
          obj.value=res.data[i].totalInvestment;
          obj.number=res.data[i].count;
          obj.proportion=res.data[i].proportion;
          list.push(obj)
        }
        this.tableData=list;
      })
    },
    getSummaries(param){
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if (index === 3) {
          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;
        }
      });
      return sums;
    },
    // 重置页数
    handleSizeChange(val) {
      this.pageIndex = 1
      this.pageSize = val
      this.getData()
    },
    // 跳转指定页数
    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.getData()
      }
    },
    sortChange1({ column, prop, order }){
      this.tableParams.field = prop;
      if(column.order === "ascending"){
        this.tableParams.order = 'asc'
      }else if(column.order === "descending"){
        this.tableParams.order = 'desc'
      }else {
        this.tableParams.order=''
        this.tableParams.field=''
      }
      this.pageIndex=1;
      this.getData()
    },
    handleMessage(){
      this.$message({
        message: '功能正在开发中',
        type: 'warning'
      });
    },
    addressListbtn(data) {
      this.province=data.province;
      this.provinceId=data.provinceId;
      this.dataQuery.province=data.provinces;
      let params={}
      if(data){
        if(this.provinceId.length > 0){
          params.provinceId=this.provinceId[0]
        }
        if(this.provinceId.length > 1){
          params.cityId=this.provinceId[1]
        }
        if(this.provinceId.length > 2){
          params.areaId=this.provinceId[2]
        }
      }
      location(params).then(res => {
        console.log(res.data)
      })
      this.pageIndex = 1;
      this.getData()
      this.getStatistics()
    },
  }
}
</script>

<style lang="scss" scoped>
  .app-container{
    padding: 0;
  }
  .qyzx{
    .query-ability{
      span{
        font-weight: 400;
        color: #3D3D3D;
        font-size: 12px;
      }
    }
    .content{
      background: #ffffff;
      padding: 16px;
      margin-bottom: 16px;
      border-radius: 4px;
    }
    .common-title{
      justify-content: space-between;
    }
    .content-box{
      height: 422px;
      display: flex;
      justify-content: space-between;
      .box-left{
        width: 50%;
      }
      .empty{
        margin: 0 auto;
        height: 550px;
        text-align: center;
        .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;
        }
      }
      .box-right{
        float: right;
        ::v-deep .el-table{
          .sort-caret.ascending{
            border-bottom-color: rgba(0,129,255,0.5);
          }
          .ascending .sort-caret.ascending{
            border-bottom-color: #0081FF;
          }
          .sort-caret.descending{
            border-top-color: rgba(0,129,255,0.5);
          }
          .descending .sort-caret.descending{
            border-top-color: #0081FF;
          }

          .el-table__header-wrapper{
            background: #F0F3FA;
            th{
              background: #F0F3FA;
              /*text-align: left;*/
            }
          }
          .el-table__footer-wrapper{
            background: #F0F3FA;
          }
          th {
            font-size: 13px !important;
            font-weight: 400 !important;
          }
          .cell {
            padding-right: 12px !important;
            padding-left: 12px !important;
            line-height: 18px;
          }
          .el-table__fixed-header-wrapper{
            th{
              background: #F0F3FA;
            }
          }
          td.el-table__cell{
            border-bottom: 0;
          }
          tr{
            &.current-row>td{
              background-color: initial;
            }
            &:nth-child(2n) {
              background: #F8FBFF;
            }
          }
          .el-table__cell{
            height: 40px;
            padding: 0;
            line-height: 40px;
          }
          .el-table__body tr:hover > td.el-table__cell{
            background: #DCEBFF;
          }
          ::-webkit-scrollbar-track-piece {
            //滚动条凹槽的颜色，还可以设置边框属性
            background-color: #F3F4F5;
            height: 16px;
            padding: 0 4px;
          }
          //滚动条的宽度
          ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
            background-color: #F3F4F5;
            border-radius: 6px;
          }
          //滚动条的滑块
          ::-webkit-scrollbar-thumb {
            border-radius: 8px;
            height: 8px;
            margin: 0 4px;
            background: rgba(98,110,126,0.2);
            border: 4px solid rgba(98,110,126,0.2);;
            &:hover{
              background: #566380;
            }
          }
          .has-gutter{
            tr{
              th:nth-child(4){
                border-right:0;
              }
              td:nth-child(4){
                border-right:0;
              }
            }
          }
          .el-table__cell.gutter{
            background: #F0F3FA;
          }
          .el-table__row{
            td:last-child{
              .cell{
                padding-right: 12px !important;
              }
            }
          }
        }
      }
    }
    .table-item{
      margin-top: 22px;
      ::v-deep .el-table{
        td.el-table__cell{
          border-bottom: 0;
        }
      }
    }
  }
</style>
