<template>
  <div :class="`drawQuery `" style="display: flex;" v-drag="`.drawQuery .ant-card-head`">
    <a-card v-show="value" title="案件查询" style="width: 335px;  box-shadow: 0 0 5px #357ee5;">
      <a-icon slot="extra" type="close" style="cursor: pointer; color: #FFFFFF;" @click="$emit('input',false)" />
      <a-radio-group id="select-radio" v-show="!basicMap.drawType" v-model="typeSelected"  @change="getTypeSelected">
        <a-radio-button id="point-button" value="point">点</a-radio-button>
        <a-radio-button id="rectangle-button" value="rectangle">矩形</a-radio-button>
        <a-radio-button id="polygon-button" value="polygon">多边</a-radio-button>
      </a-radio-group>
      <a-button style="margin-left: 20px" @click="clearFeature" type="primary">清空</a-button>
      <a-spin style="display: block;margin: 0 auto" :spinning="spinning">
      </a-spin>
      <a-list style="margin-top: 20px;" item-layout="horizontal" :data-source="data" :pagination="pagination">
        <a-list-item slot="renderItem" slot-scope="item, index"  :style="item.style">
          <a-list-item-meta @click="handleCoord(item)" :description="item.ssxz+item.sscz">
            <span slot="title">{{ item.ajh }}</span>
            <a-avatar slot="avatar" class="result" :src="require(`@/assets/result${index+1}.png`)">
            </a-avatar>
          </a-list-item-meta>
          <a-tag v-if="item.anjzt_dictText.includes('待处理')" color="blue">
            {{ item.anjzt_dictText }}
          </a-tag>
          <a-tag v-else-if="item.anjzt_dictText.includes('未派发')" color="red">
            {{ item.anjzt_dictText }}
          </a-tag>
          <a-tag v-else-if="item.anjzt_dictText.includes('待审核')" color="purple">
            {{ item.anjzt_dictText }}
          </a-tag>
          <a-tag v-else-if="item.anjzt_dictText.includes('待复飞')" color="orange">
            {{ item.anjzt_dictText }}
          </a-tag>
          <a-tag v-else-if="item.anjzt_dictText.includes('结案')" color="green">
            {{ item.anjzt_dictText }}
          </a-tag>
          <a-tag v-else>
            {{ item.anjzt_dictText }}
          </a-tag>
          <a-button slot="actions" type="primary" ghost size="small" @click="handleDetail(item)">
            详情
          </a-button>
        </a-list-item>
      </a-list>
    </a-card>
    <locate-by-geoinfo ref="locateByGeoinfo"></locate-by-geoinfo>
    <info-details ref="detail" v-model="infoShow"></info-details>

  </div>
</template>

<script>
import Draw from '@arcgis/core/views/draw/Draw'
import { getAction, postAction } from '../../../api/manage'
import Graphic from '@arcgis/core/Graphic'
import Point from '@arcgis/core/geometry/Point'
import Polygon from '@arcgis/core/geometry/Polygon'
import * as webMercatorUtils from "@arcgis/core/geometry/support/webMercatorUtils";

import InfoDetails from './InfoDetails'
import LocateByGeoinfo from './LocateByGeoinfo'

export default {
  name: 'DrawQueryTool',
  components: {InfoDetails, LocateByGeoinfo},

  data() {
    return {
      typeSelected: 'None',
      drawLayer: null,
      draw: null,
      view: '',
      map: null,
      infoShow: false,
      data: [],
      spinning: false,
      pagination: {
        onChange: page => {
          this.pagination.current = page
        },
        disabled: false,
        pageSize: 10,
        total: 0,
        size: 'small',
        current: 1
      },
      listUrl:'onemap.txcx/tinXjglSglistPolygon/geometryQuery',
      geoUrl:'/onemap.txbj/tinXjglSglistPolygon/getGeometry',
    }
  },
  props: {
    value: {
      type: Boolean,
      default: false,
      required: true
    }
  },
  inject: ['basicMap'],
  watch: {
    value: function(newValue) {
      if (newValue === false) {
        this.typeSelected = ''
      } else {
        this.basicMap.changeLayerVisibleByLayerName("TIN_XJGL_SGLIST_POLYGON",true);
        this.initDrawLayer();
      }
    }
  },
  mounted() {
  },
  methods: {
    mercatorTolonlat(mercator){
      var x = mercator[0]/20037508.34*180;
      var y = mercator[1]/20037508.34*180;
      y= 180/Math.PI*(2*Math.atan(Math.exp(y*Math.PI/180))-Math.PI/2);
      return [x,y];
    },
    initDrawLayer() {
      // this.map=this.basicMap.vecBasemap;
      let view = this.basicMap.mapView
      this.view = view
      this.draw = new Draw({
        view: view
      })
    },
    getTypeSelected() {
      if(this.typeSelected=='') return
      let view = this.basicMap.mapView
      view.graphics.removeAll()
      const action = this.draw.create(this.typeSelected, {
        mode: 'click'
      })
      view.focus()
      switch (this.typeSelected) {
        case 'point':
          action.on(
            [
              'vertex-add',
              'vertex-remove',
              'redo',
              'undo',
              'draw-complete'
            ], this.createPoint)
          break;
        case 'rectangle':
          action.on(
            [
              'vertex-add',
              'vertex-remove',
              'redo',
              'undo',
              'draw-complete',
              'cursor-update'
            ], this.createRectangle)
          break;
        case 'polygon':
          action.on(
            [
              'vertex-add',
              'vertex-remove',
              'redo',
              'undo',
              'draw-complete',
              'cursor-update'
            ], this.createPolygon)
          break;
        default:

          break;
      }

      action.on('draw-complete', (evt)=> {
        let type='Polygon'
        evt.vertices.forEach((item,index)=>{
          evt.vertices[index]=this.mercatorTolonlat(item);
        })
        let vertices= evt.vertices;
        if(this.typeSelected==='point'){
          type='Point'
          vertices=vertices[0];
        }else if(this.typeSelected==='rectangle'){
          vertices=[[vertices[0], [vertices[0][0], vertices[1][1]], vertices[1], [vertices[1][0], vertices[0][1]],vertices[0]]]
        } else {
          vertices=[];
          evt.vertices.push(evt.vertices[0])
          vertices.push(evt.vertices);
        }
        let featureGeoJson={
          type: "Feature",
          geometry: {
            type: type,
            coordinates: vertices
          },
          properties: null,
          crs: {
            'type': "name",
            'properties': {
              'name': "EPSG:4490"
            }
          }
        }
        this.loadList(featureGeoJson)
        this.typeSelected='';
      })

    },
    createPoint(event) {
      this.view.graphics.removeAll()

      //获取所有顶点
      var coordinates = event.coordinates

      //生成绘制的图形
      var graphic = new Graphic({
        geometry: new Point({
          hasZ: false,
          hasM: false,
          x: coordinates[0],
          y: coordinates[1],
          spatialReference: this.view.spatialReference
        }),
        symbol: {
          type: 'simple-marker',  // autocasts as new SimpleMarkerSymbol()
          style: 'square',
          color: 'blue',
          size: '10px',  // pixels
          outline: {  // autocasts as new SimpleLineSymbol()
            color: [255, 255, 0],
            width: 3  // points
          }
        }
      })
      // 将绘制的图形添加到view
      this.view.graphics.add(graphic)
    },
    createRectangle(event) {
      //获取所有顶点
      var vertices = event.vertices
      //两点画矩形
      if (vertices.length < 2) {
        return
      }
      var rings = [vertices[0], [vertices[0][0], vertices[1][1]], vertices[1], [vertices[1][0], vertices[0][1]]]
      //清除之前绘制
      this.view.graphics.removeAll()

      // 生成绘制的图形
      var graphic = new Graphic({
        geometry: new Polygon({
          hasZ: false,
          hasM: false,
          rings: [rings],
          spatialReference: this.view.spatialReference
        }),
        symbol: {
          type: 'simple-fill',  // autocasts as new SimpleFillSymbol()
          color: [51, 51, 204, 0.4],
          style: 'solid',
          outline: {  // autocasts as new SimpleLineSymbol()
            color: 'red',
            width: 1
          }
        }
      })
      // 将绘制的图形添加到view
      this.view.graphics.add(graphic)
    },
    createPolygon(event) {
      //获取所有顶点
      var vertices = event.vertices
      //清除之前绘制
      this.view.graphics.removeAll()

      // 生成绘制的图形
      var graphic = new Graphic({
        geometry: new Polygon({
          hasZ: false,
          hasM: false,
          rings: [vertices],
          spatialReference: this.view.spatialReference
        }),
        symbol: {
          type: 'simple-fill',  // autocasts as new SimpleFillSymbol()
          color: [51, 51, 204, 0.4],
          style: 'solid',
          outline: {  // autocasts as new SimpleLineSymbol()
            color: 'red',
            width: 1
          }
        }
      })
      // 将绘制的图形添加到view
      this.view.graphics.add(graphic)
    },
    async loadList(payload) {
      this.data = []
      this.pagination.current = 1
      this.pagination.total = 0
      this.spinning = true
      let { success, message, result } = await postAction(this.listUrl, {
        payload
      })
      if (success) {
        this.spinning = false
        this.pagination.current = 1
        if (result.records) {
          if (result.total === 0 || result.records === '') {
            this.$message.error('没有查询到信息')
            this.data = []
            return
          }
          this.data = result.records
        } else {
          if (result.length === 0 || result === '') {
            this.$message.error('没有查询到信息')
            this.data = []
            return
          }
          this.data = result
        }
        this.data.forEach((item) => {
          if (item.anjztdictText) {
            item.anjzt_dictText = item.anjztdictText
          }
          item.style='position: relative';
          if(item.anjzt_dictText==='已派发待处理'){
            var str = item.zprq;
            var d1 = new Date(str);
            var d2 = new Date();
            // 将两个日期都转换为毫秒格式，然后做差
            let diffDate = Math.abs(d2 - d1) // 取相差毫秒数的绝对值
            let totalDays = Math.floor(diffDate / (1000 * 3600 * 24)) // 向下取整
            if(totalDays>=3&&totalDays<10){
              item.style='position: relative;border: blue solid 1px;border-radius: 5px';
            }else if(totalDays>=10&&totalDays<30){
              item.style='position: relative;border: orange solid 1px;border-radius: 5px';
            }else if(totalDays>=30&&totalDays<365){
              item.style='position: relative;border: yellow solid 1px;border-radius: 5px';
            }else if(totalDays>=365){
              item.style='position: relative;border: red solid 1px;border-radius: 5px';
            }else {

            }
          }
        })
        this.pagination.total = this.data.length
      } else {
        this.$message.info(message)
      }
    },

    // 清除数据
    clearFeature() {
      let view = this.basicMap.mapView
      view.graphics.removeAll()
      if(this.draw!==''){
        this.draw.reset();
      }
    },
    handleDetail(item) {
      this.infoShow = true
      this.$refs.detail.loadDetail(item)
    },
    handleCoord(item) {
      this.loadGeom(item.ajh);
    },
    async loadGeom(ajh) {
      this.clearFeature()
      this.ajh = ajh
      let { success, message, result } = await getAction(this.geoUrl, {
        ajh
      })
      if (success) {
        if (result.records) {
          if (result.total === 0 || result.records === '') {
            this.$message.error('没有查询到信息')
            return
          }
        } else {
          if (result.length === 0 || result === '') {
            this.$message.error('没有查询到信息')
            return
          }
          this.map = this.basicMap.esriMap
          this.$refs.locateByGeoinfo.locate({ geoinfo: JSON.stringify(result.geometry) }, this.map)
        }
      } else {
        this.$message.info(message)
      }
    },
  }
}
</script>

<style scoped>

</style>
