<template>
  <div id="space-statistics" class="map-tool-model">
    <common-map-tool-title @close="close" title="空间统计"/>
    <div class="main-content p20">
      <div class="single-half-block">
        <div class="half_row">
          <common-num-title class="half-margin" title="选择需要分析的要素图层" :num="1"/>
          <div class="single-row">
            <el-select v-model="form.layerUrl" :popper-append-to-body="false" @change="changeLayer" filterable collapse-tags style="width: 100%" placeholder="请选择">
              <el-option
                  v-for="item in allLayerList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.url">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="half_row">
          <common-num-title class="half-margin"  title="选择统计范围" :num="2"/>
          <div class="single-row">
<!--            <el-radio-group type="kind" v-model="form.type" @change="areaChange">-->
<!--              <el-radio  label="区县">区县</el-radio>-->
<!--              <el-radio  label="环线">环线</el-radio>-->
<!--            </el-radio-group>-->
<!--            <el-select v-model="form.extent":popper-append-to-body="false" filterable collapse-tags style="width: 100%" placeholder="请选择">-->
<!--              <el-option-->
<!--                  v-for="item in areaList"-->
<!--                  :key="item.name"-->
<!--                  :label="item.name"-->
<!--                  :value="item.value">-->
<!--              </el-option>-->
<!--            </el-select>-->


            <el-cascader
                v-model="form.extent"
                :options="extentList"
                :props="{ expandTrigger: 'hover' }"
                ></el-cascader>
          </div>
        </div>
      </div>
      <div class="single-block">
        <div class="single-row" style="display: flex;flex-direction: row">
          <common-num-title   title="筛选数据" style="width: 50%" :num="3"/>
          <div style="width: 45%;display: flex;flex-direction: row;align-items: center;justify-content: flex-end">
            <div v-for="item in typeList" :key="item.id" class="type_icon" :class="[item.chosen?'type_icon_chosen':'']" @click="selectSingleType(item)">
              {{ item.name }}
            </div>
          </div>
        </div>
          <div v-if="form.screenType=='valueField'" class="single-row">

            <el-cascader  v-model="form.filterScreenField" :popper-append-to-body="false"  filterable style="width: 96%;margin-left: 2%"  placeholder=""
                         :options="showField"
                :props="props"
                collapse-tags
                clearable></el-cascader>
          </div>

        <div v-if="form.screenType=='costom'" class="single_content">
          <div class="content_title">
            <span class="single_title1">字段名称</span>
            <span class="single_title2">筛选类型</span>
            <span class="single_title3">筛选值</span>
            <span>操作</span>
          </div>
          <ul>
            <li v-for="item in statisticsScreenList" class="statistics_item" :key="item.id">
              <el-select v-model="item.field" :popper-append-to-body="false" filterable collapse-tags style="width: 30%" placeholder="请选择">
                <el-option
                    v-for="item in showField"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
              <el-select v-model="item.statisticsType" :popper-append-to-body="false" filterable collapse-tags style="width: 20%" placeholder="请选择">
                <el-option
                    v-for="item in statisticsScreenTypeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
              <el-input v-model="item.value" style="width: 42%" />
              <i class="el-icon-delete fly_icon" @click="deleteScreenSingleItem(item)"></i>
            </li>
          </ul>
          <div class="single_add" @click="addScreenSingleItem">
            <span>+</span>
          </div>
        </div>

          <common-num-title  title="展示字段" :num="4"/>
          <div class="single-row">
            <el-select v-model="form.finalField" :popper-append-to-body="false" multiple filterable collapse-tags style="width: 96%;margin-left: 2%" placeholder="请选择">
              <el-option
                  v-for="item in showField"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </div>
      </div>
      <div class="single-block">
        <common-num-title class="half-margin"  title="配置统计的内容" :num="5"/>
        <div class="single_content">
          <div class="content_title">
            <span class="single_title">字段名称</span>
            <span class="single_title">统计方式</span>
            <span>操作</span>
          </div>
          <ul>
            <li v-for="item in statisticsList" class="statistics_item" :key="item.id">
              <el-select v-model="item.field" :popper-append-to-body="false" filterable collapse-tags style="width: 42%" placeholder="请选择">
                <el-option
                    v-for="item in showField"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
              <el-select v-model="item.statisticsType" :popper-append-to-body="false" filterable collapse-tags style="width: 42%" placeholder="请选择">
                <el-option
                    v-for="item in statisticsTypeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
              <i class="el-icon-delete fly_icon" @click="deleteSingleItem(item)"></i>
            </li>
          </ul>
          <div class="single_add" @click="addSingleItem">
            <span>+</span>
          </div>
        </div>
      </div>
<!--      <div class="single-block">-->
<!--        <common-num-title class="half-margin"  title="统计结果" :num="4"/>-->
<!--        <div class="single-row">-->
<!--          <span>{{tempStatisticResult}}</span>-->
<!--        </div>-->
<!--      </div>-->
    </div>
    <div class="bottom-btn">
      <div class="btn single_button" style="margin-right: 60px"  @click="deleteAnalysis()">清除</div>
      <div class="btn single_button" @click="runSpaceStatistics">运行分析</div>
    </div>
  </div>
</template>

<script>
import {nanoid} from "nanoid";
import CommonMapToolTitle from "@/components/common/CommonMapToolTitle";
import CommonNumTitle from "@/components/common/CommonNumTitle";
import {getLayerFieldList, getLayerList} from "@/service/show-platform";
import {clearMapDraw, drawByType, getLayerAllFields, SetStatisticDefinition} from "@/units/map/AddLayer";
import {createNamespacedHelpers} from "vuex";
import {
  CHANGE_CURRENT_RETURN_RESULT_ACTION, CHANGE_RIGHT_TOOL_STATE_ACTION, CHANGE_SPACE_STATISTICS_FIELD_ACTION
} from "@/view/show-platform/store/action-constant";
const {mapState,mapActions} = createNamespacedHelpers('platform')
export default {
  name: "SpaceStatistics",
  computed:{
    ...mapState({
      currentReturnFields:'currentReturnFields',
      currentReturnResult:'currentReturnResult',
      rightToolState:'rightToolState'
    }),
    tempFields(){
      let temp = []
      for(let i=0;i<this.currentReturnFields.length;i++){
        if(this.currentReturnFields[i].type=='esriFieldTypeOID'||this.currentReturnFields[i].type=='esriFieldTypeSmallInteger'){
          temp.push(this.currentReturnFields[i])
        }
      }
      return temp
    },

  },
  components:{
    CommonMapToolTitle,CommonNumTitle
  },
  data(){
    return{
      props: { multiple: true },
      allLayerList:[],
      statisticsList:[
      ],
      statisticsScreenList:[],
      areaList:[],
      qxList:[
        {
          name:'全部',
          value:'1=1'
        },
        {
          name:'青浦区',
          value:"区县名称='青浦区'"
        },
        {
          name:'宝山区',
          value:"区县名称='宝山区'"
        },
        {
          name:'奉贤区',
          value:"区县名称='奉贤区'"
        },
        {
          name:'徐汇区',
          value:"区县名称='徐汇区'"
        },
        {
          name:'普陀区',
          value:"区县名称='普陀区'"
        },
        {
          name:'杨浦区',
          value:"区县名称='杨浦区'"
        },
        {
          name:'松江区',
          value:"区县名称='松江区'"
        },
        {
          name:'虹口区',
          value:"区县名称='虹口区'"
        },
        {
          name:'金山区',
          value:"区县名称='金山区'"
        },
        {
          name:'长宁区',
          value:"区县名称='长宁区'"
        },
        {
          name:'静安区',
          value:"区县名称='静安区'"
        },
        {
          name:'黄浦区',
          value:"区县名称='黄浦区'"
        },
        {
          name:'嘉定区',
          value:"区县名称='嘉定区'"
        },
        {
          name:'闵行区',
          value:"区县名称='闵行区'"
        },
        {
          name:'浦东新区',
          value:"区县名称='浦东新区'"
        },
        {
          name:'崇明区',
          value:"区县名称='崇明区'"
        }
      ],
      hxList:[
        {
          name:'全部',
          value:'1=1'
        },
        {
          name:'内中环间',
          value:"名称='内中环间'"
        },
        {
          name:'中外环间',
          value:"名称='中外环间'"
        },
        {
          name:'外环外',
          value:"名称='外环外'"
        },
        {
          name:'内环',
          value:"名称='内环'"
        },
        {
          name:'外环',
          value:"名称='外环'"
        },
        {
          name:'中环',
          value:"名称='中环'"
        }
      ],
      extentList:[
        {
          value: '区县',
          label: '区县',
          children:[
            {
              label:'全部',
              value:'1=1'
            },
            {
              label:'青浦区',
              value:"区县名称='青浦区'"
            },
            {
              label:'宝山区',
              value:"区县名称='宝山区'"
            },
            {
              label:'奉贤区',
              value:"区县名称='奉贤区'"
            },
            {
              label:'徐汇区',
              value:"区县名称='徐汇区'"
            },
            {
              label:'普陀区',
              value:"区县名称='普陀区'"
            },
            {
              label:'杨浦区',
              value:"区县名称='杨浦区'"
            },
            {
              label:'松江区',
              value:"区县名称='松江区'"
            },
            {
              label:'虹口区',
              value:"区县名称='虹口区'"
            },
            {
              label:'金山区',
              value:"区县名称='金山区'"
            },
            {
              label:'长宁区',
              value:"区县名称='长宁区'"
            },
            {
              label:'静安区',
              value:"区县名称='静安区'"
            },
            {
              label:'黄浦区',
              value:"区县名称='黄浦区'"
            },
            {
              label:'嘉定区',
              value:"区县名称='嘉定区'"
            },
            {
              label:'闵行区',
              value:"区县名称='闵行区'"
            },
            {
              label:'浦东新区',
              value:"区县名称='浦东新区'"
            },
            {
              label:'崇明区',
              value:"区县名称='崇明区'"
            }
          ]
        },
        {
          value: '环线',
          label: '环线',
          children:[
            {
              label:'全部',
              value:'1=1'
            },
            {
              label:'内中环间',
              value:"名称='内中环间'"
            },
            {
              label:'中外环间',
              value:"名称='中外环间'"
            },
            {
              label:'外环外',
              value:"名称='外环外'"
            },
            {
              label:'内环',
              value:"名称='内环'"
            },
            {
              label:'外环',
              value:"名称='外环'"
            },
            {
              label:'中环',
              value:"名称='中环'"
            }
          ]
        },
      ],
      showField:[
        // {
        //   value:'MANAGEMENT',
        //   label:'MANAGEMENT注释',
        //   children:[
        //     { value: '上海市黄浦区建筑建材业安全质量监督站', label: '上海市黄浦区建筑建材业安全质量监督站' },
        //     { value: '上海市闵行区建设工程质量监督站', label: '上海市闵行区建设工程质量监督站' },
        //   ]
        // },
        // {
        //   value:'NAME',
        //   label:'NAME注释',
        //   children:[
        //   ]
        // },
        // {
        //   value:'STATE',
        //   label:'STATE注释',
        //   children:[
        //     { value: '竣工', label: '竣工' },
        //     { value: '在监在建', label: '在监在建' },
        //   ]
        // },
        // {
        //   value:'BUILDTIME',
        //   label:'BUILDTIME注释',
        //   children:[
        //   ]
        // },
        // {
        //   value:'PROJECTNUM',
        //   label:'PROJECTNUM注释',
        //   children:[
        //   ]
        // },
        // {
        //   value:'BUILDUNIT',
        //   label:'BUILDUNIT注释',
        //   children:[
        //   ]
        // },
        // {
        //   value:'UPDATETIME',
        //   label:'UPDATETIME注释',
        //   children:[
        //   ]
        // },
      ],
      typeList:[
        {
          id:'01',
          name:'自定义',
          value:'costom',
          chosen:false
        },
        {
          id:'02',
          name:'值域',
          value:'valueField',
          chosen:false
        },
      ],
      statisticsScreenTypeList:[
        {
          label:'>',
          value:'>',
        },
        {
          label:'<',
          value:'<',
        },
        {
          label:'=',
          value:'=',
        },
      ],
      statisticsTypeList:[
        {
          label:'总数',
          value:'count',
        },
        {
          label:'求和',
          value:'sum',
        },
        {
          label:'平均数',
          value:'avg',
        },
        {
          label:'最小值',
          value:'min',
        },
        {
          label:'最大值',
          value:'max',
        },
      ],
      form:{
        layerUrl:'',
        type:'',
        layerType:'',
        screenType:'',
        extent:'',
        filterScreenField:'',
        filterField:'',
        finalField:''
      },
      tempStatisticResult:''

    }
  },
  mounted(){

    this.typeList[0].chosen = true;
    this.form.screenType = 'costom'
    getLayerList().then(res =>{
      let data = res.msg[0].Rows;
      this.getLayerList(data)
    })
  },
  methods:{
    selectSingleType(item){
      for(let i=0;i<this.typeList.length;i++){
        if(item.id==this.typeList[i].id){
          this.typeList[i].chosen = true;
          this.form.screenType=this.typeList[i].value;
        }else{
          this.typeList[i].chosen = false;
        }
      }
    },
    getStatisticTypeName(type){
      switch (type){
        case 'count':
          return '总数'
          break;
        case 'sum':
          return '求和'
          break;
        case 'avg':
          return '平均数'
          break;
        case 'min':
          return '最小值'
          break;
        case 'max':
          return '最大值'
          break;
      }
    },
    tempResult(){
      let temp = ''
      debugger
      for(let  key in this.currentReturnResult.attributes[0]){
        for(let i=0;i<this.statisticsList.length;i++){
          if(this.statisticsList[i].field== key){
            temp  += key + "的" + this.getStatisticTypeName(this.statisticsList[i].statisticsType) +"值为"+ this.currentReturnResult.attributes[0][key] +";";
          }
        }
      }
      this.tempStatisticResult = temp;
    },
    getLayerList(data){
      let allData = [] //全部的分类无序数据
      let totalData = [] //全部的一级节点数据
      this.allLayerList = [];
      //筛选出指定大类数据
      for(let i=0;i<data.length;i++){
        allData.push(data[i])
      }
      //获取全部一级节点数据
      allData.forEach((item,index)=>{
        let obj = item;
        totalData.push({
          label:obj.SECOND_TYPE,
          id:obj.MAIN_CODE + obj.SECOND_CODE,
          pid:obj.MAIN_TYPE,
          type:"second",
          children: []
        })
      })
      totalData = this.uniqueFunc(totalData,'label');

      //对于全部节点数据进行填充
      for(let j=0;j<totalData.length;j++){
        for(let k=0;k<allData.length;k++){
          if(totalData[j].label ==allData[k].SECOND_TYPE){
            let node = {
              id:allData[k].CODE,
              label:allData[k].TYPE_NAME,
              pid:allData[k].SECOND_CODE,
              type: "layer",
              opacity:100,    //设置默认的透明度
              url: allData[k].ADDRESS,
              layertype: allData[k].TYPE,
              u_code: allData[k].U_CODE,
              u_name: allData[k].U_NAME,
              time: allData[k].TIME,
              main: allData[k].MAIN_TYPE,
            }
            this.allLayerList.push(node)
          }
        }
      }
    },
    uniqueFunc(arr, uniId){
      const res = new Map();
      return arr.filter((item) => !res.has(item[uniId]) && res.set(item[uniId], 1));
    },
    changeLayer(){
      let id='';
      this.form.filterScreenField = '';
      this.form.filterField = '';
      this.form.finalField = '';
      this.statisticsScreenList = [];
      this.statisticsList = [];
      this.form.layerType= '';
      for(let i=0;i<this.allLayerList.length;i++){
        if(this.allLayerList[i].url == this.form.layerUrl){
          debugger;
          console.log(this.allLayerList[i])
          id = this.allLayerList[i].id
        }
      }
      getLayerFieldList(id).then(res =>{
        debugger;
        let data = res.msg[0].Rows;
        let fieldData = []
        for(let i=0;i<data.length;i++){
         let temp = {
           value:data[i].ATTRIBUTE_NAME,
           label:data[i].FIELD_DESCRIPTION,
           type:data[i].FIELD_TYPE,
           children:data[i].children
         }
          fieldData.push(temp)
        }
        this.showField = fieldData;
      })


      //getLayerAllFields(this.form.layerUrl)
    },
    areaChange(){
      if(this.form.type=='区县'){
        this.areaList = this.qxList
      }else{
        this.areaList = this.hxList
      }
    },
    addSingleItem(){
      this.statisticsList.push({
        id:nanoid(),
        field:'',
        statisticsType:''
      })
    },
    deleteSingleItem(item){
      for(let i=0;i<this.statisticsList.length;i++){
        if(item.id ==this.statisticsList[i].id){
          this.statisticsList.splice(i,1)
        }
      }
    },
    addScreenSingleItem(){
      this.statisticsScreenList.push({
        id:nanoid(),
        field:'',
        statisticsType:''
      })
    },
    deleteScreenSingleItem(item){
      for(let i=0;i<this.statisticsScreenList.length;i++){
        if(item.id ==this.statisticsScreenList[i].id){
          this.statisticsScreenList.splice(i,1)
        }
      }
    },
    runSpaceStatistics() {
      console.log(this.form)
      let tempForm =  this.form;
      tempForm.statisticsField = this.statisticsList
      this[CHANGE_SPACE_STATISTICS_FIELD_ACTION](tempForm
      )
      let type = '';
      let extent = '';
      let querySql = '1=1';
      type = this.form.extent[0];
      extent =  this.form.extent[1];
      console.log(this.form.filterField)
      debugger


      let fieldData = [];
      let field = [];
      let allSql;
      if(this.form.screenType =='valueField'){
        for(let i =0;i<this.form.filterField.length;i++){
          if(field.indexOf(this.form.filterField[i][0]) <0){
            field.push(this.form.filterField[i][0]);
            let temp = {
              name:this.form.filterField[i][0],
              sql:[]
            }
            fieldData.push(temp)
          }
        }
        for(let i =0;i<this.form.filterField.length;i++){
          for(let j=0;j<fieldData.length;j++){
            if(this.form.filterField[i][0]==fieldData[j].name){
              fieldData[j].sql.push(this.form.filterField[i][1])
            }
          }
        }
        allSql = '  1=1';
        for(let i=0;i<fieldData.length;i++){
          allSql += " and " + fieldData[i].name + " in ( '" + fieldData[i].sql.join("','") +"')"
        }
      }else{
        allSql= "1=1";
        for(let i=0;i<this.statisticsScreenList.length;i++){
          if(isNaN(Number(this.statisticsScreenList[i].value,10))){
            allSql += " and " + this.statisticsScreenList[i].field + " "+this.statisticsScreenList[i].statisticsType +"'"+this.statisticsScreenList[i].value+"'";
          }else{
            allSql += " and " + this.statisticsScreenList[i].field + " "+this.statisticsScreenList[i].statisticsType +this.statisticsScreenList[i].value;
          }
        }
      }

      this[CHANGE_CURRENT_RETURN_RESULT_ACTION](''
      )
      this.$emit('setLoading',true);
      this.$emit('setToolDetailType','spaceStatisticsResult');
      debugger;
      for(let i=0;i<this.allLayerList.length;i++){
        if(this.allLayerList[i].url == this.form.layerUrl){
          this.form.layerType = this.allLayerList[i].id;
        }
      }
      if(this.form.layerType=='D90030000202108'){ //白膜
        this.form.layerType = 'whiteMold'
      }else{
        this.form.layerType = 'dynamic'
      }
      SetStatisticDefinition(this.form.layerUrl,this.form.layerType,type,extent,allSql)
    },
    deleteAnalysis(){
      clearMapDraw(true,true,true);
      this.$emit('setToolDetailType','');
    },
    close(){
      this[CHANGE_RIGHT_TOOL_STATE_ACTION](!this.rightToolState
      )
      this.$emit('setToolType','');
    },
      ...mapActions({
        [CHANGE_CURRENT_RETURN_RESULT_ACTION]:CHANGE_CURRENT_RETURN_RESULT_ACTION,
        [CHANGE_SPACE_STATISTICS_FIELD_ACTION]:CHANGE_SPACE_STATISTICS_FIELD_ACTION,
        [CHANGE_RIGHT_TOOL_STATE_ACTION]:CHANGE_RIGHT_TOOL_STATE_ACTION

      })
  },
  watch:{
    currentReturnResult:{
      handler(){
        this.tempResult()
      }
    },
  }
}
</script>

<style scoped lang="scss">
::v-deep{
  .el-cascader__search-input {
    height: auto !important;
    background: transparent;
    border:none;
  }
  .el-select__tags{
    white-space: nowrap;
    overflow: hidden;
  }
  .el-select__input{
    background-color: transparent !important;
    border: none !important;
    color: #fff;
  }
  .el-select-dropdown__wrap{
    max-height: 150px;
  }
  .el-scrollbar__wrap{
    overflow-y: scroll;
    height: 100%;
  }
  .el-select-dropdown{
    position: absolute !important;
    left: 0px !important;
    border: 1px solid #00a1ff !important;
    background-color: rgba(0, 31, 112, 0.8) !important;
  }
  .el-select-dropdown__item.hover, .el-select-dropdown__item:hover{
    background-color: rgba(0, 31, 112, 1);
    color: #409EFF;
  }
  .el-select-dropdown.is-multiple .el-select-dropdown__item.selected.hover{
    background-color: rgba(0, 31, 112, 1);
    color: #409EFF;
  }
  .el-select-dropdown.is-multiple .el-select-dropdown__item.selected{
    background-color: rgba(0, 31, 112, 1);
    color: #409EFF;
  }
  .el-tag.el-tag--info .el-tag__close{
    color: #fff;
  }
  .el-select .el-tag__close.el-icon-close{
    color: #409EFF  !important;
    background-color: transparent  !important;
  }
  .el-popper[x-placement^=bottom] .popper__arrow::after{
    border-bottom-color: rgba(0, 31, 112, 1);
  }
  .el-tag.el-tag--info {
    background-color: rgba(0, 31, 112, 0.8);
    border-color: #00a1ff;
    color: #409EFF;
  }
  .el-select-dropdown__item{
    color:#fff
  }
  .el-radio{
    color: #fff;
  }
}
#space-statistics{
  position: absolute;
  z-index: 1;
  width: 510px;
  top: 89px;
  right: 120px;
  .main-content{
    .single-half-block{
      display: flex;
      flex-direction: row;
      justify-content: space-around;
      .half_row{
        width: 45%;
      }
    }
    .single-block{
      display: flex;
      flex-direction: column;
      .half_row{
        width: 45%;
      }
      .single-row{
        padding-bottom: 10px;
        color: #fff;
        .type_icon{
          cursor: pointer;
          padding: 5px 10px;
          margin-left: 20px;
          border-radius: 2px;
          border: 1px solid rgba(0, 170, 255, 0.8);
        }
        .type_icon_chosen{
          background-color: rgba(0, 204, 255, 0.7);
        }
      }
      .single_content{
        .content_title{
          color: #fff;
          display: flex;
          padding: 0px;
          margin:0px 10px 0px 10px;
          justify-content: space-between;
          .single_title{
            display: flex;
            justify-content: center;
            width: 40%;
          }
        }
        >ul{
          list-style-type: none;
          padding: 4px;
          margin:0px 10px 0px 10px;
          height: 140px;
          overflow-y: auto;
          overflow-x: hidden;
          .statistics_item{
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            padding:5px 0px;
            border-bottom: 1px solid #409EFF;
            .fly_icon{
              cursor: pointer;
              color: #fff;
              display: flex;
              align-items: center;
            }
          }

        }
        .single_add{
          cursor: pointer;
          margin:10px 10px 10px 10px;
          height: 40px;
          border: 1px dashed #409EFF;
          display: flex;
          justify-content: center;
          align-items: center;
          span{
            color: #fff;
            font-size: 20px;
          }
        }
      }
    }
  }
  .half-margin{
    margin-bottom: 4px;
  }
  ::-webkit-scrollbar{
    width: 8px;
    height: 8px;
  }
  ::-webkit-scrollbar-thumb{
    background-color: #028aab;
    border-radius: 3px;
  }
}
</style>
