<template>
  <div>
    <info-details ref="detail" v-model="infoShow" cls="edit"></info-details>
    <locate-by-geoinfo ref="locateByGeoinfo"></locate-by-geoinfo>
    <div :class="`edit edit`" style="display: flex;" v-drag="`.edit .ant-card-head`">
      <a-card v-show="value" title="编辑图斑" style=" max-height: 90vh; width: 355px;  box-shadow: 0 0 5px #357ee5;">
        <a-icon slot="extra" type="close" style="cursor: pointer; color: #FFFFFF;" @click="$emit('input',false)" />
        <div>
          <label for="">
            图斑查询：
            <a-input-search allow-clear :loading="isLoading" style="width: 70%" v-model.trim="keyword"
                            @search="handleSearch"
                            placeholder="请输入案件号"
                            @pressEnter="handleSearch" />
          </label>
          <div style="margin: 10px auto;display: flex;justify-content: space-evenly;">
            <a-tooltip placement="bottom">
              <template slot="title">
                在地图上点击选择
              </template>
              <a-button type="primary" icon="edit" @click="initDrawLayer">选择图斑</a-button>
            </a-tooltip>
            <a-button type="danger" icon="check-circle" @click="handleSubmit">提交</a-button>
          </div>
          <div style="margin: 10px auto;display: flex;justify-content: space-evenly;">
            <a-button size="small" icon="edit" @click="handleSketch('sketchPolygonTools')">绘制</a-button>
            <a-button size="small" icon="double-left" @click="handleSketch('sketchUndo')">回退</a-button>
            <a-button size="small" icon="double-right" @click="handleSketch('sketchRedo')">前进</a-button>
            <a-button size="small" icon="delete" @click="handleSketch('sketchDelete')">删除</a-button>
          </div>
          <a-list style="margin-top: 20px;" item-layout="horizontal" :data-source="data" :pagination="pagination">
            <a-list-item slot="renderItem" slot-scope="item, index"
                         style="position: relative; height: 95px;user-select: auto;"  :style="item.style">
              <a-list-item-meta @click="loadGeom(item.ajh)" :description="item.ghdl">
                <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-button slot="actions" type="primary" size="small" @click="showModal(item)">
                编辑
              </a-button>
              <a-modal
                :title="`案件号：${ajh}`"
                :visible="modelVisible"
                :confirm-loading="confirmLoading"
                @ok="handleOk"
                okText="提交修改"
                @cancel="handleCancel"
                class="edit"
                width="320px"
              >
                <div>
                  <label for="" style="margin: 8px 0;color: #66cc00;display: block">
                    建设程度：
                    <a-select v-model="jscd" style="width: 60%" placeholder="请选择建设程度">
                      <a-select-option value="在建">
                        在建
                      </a-select-option>
                      <a-select-option value="完工">
                        完工
                      </a-select-option>
                    </a-select>
                  </label>
                  <label for="" style="margin: 8px 0;color: #66cc00;display: block">
                    符合规划：
                    <a-select v-model="sffhgh" style="width: 60%" placeholder="请选择是否符合规划">
                      <a-select-option value="是">
                        是
                      </a-select-option>
                      <a-select-option value="否">
                        否
                      </a-select-option>
                    </a-select>
                  </label>
                </div>
                <a-button style="margin: 0 auto;display: block" icon="history" type="primary" @click="showSbModel">
                  修改上报时间
                </a-button>
              </a-modal>
              <a-modal
                title="案件上报日期编辑"
                :visible="sbmodelVisible"
                :confirm-loading="sbconfirmLoading"
                @ok="handleSbOk"
                okText="提交修改"
                @cancel="handleSbCancel"
                class="edit"
                width="330px"
              >
                <div>
                  <label for="" style="margin: 8px 0;color: #66cc00;display: block">
                    案件编号：
                    <span style="color: #333">{{ ajh }}</span>
                  </label>
                  <label for="" style="margin: 8px 0;color: #66cc00;display: block">
                    上报日期：
                    <span style="color: #333">{{ sbxx.SBRQ }}</span>
                  </label>
                  <label for="" style="margin: 8px 0;color: #66cc00;display: block">
                    上报人员：
                    <span style="color: #333">{{ sbxx.REALNAME }}</span>
                  </label>
                  <label for="" style="margin: 8px 0;color: #66cc00;display: block">
                    新上报日期：
                    <a-date-picker @change="dateOnChange" />
                  </label>
                </div>
              </a-modal>
              <a-popconfirm
                slot="actions"
                title="删除后不可撤销，确定永久删除此案件"
                ok-text="是"
                cancel-text="否"
                @confirm="confirm(item,index)"
              >
                <a-button type="danger" ghost size="small">
                  删除
                </a-button>
              </a-popconfirm>
            </a-list-item>
          </a-list>
        </div>
      </a-card>
    </div>


  </div>

</template>

<script>
import { deleteAction, getAction, httpAction, postAction, putAction } from '../../../api/manage'
import LocateByGeoinfo from './LocateByGeoinfo'
import InfoDetails from './InfoDetails'
import Draw from '@arcgis/core/views/draw/Draw'
import Graphic from '@arcgis/core/Graphic'
import Point from '@arcgis/core/geometry/Point'

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

  data() {
    return {
      map: '',
      draw:'',
      visible: false,
      list: [],
      isLoading: false,
      vectorLayer: '',
      drawLayer: '',
      queryType: '',
      lastType: '',
      keyword: '',
      data: [],
      onPage: false,
      pagination: {
        onChange: page => {
          this.pagination.current = page
          this.onPage = true
          this.handleSearch()
        },
        disabled: false,
        pageSize: 10,
        total: 0,
        size: 'small',
        current: 1
      },
      infoShow: false,
      ModalText: 'Content of the modal',
      modelVisible: false,
      sbmodelVisible: false,
      confirmLoading: false,
      sbconfirmLoading: false,
      jscd: '',
      sffhgh: '',
      ajh: '',
      sbrq: '',
      userName: '',
      sbxx: '',
      newsbrq: '',
      url:{
        delate:'/ajgl.ajxx/tinXjglSglistPolygon/delAjxx',
        sbList:'/ajgl.ajxx/tinXjglSglistPolygon/ajxxlist',
        sbEdit:'/ajgl.ajxx/tinXjglSglistPolygon/edit2',
        sbrqEdit:'/ajgl.ajsb/tinCaseSubmit/edit2',
        list:'ajgl.ajxx/tinXjglSglistPolygon/ajsbxxlist',
        listByGeom:'onemap.txcx/tinXjglSglistPolygon/geometryQuery',
        geom:'/onemap.txbj/tinXjglSglistPolygon/getGeometry',
        submit:'/onemap.txbj/tinXjglSglistPolygon/updateGeometry',
        update:'/onemap.sa/zfCaseSa/edit',
      }
    }
  },
  props: {
    value: {
      type: Boolean,
      default: false,
      required: true
    }
  },
  watch: {
    value(val) {
      if (val === false) {
        //清空搜索框
        this.lineShow = false
        this.onlineShow = false
        this.ajShow = false
        this.clear()
      } else {
        this.basicMap.changeLayerVisibleByLayerName("TIN_XJGL_SGLIST_POLYGON",true);
      }
    }
  },
  inject: ['basicMap'],
  async created() {
  },
  methods: {
    handleSketch(val){
      this.$refs.locateByGeoinfo[val]();
      console.log( this.$refs.locateByGeoinfo[val]())
    },
    async confirm(item, index) {
      let { success, message, result } = await deleteAction(this.url.delate, {
        ajh: item.ajh
      })
      if (success) {
        this.$message.success(message)
        this.data.splice(index, 1)
      } else {
        this.$message.info(message)
      }
    },
    showModal(item) {
      this.modelVisible = true
      this.sffhgh = item.sffhgh
      this.jscd = item.jscd
      this.ajh = item.ajh
    },
    async showSbModel() {
      this.sbmodelVisible = true
      let { success, message, result } = await getAction(this.url.sbList, {
        ajh: this.ajh
      })
      if (success) {
        if (result.length === 0 || result === '') {
          this.$message.error('没有查询到信息')
          return
        }
        this.sbxx = result[0]
      } else {
        this.$message.info(message)
      }
    },
    async handleOk(e) {
      this.confirmLoading = true
      /*this.jscd;
      this.sffhgh;*/
      let { success, message, result } = await getAction(this.url.sbEdit, {
        ajh: this.ajh,
        jscd: this.jscd,
        sffhgh: this.sffhgh
      })
      if (success) {
        if (result.length === 0 || result === '') {
          this.$message.error('没有查询到信息')
          return
        }
        this.$message.success(message)
        this.modelVisible = false
        this.confirmLoading = false
        this.handleSearch()
      } else {
        this.$message.info(message)
      }
    },
    handleCancel(e) {
      this.modelVisible = false
    },
    async handleSbOk(e) {
      this.sbconfirmLoading = true
      let { success, message, result } = await getAction(this.url.sbrqEdit, {
        ajh: this.ajh,
        realname: this.sbxx.REALNAME,
        oldsbrq: this.sbxx.SBRQ,
        newsbrq: this.newsbrq
      })
      if (success) {
        if (result.length === 0 || result === '') {
          this.$message.error('没有查询到信息')
          return
        }
        this.$message.success(message)
        this.sbmodelVisible = false
        this.sbconfirmLoading = false
      } else {
        this.$message.info(message)
      }
    },
    dateOnChange(date, dateString) {
      this.newsbrq = dateString
    },
    handleSbCancel(e) {
      console.log('Clicked cancel button')
      this.sbmodelVisible = false
    },
    async handleSearch() {
      if (this.keyword) {
        this.isLoading = true
        this.pagination.disabled = true
        if (!this.onPage) {
          this.pagination.current = 1
        }
        let { success, message, result } = await getAction(this.url.list, {
          createBy: this.$store.state.user.info.username,
          ajh: this.keyword,
          pageNo: this.pagination.current,
          pageSize: 10
        })
        this.onPage = false
        if (success) {
          this.isLoading = false
          this.pagination.disabled = false
          if (result.records) {
            if (result.total === 0 || result.records === '') {
              this.$message.error('没有查询到信息')
              this.data = []
              this.pagination.total = 0
              return
            }
            this.data = result.records
            this.pagination.total = result.total
          } else {
            if (result.length === 0 || result === '') {
              this.$message.error('没有查询到信息')
              this.data = []
              this.pagination.total = 0
              return
            }
            this.data = result
            this.pagination.total = result.length
          }
          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 {

              }
            }
          })
        } else {
          this.$message.info(message)
        }
      } else {
        this.$message.warn('请输入查询关键字！')
      }
    },
    handleDetail(item) {
      this.infoShow = true
      this.$refs.detail.loadDetail(item)
    },
    handleCoord(item) {
      this.$refs.locateByGeoinfo.locate(item, this.basicMap.esriMap)
    },
    clear() {
      this.$refs.locateByGeoinfo.clear()
      this.clearFeature()
    },
    initDrawLayer() {
      // this.map=this.basicMap.vecBasemap;
      let view = this.basicMap.mapView
      this.view = view

      this.draw = new Draw({
        view: view
      })
      this.getTypeSelected()
    },
    getTypeSelected() {
      let view = this.basicMap.mapView
      view.graphics.removeAll()
      const action = this.draw.create('point', {
        mode: 'click'
      })
      view.focus()
      action.on(
        [
          'vertex-add',
          'vertex-remove',
          'redo',
          'undo',
          'draw-complete'
        ], this.createPoint)

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

      })
    },
    createPoint(event) {
      //获取所有顶点
      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: '8px',  // pixels
          outline: {  // autocasts as new SimpleLineSymbol()
            color: [255, 255, 0],
            width: 3  // points
          }
        }
      })
      // 将绘制的图形添加到view
      this.view.graphics.add(graphic)
    },
    async loadList(payload) {
      let { success, message, result } = await postAction(this.url.listByGeom, {
        payload
      })
      if (success) {
        if (result.records) {
          if (result.total === 0 || result.records === '') {
            this.$message.error('没有查询到信息')
            return
          }
          this.loadGeom(result.records[0].ajh)
        } else {
          if (result.length === 0 || result === '') {
            this.$message.error('没有查询到信息')
            return
          }
          this.loadGeom(result[0].ajh)
        }
      } else {
        this.$message.info(message)
      }
    },
    async loadGeom(ajh) {
      this.clearFeature()
      this.ajh = ajh
      let { success, message, result } = await getAction(this.url.geom, {
        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) ,edit:true})
        }
      } else {
        this.$message.info(message)
      }
    },
    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];
    },
    handleSubmit() {
      this.$confirm({
        title: '确认提交?',
        onOk: async () => {
          let coord=[]
          this.layerSketch=this.basicMap.layerSketch;
          if (this.layerSketch.graphics.length > 0) {
            console.log(this.layerSketch.graphics)
            /*self.layerSketch.graphics.filter(function (graphic) {
              self.sGraphic = graphic;
              console.log(graphic)
                  //定义坐标
                  });*/
            coord=this.layerSketch.graphics._items[0].geometry.rings[0];
          }else {
            this.$error({title:'当前无图斑地理信息，请确认修改完成！'})
            return
          }
          coord.forEach((item,index)=>{
            coord[index]=this.mercatorTolonlat(item);
          })
          let vertices=[];
          coord.push(coord[0])
          vertices.push(coord);
          let featureGeoJson={
            type: "Feature",
            geometry: {
              type: 'Polygon',
              coordinates: vertices
            },
            properties: null,
            crs: {
              'type': "name",
              'properties': {
                'name': "EPSG:4490"
              }
            }
          }
          let { success, message, result } = await postAction(this.url.submit, {
            ajh: this.ajh,
            geoJson: JSON.stringify(featureGeoJson)
          })
          if (success) {
            this.$message.success(message)
            this.$refs.locateByGeoinfo.clear()
            let view = this.basicMap.mapView;
            const zoom = view.zoom;
            view.goTo({
              zoom: zoom + 1,
            },{duration:1})
            view.goTo({
              zoom: zoom - 1,
            },{duration:1})
          } else {
            this.$message.info(message)
          }
          await getAction(this.url.update, {
            ajh: this.ajh
          })
        },
      })

    },
    clearFeature() {
      this.basicMap.mapView.graphics.removeAll()

    }
  }

}
</script>

<style>
.edit a > .anticon {
  /* vertical-align: 0.2em; */
}

.edit .ant-modal-mask {
  background-color: rgba(0, 0, 0, 0.08);
}

.edit .ant-modal-content {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.edit .ant-avatar {
  /* background: url("https://img1.baidu.com/it/u=1159474645,508069395&fm=26&fmt=auto"); */
}

.edit .ant-list-item {
  align-items: flex-start;
}

.edit .ant-list-item-action {
  margin-left: 10px;
  position: absolute;
  bottom: 3px;
  right: 0;
}

.toolBar .ant-spin-nested-loading {
  max-height: 35vh;
  overflow-y: auto;

}
</style>
