<template>
  <div id="space-statistics-result"  class="map-tool-model">
    <common-map-tool-title @close="close" title="统计结果"/>
    <div class="main-content p20">
      <el-table v-if="tableData.length >0"
          @row-click="gotoSingleItem"
          :data="tableData"
          :height="280"
          :summary-method="getSummaries"
          show-summary
          style="width: 100%">
        <el-table-column   label="序号" align="center">
          <template slot-scope="scop">
            {{scop.$index+1}}
          </template>
        </el-table-column>
        <el-table-column
            v-for="(item,index) in coloumList" :key="index"
            show-overflow-tooltip
            :render-header="renderHeader"
            :prop="item.prop"
            :label="item.label">
        </el-table-column>
      </el-table>
    </div>
    <div class="bottom-btn">
      <div class="btn single_button" @click="outputExcel">

        <download-excel class="blueBtn"
                        :data="tableData"
                        :fields="json_fields"
                        worksheet="My Worksheet"
                        name="分析结果"
        >
          导出Excel<i class="el-icon-download el-icon--right"></i>
        </download-excel>
      </div>
      <div class="btn single_button" @click="close">关闭</div>
    </div>
  </div>
</template>

<script>
import CommonMapToolTitle from "@/components/common/CommonMapToolTitle";
import {addDataPoint, changePosition, setFieldQuerySearch} from "@/units/map/AddLayer";
import {createNamespacedHelpers} from "vuex";
const {mapState} = createNamespacedHelpers('platform')
export default {
  name: "SpaceStatisticsResult",
  components:{
    CommonMapToolTitle
  },
  computed: {
    ...mapState({
      currentReturnResult: 'currentReturnResult',
      spaceStatisticsField:'spaceStatisticsField'
    }),
  },
  data(){
    return{
      tableData:[],
      coloumList:[],
      json_fields:{

      },
    }
  },
  methods:{
    gotoSingleItem(val){
      debugger
      if(this.spaceStatisticsField.layerType=='dynamic'){
        let position = [
          {
            "mapx": val["MAPX"],
            "mapy": val["MAPY"],
          },
        ]
        changePosition(position,false,true)
      }else{
        setFieldQuerySearch('whiteMold','OBJECTID='+val.OBJECTID);
      }
    },
    getSummaries(param) {
      debugger
      const { columns, data } = param;
      const sums = [];
      let tempField = this.spaceStatisticsField.statisticsField;
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '统计';
          return;
        }
        let instatistic = false;
        let instatisticType = '';
        for (let i = 0; i < tempField.length; i++) {
          if (column.property == tempField[i].field) {
            instatistic = true;
            instatisticType = tempField[i].statisticsType
            break;
          }
        }
        if(instatistic){
          if(instatisticType =='sum'){
            const values = data.map(item => Number(item[column.property]));
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0);
            } else {
              sums[index] = '--';
            }
          }else if(instatisticType =='count'){
            sums[index] = this.tableData.length;
          }else if(instatisticType =='avg'){
            const values = data.map(item => Number(item[column.property]));
            if (!values.every(value => isNaN(value))) {
              sums[index] = ((values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0))/(this.tableData.length + 1)).toFixed(2);
            } else {
              sums[index] = '--';
            }
          }else if(instatisticType =='max'){
            const values = data.map(item => Number(item[column.property]));
            if (!values.every(value => isNaN(value))) {
              let max = values[0]
              for(let i=0;i<values.length;i++){
                if(values[i] >= max){
                  max = values[i]
                }
              }
              sums[index] = max;
            } else {
              sums[index] = '--';
            }
          }else if(instatisticType =='min'){

            const values = data.map(item => Number(item[column.property]));
            if (!values.every(value => isNaN(value))) {
              let max = values[0]
              for(let i=0;i<values.length;i++){
                if(values[i] <= max){
                  max = values[i]
                }
              }
              sums[index] = max;
            } else {
              sums[index] = '--';
            }
          }
        }else{
          sums[index] = '--';
        }


      })

      return sums;
    },

    getColoumAndData(val){
      debugger
      this.$emit('setLoading',false);
      this.coloumList = [];
      this.tableData = [];
      let mapPositionData = [];

      console.log(this.spaceStatisticsField)
      debugger
      if(val.length > 0){
        this.json_fields = {};
        for(let key in this.spaceStatisticsField.finalField){
          let temp = {
            prop:this.spaceStatisticsField.finalField[key],
            label:this.spaceStatisticsField.finalField[key],
          }
          this.coloumList.push(temp)
          this.json_fields[this.spaceStatisticsField.finalField[key]] = this.spaceStatisticsField.finalField[key];
        }
        this.tableData = val;
      }
      // let statisData = [];
      // for(let i=0;i<this.spaceStatisticsField.statisticsField.length;i++){
      //   if(this.spaceStatisticsField.statisticsField[i].statisticsType == 'count'){
      //     let temp = {
      //       field:this.spaceStatisticsField.statisticsField[i].field,
      //       name:"总数",
      //       value:val.length
      //     }
      //   }else if(this.spaceStatisticsField.statisticsField[i].statisticsType == 'sum'){
      //     let sum = 0;
      //     for(let i=0;i<val.length;i++){
      //
      //     }
      //     let temp = {
      //       field:this.spaceStatisticsField.statisticsField[i].field,
      //       name:"求和",
      //       value:val.length
      //     }
      //   }else if(this.spaceStatisticsField.statisticsField[i].statisticsType == 'avg'){
      //     let temp = {
      //       field:this.spaceStatisticsField.statisticsField[i].field,
      //       name:"平均数",
      //       value:val.length
      //     }
      //   }else if(this.spaceStatisticsField.statisticsField[i].statisticsType == 'min'){
      //     let temp = {
      //       field:this.spaceStatisticsField.statisticsField[i].field,
      //       name:"最小值",
      //       value:val.length
      //     }
      //   }else if(this.spaceStatisticsField.statisticsField[i].statisticsType == 'max'){
      //     let temp = {
      //       field:this.spaceStatisticsField.statisticsField[i].field,
      //       name:"最大值",
      //       value:val.length
      //     }
      //   }
      // }

      console.log(this.coordinateResultHeader)
      debugger
      for(let i=0;i<val.length;i++){
        let temp = {
          mapx:val[i]["MAPX"],
          mapy:val[i]["MAPY"],
        }
        mapPositionData.push(temp);
      }
      addDataPoint(false,mapPositionData)
      console.log(val)
    },
    // 表头部重新渲染
    renderHeader(h, { column, $index }) {
      // 新建一个 span
      let span = document.createElement('span');
      // 设置表头名称
      span.innerText = column.label;
      // 临时插入 document
      document.body.appendChild(span);
      // 重点：获取 span 最小宽度，设置当前列，注意这里加了 20，字段较多时还是有挤压，且渲染后的 div 内左右 padding 都是 10，所以 +20 。（可能还有边距/边框等值，需要根据实际情况加上）
      column.minWidth = span.getBoundingClientRect().width + 20;
      // 移除 document 中临时的 span
      document.body.removeChild(span);
      return h('span', column.label);
    },
    outputExcel(){

    },
    close(){
      this.$emit('setToolDetailType','');
    },
  },
  watch:{
    currentReturnResult:{
      deep:true,
      handler(val){
        debugger
        if(val !==''){
          this.getColoumAndData(val.attributes)
        }
      }
    },
  }

}
</script>

<style scoped lang="scss">
::v-deep{
  .el-table__footer-wrapper td.el-table__cell{
    border-top: 1px solid rgba(0, 170, 255, 0.8) !important;
  }
  .el-table__footer-wrapper tbody td.el-table__cell, .el-table__header-wrapper tbody td.el-table__cell{
    background-color: transparent !important;
    color: #fff !important;
  }
  .el-tabs__item{
    color: #fff;
  }
  .el-tabs__item.is-active {
    color: #409EFF !important;
  }
  .el-tabs--card>.el-tabs__header{
    border-bottom: 1px solid rgba(0, 170, 255, 0.8);
  }
  .el-tabs--card>.el-tabs__header .el-tabs__item.is-active{
    border-bottom: 1px solid rgba(0, 170, 255, 0.8);
  }
  .el-tabs--card>.el-tabs__header .el-tabs__nav{
    border:1px solid rgba(0, 170, 255, 0.8);
  }
  .el-tabs--card>.el-tabs__header .el-tabs__item{
    border-left:1px solid rgba(0, 170, 255, 0.8);
  }
  .el-table, .el-table__expanded-cell{
    background-color: transparent;
  }
  .el-table th.el-table__cell{
    background-color: transparent;
  }
  .el-table tr{
    background-color: transparent;
  }
  .el-table td.el-table__cell, .el-table th.el-table__cell.is-leaf{
    border-bottom: 1px solid rgba(0, 170, 255, 0.8);
  }
  .el-table thead{
    color: #fff;
  }
  .el-table{
    color: #fff;
  }
  .el-table--border::after, .el-table--group::after, .el-table::before{
    background-color: transparent;
  }
  .el-table tbody tr:hover>td {
    background: rgba(0, 204, 255, 0.7) !important
  }
}
#space-statistics-result{
  position: absolute;
  z-index: 1;
  width: 650px;
  top: 150px;
  left: 540px;
  .bottom-btn{
    display: flex;
    justify-content: right;
    .single_button{
      margin: 0px 10px;
    }
  }
  ::-webkit-scrollbar{
    width: 8px;
    height: 8px;
  }
  ::-webkit-scrollbar-thumb{
    background-color: #028aab;
    border-radius: 3px;
  }
}

</style>
