<template>
  <div :class='`toolbar toolBar toolBar${splitScreen} unselectable`' id='toolBar' ref='toolbar'>
    <div id='test'></div>
    <ul class='nav nav-pills'>
      <li v-if='isRes' @click="handleTools('resShow')">
        <a>
          <a-tooltip placement='bottom'>
            <template #title>图层</template>
            <img src='../static/layers.png' width='24'>
          </a-tooltip>
          <p v-show='showLabel'> 图层</p>
        </a>
      </li>
      <res-catalog class='resCatalog' v-if='isRes' id='resourceCatalog' v-model='toolShow.resShow'></res-catalog>
      <li v-if='isQuery' @click="handleTools('queryShow')">
        <a>
          <a-tooltip placement='bottom'>
            <template #title>查询</template>
            <img src='../static/query.png' width='24'>
          </a-tooltip>
          <p v-show='showLabel'> 查询</p>
        </a>
      </li>
      <query-tool v-if='isQuery' id='queryTool' ref='queryTool' v-model='toolShow.queryShow'
                  :query-config-url='queryConfigUrl' :query-url='queryUrl'></query-tool>
      <li v-if='isIdentify' @click='handleIdentify'>
        <a>
          <a-tooltip placement='bottom'>
            <template #title>I查询</template>
            <img src='../static/identify.png' width='24'>
          </a-tooltip>
          <p v-show='showLabel'> I查询</p>
        </a>
      </li>
      <query-info ref='detail' v-model='featureInfoShow' title='要素信息'></query-info>
      <li v-if='isAjQuery' @click="handleTools('ajQueryShow')">
        <a>
          <a-tooltip placement='bottom'>
            <template #title>案件查询</template>
            <img src='../static/ajquery.png' width='24'>
          </a-tooltip>
          <p v-show='showLabel'> 案件查询</p>
        </a>
      </li>
      <aj-query-tool v-if='isAjQuery' id='ajQueryTool' ref='ajQueryTool' v-model='toolShow.ajQueryShow'></aj-query-tool>
      <li v-if='isCoords' @click="handleTools('coordsShow')">
        <a>
          <a-tooltip placement='bottom'>
            <template #title>定位</template>
            <img src='../static/locationTool.png' width='24'>
          </a-tooltip>
          <p v-show='showLabel'> 定位</p>
        </a>
      </li>
      <coords-locate v-if='isCoords' v-model='toolShow.coordsShow' id='coordsLocate' ref='coordsLocate'></coords-locate>
      <li v-if='isDrawQuery' @click="handleTools('drawQueryShow')">
        <a>
          <a-tooltip placement='bottom'>
            <template #title>空间查询</template>
            <img src='../static/drawQuery.png' width='24'>
          </a-tooltip>
          <p v-show='showLabel'> 空间查询</p>
        </a>
      </li>
      <draw-query-tool v-if='isDrawQuery' v-model='toolShow.drawQueryShow' id='drawQueryTool'
                       ref='drawQueryTool'></draw-query-tool>
      <li v-if='isEdit' @click="handleTools('editShow')">
        <a>
          <a-tooltip placement='bottom'>
            <template #title>编辑图斑</template>
            <img src='../static/drawPencil.png' width='24'>
          </a-tooltip>
          <p v-show='showLabel'> 编辑图斑</p>
        </a>
      </li>
      <edit-feature v-if='isEdit' v-model='toolShow.editShow' id='editFeature' ref='drawQueryTool'></edit-feature>
      <li v-if='isMeasure' @click="handleTools('measureShow')">
        <a>
          <a-tooltip placement='bottom'>
            <template #title>测量</template>
            <img src='../static/measureTool.png' width='24'>
          </a-tooltip>
          <p v-show='showLabel'> 测量</p>
        </a>
      </li>
      <measurement2-d v-if='isMeasure' ref='measureToll' id='measureTool'
                      v-model='toolShow.measureShow'></measurement2-d>
      <li v-if='isFlightPath' @click="handleTools('flightPathShow')">
        <a>
          <a-tooltip placement='bottom'>
            <template #title>巡查轨迹</template>
            <img src='../static/xuncha.png' width='24'>
          </a-tooltip>
          <p v-show='showLabel'> 巡查轨迹</p>
        </a>
      </li>
      <flight-path v-if='isFlightPath' ref='flightPath' id='flightPath' v-model='toolShow.flightPathShow'></flight-path>
      <li v-if='isViewOnline' @click="handleTools('viewOnlineShow')">
        <a>
          <a-tooltip placement='bottom'>
            <template #title>在线监控</template>
            <img src='../static/online.png' width='24'>
          </a-tooltip>
          <p v-show='showLabel'> 在线监控</p>
        </a>
      </li>
      <view-online v-if='isViewOnline' ref='viewOnline' id='viewOnline' v-model='toolShow.viewOnlineShow'></view-online>
      <li v-if='isDraw' @click='handleDrawTool'>
        <a>
          <a-tooltip placement='bottom'>
            <template #title>标绘</template>
            <img src='../static/drawPencil.png' width='24'>
          </a-tooltip>
          <p v-show='showLabel'> 标绘</p>
        </a>
      </li>
      <li v-if='isPrint' @click='handlePrint'>
        <a>
          <a-tooltip placement='bottom'>
            <template #title>打印</template>
            <img src='../static/print.png' width='24'>
          </a-tooltip>
          <p v-show='showLabel'> 打印</p>
        </a>
      </li>
      <li v-if='isAnalysis' @click="handleTools('analysisShow')">
        <a>
          <a-tooltip placement='bottom'>
            <template #title>分析</template>
            <img src='../static/analysis.png' width='24'>
          </a-tooltip>
          <p v-show='showLabel'> 分析</p>
        </a>
      </li>
      <spatial-analysis v-if='isAnalysis' id='spatialAnalysis' ref='spatialAnalysis'
                        v-model='toolShow.analysisShow'></spatial-analysis>
      <li v-if='isHome' id='homeTool' @click='handleHome'>
        <a>
          <a-tooltip placement='bottom'>
            <template #title>复位</template>
            <img src='../static/home.png' width='24'>
          </a-tooltip>
          <p v-show='showLabel'> 复位</p>
        </a>
      </li>
      <li v-if='isClear' id='clearTool' @click='handleClear'>
        <a>
          <a-tooltip placement='bottom'>
            <template #title>清除</template>
            <img src='../static/clear.png' width='24'>
          </a-tooltip>
          <p v-show='showLabel'> 清除</p>
        </a>
      </li>
      <li v-if='isSplit' id='split-screen' @click='handleSplitScreen'>
        <a>
          <a-tooltip placement='bottom'>
            <template #title>分屏</template>
            <img src='../static/splitScreen.png' width='24'>
          </a-tooltip>
          <p v-show='showLabel'> 分屏</p>
        </a>
      </li>

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

<script>
import Viewpoint from '@arcgis/core/Viewpoint';
import Sketch from '@arcgis/core/widgets/Sketch';
import Print from '@arcgis/core/widgets/Print';
import * as identify from '@arcgis/core/rest/identify';
import IdentifyParameters from '@arcgis/core/rest/support/IdentifyParameters';
import Extent from '@arcgis/core/geometry/Extent';
import Measurement2D from './Measurement2D';
import CoordsLocate from './CoordsLocate';
import QueryTool from './QueryTool';
import ResCatalog from './ResCatalog';
import DrawQueryTool from './DrawQueryTool';
import EditFeature from './EditFeature';
import FlightPath from './FlightPath';
import ViewOnline from './ViewOnline';
import SpatialAnalysis from './SpatialAnalysis';
import AjQueryTool from './AjQueryTool';
import { getAction } from '../../../api/manage';
import QueryInfo from './QueryInfo';


export default {
  name: 'ToolBar',
  components: {
    QueryInfo,
    ResCatalog,
    DrawQueryTool,
    QueryTool,
    Measurement2D,
    CoordsLocate,
    EditFeature,
    FlightPath,
    ViewOnline,
    SpatialAnalysis,
    AjQueryTool
  },
  inject: ['basicMap'],
  props: {
    tools: {
      type: Array,
      default: function() {
        return [];
      }
    },
    showToolTip: {
      type: Boolean,
      default: true
    },
    splitScreen: {
      default: false
    }
  },
  data() {
    return {
      featureInfoShow: false,
      showLabel: true,
      screenWidth: document.body.clientWidth,
      isRes: false,
      isQuery: false,
      isCoords: false,
      isMeasure: false,
      isDrawQuery: false,
      isEdit: false,
      isDraw: false,
      isHome: false,
      isClear: false,
      isFlightPath: false,
      isViewOnline: false,
      isPrint: false,
      isAnalysis: false,
      isAjQuery: false,
      isSplit: false,
      isIdentify: false,
      enableIdentify: false,
      toolShow: {
        coordsShow: false,
        resShow: false,
        measureShow: false,
        queryShow: false,
        drawQueryShow: false,
        editShow: false,
        drawShow: false,
        flightPathShow: false,
        viewOnlineShow: false,
        printShow: false,
        analysisShow: false,
        ajQueryShow: false
      },
      queryConfigUrl: '/commonQueryConfig/commonQueryConfig/queryListByUser',
      identifyQueryUrl: '/commonQueryConfig/commonQueryConfig/identifyQuery',
      queryUrl: '/commonQueryConfig/commonQueryConfig/commonQuery',
      print: '',
      sketch: '',
      xzLayer: '',
      ghLayer: ''
    };
  },
  watch: {
    tools: function(tools) {
      this.tools.forEach((item) => {
        this[item] = true;
      });
      this.$nextTick(function() {
        this.getLabelShow();
      });
    },
    featureInfoShow:function(visible) {
      if(!visible){
        this.basicMap.handleCursorStyle('auto');
        this.enableIdentify = false;
        this.basicMap.mapView.graphics.removeAll();
      }
    }
    /*screenWidth (val) {
      this.screenWidth = val;
      this.getLabelShow()
    }*/
  },
  provide() {
    return {
      splitScreen: this.splitScreen
    };
  },
  mounted() {
    window.onresize = () => {
      return (() => {
        window.screenWidth = document.body.clientWidth;
        this.screenWidth = window.screenWidth;
      })();
    };
  },
  methods: {
    getLabelShow(split) {
      /*let w = this.$refs.toolbar.offsetWidth;
      let mapw = document.querySelector('.basicMap').offsetWidth;
      console.log(w,mapw,w/mapw)
      if(w/mapw >= 0.6){
        this.showLabel = false;
      }else {
        this.showLabel = true;
        if(split){
          this.$nextTick(()=>{
            this.getLabelShow()
          })
        }
      }*/
    },
    handleSplitScreen() {
      this.basicMap.splitScreen = !this.basicMap.splitScreen;
      if (this.ghLayer === '') {
        /*this.basicMap.layerList.map((item) => {
          if(item.name==='基础图层'){
            item.layers.map((layerItem)=>{
              if(layerItem.alias==='规划图'){
                this.ghLayer=layerItem;
                this.ghLayer.visible=true;
                this.basicMap._loadLayer(this.ghLayer,this.basicMap.esriMap2);
              }else if(layerItem.alias==='现状图'){
                this.xzLayer=layerItem;
                this.xzLayer.visible=true;
                this.basicMap._loadLayer(this.xzLayer,this.basicMap.esriMap3);
              }
            })
          }
        })*/
      }
      this.$nextTick(() => {
        this.getLabelShow(true);
        setTimeout(() => {
          this.basicMap.mapView2.extent = this.basicMap.mapView.extent;
        }, 30);
        if (this.basicMap.splitScreen) {
          window.addEventListener('mousemove', this.mouse, true);
        } else {
          window.removeEventListener('mousemove', this.mouse, true);
        }
      });
    },
    getDivPosition(div) {
      if (!div) return;
      var x = div.getBoundingClientRect().left;
      var y = div.getBoundingClientRect().top;
      return { x: x, y: y };
    },
    mouse(event) {
      var mapDom = document.getElementById('basicMap');
      let div1 = document.getElementById('div1');
      if (!div1 || !mapDom) return;
      let mapX = this.getDivPosition(mapDom).x;
      let mapY = this.getDivPosition(mapDom).y;
      var posX = 0, posY = 0;  //临时变量值
      var e = event || window.event;  //标准化事件对象
      if (e.pageX || e.pageY) {  //获取鼠标指针的当前坐标值
        posX = e.pageX;
        posY = e.pageY;
      } else if (e.clientX || e.clientY) {
        posX = event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
        posY = event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
      }
      let mx = posX - mapX;
      let my = posY - mapY;
      // console.log(mx,my,div1.offsetWidth,div1.offsetHeight)
      if (mx > 0 && my > 0 && mx < mapDom.offsetWidth && my < mapDom.offsetHeight) {
        div1.style.position = 'absolute';  //定义当前对象为绝对定位
        div1.style.top = (my) + 'px';  //用鼠标指针的y轴坐标和传入偏移值设置对象y轴坐标
        div1.style.left = (mx) + 'px';  //用鼠标指针的x轴坐标和传入偏移值设置对象x轴坐标
      }

    },
    handleTools(val) {
      let oldVal = this.toolShow[val];
      this.toolShow = {
        coordsShow: false,
        resShow: false,
        measureShow: false,
        queryShow: false,
        drawQueryShow: false,
        editShow: false,
        drawShow: false,
        flightPathShow: false,
        viewOnlineShow: false,
        printShow: false,
        analysisShow: false,
        ajQueryShow: false
      };
      this.toolShow[val] = !oldVal;
      if (this.toolShow.drawShow === false && this.sketch !== '') {
        this.sketch.visible = false;
        this.sketch.cancel();
        this.basicMap.draw_GraphicsLayer.removeAll();
      }
      if (this.toolShow.printShow === false && this.print !== '') {
        this.print.visible = false;
      }
      if (this.isMeasure && this.toolShow.measureShow === false) {
        this.$refs.measureToll.closeTool();
      }
      if (val === 'measureShow' && oldVal === false) {
        this.$refs.measureToll.initTool();
      } else if (val === 'analysisShow') {
        /*if (oldVal === true) {
          this.$refs.spatialAnalysis.stopDraw();
        } else {
        }*/
      } else if (val === 'ajQueryShow' && oldVal === true) {
        this.$refs.ajQueryTool.clear();
      }
    },
    handleIdentify() {
      this.enableIdentify = true;
      this.basicMap.handleCursorStyle('pointer');
    },
    doIdentify(evt) {
      if(this.basicMap.v_layerIds.length ==0){
        this.$message.warn('没有找到可供查询的要素！');
        this.enableIdentify = false;
        this.basicMap.handleCursorStyle('auto');
        return;
      }
      let view = this.basicMap.mapView;
      let params = new IdentifyParameters();
      params.tolerance = 2;
      params.layerIds = this.basicMap.v_layerIds;
      params.layerOption = 'top';
      params.width = view.width;
      params.height = view.height;
      params.geometry = evt.mapPoint;
      params.mapExtent = view.extent;
      params.returnGeometry = true;
      this.basicMap.handleCursorStyle('wait');

      let that = this;
      let identifyUrl = window._CONFIG['mapServerURL'];
      identify.identify(identifyUrl, params).then(function(response) {
        var result = response.results;
        if (result.length > 0) {
          let geometry = result[0].feature.geometry;
          that.basicMap.locateByGeometry(geometry);
          let layerName = result[0].layerName;
          let objectId = result[0].feature.attributes.OBJECTID;
          getAction(that.identifyQueryUrl, {
            layerName: layerName,
            objectId: objectId
          }).then((res) => {
            if (res.success && res.result !=null) {
              that.featureInfoShow = true;
              that.$refs.detail.loadDetail(res.result);
            } else {
              that.$message.warn('没有查询到要素属性信息！');
            }
          });
        }else{
          that.$refs.detail.loadDetail([]);
        }
        that.basicMap.handleCursorStyle('pointer');
      });
    },
    handleDrawTool() {
      this.handleTools('drawShow');
      if (this.toolShow.drawShow === true) {
        if (this.sketch == '') {
          this.sketch = new Sketch({
            layer: this.basicMap.draw_GraphicsLayer,
            view: this.basicMap.mapView,
            visible: true

          });
          this.basicMap.mapView.ui.add(this.sketch, 'bottom-left');
        }
        this.sketch.visible = true;
      }

    },
    handlePrint() {
      this.handleTools('printShow');
      let view = this.basicMap.mapView;
      if (this.toolShow.printShow === true) {
        if (this.print === '') {
          debugger
          this.print = new Print({
            view: view,
            // specify your own print service
            printServiceUrl:
              'http://218.59.194.82:6080/arcgis/rest/services/Utilities/PrintingTools/GPServer/Export%20Web%20Map%20Task'
          });
          // Add widget to the top right corner of the view
          view.ui.add(this.print, 'bottom-right');
        }
        this.print.visible = true;
      }

    },
    handleHome() {
      let vp = new Viewpoint({
        targetGeometry: new Extent(
          114.5997, 34.5248, 123.2469, 38.5253
        )
      });
      this.basicMap.mapView.goTo({
        target: [118.9943, 36.4939],
        zoom: 8,
        heading: 48,
        tilt: 80
      }, { duration: 300 });
      this.basicMap.mapView.rotation = 0;
      this.basicMap.mapView2.goTo({
        viewpoint: vp
      }, { duration: 300 });

    },
    handleClear() {
      this.handleTools();
      this.basicMap.mapView.graphics.removeAll();
      this.$refs.spatialAnalysis.clear();
      this.featureInfoShow = false;
    }
  }
};
</script>

<style >
.toolbar {
  position: absolute;
  top: 1em;
  left: 5em;
  border-radius: 4px;
  padding: 0;
  margin: 0;
  background-color: whitesmoke;
  cursor: pointer;
  z-index: 1;
  box-shadow: 0 0 5px #1890ff;
  opacity: 0.9;
}


.toolbar .ant-card .ant-card-head {
  background-color: rgba(24, 129, 253, 0.8);
  color: #FFFFFF;
  cursor: move;
}

.toolbar .ant-card .panelClose {
  cursor: pointer;
  color: #FFFFFF;
}

.toolbar .resCatalog .ant-card-body {
  padding: 0 !important;
}

.toolBar .resCatalog .ant-card-body {
  padding: 0;
}

.toolBar .resCatalog .ant-collapse > .ant-collapse-item-active > .ant-collapse-header {
  color: #0c8fcf;
}

.resCatalog .ant-collapse .ant-collapse > .ant-collapse-item > .ant-collapse-header {
  margin-left: 15px;
}

.resCatalog .ant-collapse-content > .ant-collapse-content-box {
  padding: 0px;
}



#measureTool,
#drawTool,

#coordsLocate,
#drawQueryTool,
#editFeature,
#viewOnline,
#flightPath,
#spatialAnalysis,
.aj-query,
.query,
.resCatalog
{
  position: fixed;
  top: 210px;
  right: 2em;
}

.esri-sketch {
  opacity: 0.9;
}

</style>
<style scoped>
li>a{
  text-align: center;
}
li p{
  padding: 0;
  margin: 0;
}
.toolBar {
  left: auto;
  right: 1em;
}
.nav {
  padding-left: 0;
  margin-bottom: 0;
  list-style: none;
  display: flex;
}

.nav-pills > li {
  float: left;
}

.nav > li {
  position: relative;
  display: block;
}

.nav-pills > li + li {
  margin-left: 2px;
}

.nav-pills > li > a {
  border-radius: 4px;
}

.nav > li > a {
  position: relative;
  display: block;
  padding: 10px 15px;
}

.nav > li > a:hover,
.nav > li > a:focus {
  text-decoration: none;
  background-color: #eeeeee;
}

a {
  color: #1890ff;
  text-decoration: none;
}

.nav > li > a > img {
  max-width: none;
}

img {
  vertical-align: middle;
}
</style>
