<template>
  <div class="app-container">
    <div class="level-title">
      <h1>{{ this.$parent.DOOR_ID == '' ? "新增" : "修改" }}</h1>
    </div>
    <div>
      <el-form v-loading="dialogFormVisible" ref="form" :model="form" :rules="rules" label-width="150px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属分公司:" prop="CORPINFO_ID">
              <el-select v-model="form.CORPINFO_ID" filterable placeholder="请选择" style="width: 205px">
                <el-option
                  v-for="item in corpList"
                  :key="item.CORPINFO_ID"
                  :label="item.CORP_NAME"
                  :value="item.CORPINFO_ID"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="口门名称:" prop="DOOR_NAME">
              <el-input v-model="form.DOOR_NAME" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="口门类型:" prop="DOOR_TYPE">
              <el-select v-model="form.DOOR_TYPE" style="width: 100%;">
                <el-option v-for="item in typeList" :key="item.VALUE" :label="item.NAME" :value="item.VALUE" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态:" prop="STATUS">
              <el-select v-model="form.STATUS" style="width: 100%;">
                <el-option v-for="item in statusList" :key="item.VALUE" :label="item.NAME" :value="item.VALUE" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="经纬度:" class="is-required">
              <el-input v-model="form.LONGITUDEANDLATITUDE" style="width:206px" placeholder="请选择" disabled/>
              <el-button style="margin-left: 10px" type="primary" @click="handleMap">点击定位</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="ui-foot">
      <el-button type="success" @click="confirm">保 存</el-button>
      <el-button plain type="info" @click="goBack">返 回</el-button>
    </div>

    <el-dialog :visible.sync="dialogFormMap" title="定位" width="1050px" class="dy-dialog">
      <div id="cesiumContainer" />
      <div slot="footer" class="dialog-footer">
        <span>经度:</span>
        <el-input v-model="form.LONGITUDE" style="width: 200px" placeholder="请输入内容" disabled />
        <span>纬度:</span>
        <el-input v-model="form.LATITUDE" style="width: 200px" placeholder="请输入内容" disabled />
        <el-button @click="dialogFormMap = false">取 消</el-button>
        <el-button type="primary" @click="setPosition">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination' // 通过 el-pagination二次打包
import { requestFN } from '@/utils/request'
import SelectTree from '@/components/SelectTree'
import waves from '@/directive/waves'
import TiandiMap from '../../../../../components/TianMap/TiandiMap'

let viewer = null
const Cesium = window.Cesium
Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJkOWQ0MGYwMy0yODUwLTQ1YzktOGM4OC02MTMwY2UyZjNlMzQiLCJpZCI6MTY0NTUwLCJpYXQiOjE2OTM4OTU1Mjd9.1cC0sSzyj79LZv0ILNCcl0Mabw6hl8TNngFNFr7H8f4'
var subdomains = ['0', '1', '2', '3', '4', '5', '6', '7']
var tiandituTk = 'e8a16137fd226a62a23cc7ba5c9c78ce'
const img_h = require('../../../../../assets/images/map/h.png')
export default {

  components: { Pagination, SelectTree, TiandiMap },
  directives: { waves },
  data() {
    return {
      dialogFormMap: false,
      dialogFormVisible: false,
      dialogTableVisible: false,
      PERSON_CHARGE: '',
      DEPARTMENT_ID_OLD: '',
      form: {
        CORPINFO_ID: '',
        DOOR_NAME: '',
        DOOR_TYPE: '',
        STATUS: '',
        LONGITUDE: '',
        LATITUDE: '',
        LONGITUDEANDLATITUDE: ''
      },
      corpList: [],
      riskForm: {},
      KEYWORDS: '',
      rules: {
        CORPINFO_ID: [{ required: true, message: '所属分公司不能为空', trigger: 'blur' }],
        DOOR_NAME: [{ required: true, message: '口门名称不能为空', trigger: 'blur' }],
        DOOR_TYPE: [{ required: true, message: '口门类型不能为空', trigger: 'blur' }],
        STATUS: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
      },
      formLabelWidth: '120px',
      fullscreenLoading: false,
      total: 0,
      listQuery: {
        page: 1,
        limit: 20
      },
      multipleSelection: [],
      accidentList: [],
      typeList: [
        { NAME: '人行口门', VALUE: 0 },
        { NAME: '车行口门', VALUE: 1 }
      ],
      statusList: [
        { NAME: '正常', VALUE: 0 },
        { NAME: '停用', VALUE: 1 },
        { NAME: '暂时关闭', VALUE: 2 }
      ]
    }
  },
  watch: {
  },
  async created() {
    viewer = null
    this.DOOR_ID = this.$parent.DOOR_ID
    this.form.DOOR_NAME = this.$parent.DOOR_NAME
    this.form.DOOR_TYPE = this.$parent.DOOR_TYPE
    this.form.STATUS = this.$parent.STATUS
    this.getCorpList()
    if (this.DOOR_ID) {
      this.getDataByID()
    }
  },
  methods: {
    setPosition() {
      this.form.LONGITUDEANDLATITUDE = this.form.LATITUDE + '--' + this.form.LONGITUDE
      this.dialogFormMap = false
    },
    /**
     * 初始化天地图对象
     */
    /*    initTDT() {
      return new Promise((resolve, reject) => {
        if (window.T) {
          console.log('天地图初始化成功...')
          resolve(window.T)
          reject('error')
        }
      }).then(T => {
        window.T = T
      })
    },*/
    /**
     * 初始化地图
     * @param {*} lng 经度
     * @param {*} lat 纬度
     * @param {*} zoom 缩放比例(1~18)
     */
    initMap(lng, lat, zoom) {
      viewer = new Cesium.Viewer('cesiumContainer', {
        // terrainProvider: Cesium.createWorldTerrain()
        animation: false, // 动画
        homeButton: true, // home键
        geocoder: true, // 地址编码
        baseLayerPicker: false, // 图层选择控件
        timeline: false, // 时间轴
        fullscreenButton: true, // 全屏显示
        infoBox: true, // 点击要素之后浮窗
        sceneModePicker: true, // 投影方式  三维/二维
        navigationInstructionsInitiallyVisible: false, // 导航指令
        navigationHelpButton: false, // 帮助信息
        selectionIndicator: false, // 选择
        imageryProvider: new Cesium.WebMapTileServiceImageryProvider({
          // 影像底图
          url: 'http://t{s}.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=' + tiandituTk,
          subdomains: subdomains,
          layer: 'tdtImgLayer',
          style: 'default',
          format: 'image/jpeg',
          tileMatrixSetID: 'GoogleMapsCompatible', // 使用谷歌的瓦片切片方式
          show: true
        })
      })
      viewer._cesiumWidget._creditContainer.style.display = 'none' // 隐藏cesium ion
      Cesium.ExperimentalFeatures.enableModelExperimental = true
      var tile3d = new Cesium.Cesium3DTileset({
        url: config.mapJsonUrl
      })
      viewer.scene.primitives.add(tile3d)

      this.toCenter(lng, lat, zoom)
      this.leftDownAction()
    },
    toCenter(LONGITUDE, LATITUDE, height) {
      if (!LONGITUDE && !LATITUDE) {
        viewer.camera.flyTo({
          destination: Cesium.Cartesian3.fromDegrees(119.58, 39.94, height)
        })
        viewer.entities.removeAll()
      } else {
        viewer.camera.flyTo({
          destination: Cesium.Cartesian3.fromDegrees(LONGITUDE, LATITUDE, height)
        })
        viewer.entities.removeAll()
        this.form.LONGITUDE = LONGITUDE
        this.form.LATITUDE = LATITUDE
        this.addPoint([LONGITUDE, LATITUDE], 'init')
      }
    },
    leftDownAction() {
      // 去掉entity的点击事件 start
      viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
      viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
      // 去掉entity的点击事件 end

      const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
      handler.setInputAction(event => {
        viewer.entities.removeAll()
        const clickPosition = viewer.scene.camera.pickEllipsoid(event.position) // 转经纬度(弧度)坐标
        const radiansPos = Cesium.Cartographic.fromCartesian(clickPosition) // 转角度
        this.form.LONGITUDE = Cesium.Math.toDegrees(radiansPos.longitude)
        this.form.LATITUDE = Cesium.Math.toDegrees(radiansPos.latitude)
        this.addPoint(clickPosition, 'click')
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    },
    addPoint(position, type) {
      viewer.entities.add({ position: type === 'init' ? Cesium.Cartesian3.fromDegrees(...position) : position, billboard: {
        image: img_h,
        height: 25,
        width: 23,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        disableDepthTestDistance: Number.POSITIVE_INFINITY
      }})
    },
    handleMap() {
      this.dialogFormMap = true
      this.$nextTick(() => {
        if (!viewer) this.initMap(this.form.LONGITUDE, this.form.LATITUDE, 5000)
        else this.toCenter(this.form.LONGITUDE, this.form.LATITUDE, 5000)
        /* else this.initCenter(this.form.LONGITUDE, this.form.LATITUDE, 16)*/
      })
    },
    confirm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.$parent.DOOR_ID == '') {
            this.handleAdd()
          } else {
            if (valid) {
              this.listLoading = true
              requestFN(
                '/mkmjDoor/edit',
                this.form
              ).then((data) => {
                this.goBack()
                this.listLoading = false
                this.dialogFormEdit = false
              }).catch((e) => {
                this.listLoading = false
              })
            }
          }
        }
      })
    },
    handleAdd() {
      requestFN(
        '/mkmjDoor/add',
        this.form
      ).then((data) => {
        if (data.msg === '保存成功') {
          this.$message.success(data.msg)
          this.goBack()
        } else {
          this.$message.warning(data.msg)
        }
      }).catch((e) => {
      })
    },
    getDataByID() {
      this.listLoading = true
      this.dialogFormVisible = true
      requestFN(
        '/mkmjDoor/goEdit',
        { DOOR_ID: this.DOOR_ID }
      ).then((data) => {
        this.form = data.pd
        this.form.LONGITUDEANDLATITUDE = this.form.LATITUDE + '--' + this.form.LONGITUDE
        this.dialogFormVisible = false
      }).catch((e) => {
        this.dialogFormVisible = false
        this.listLoading = false
      })
    },
    getCorpList() {
      requestFN(
        '/corpinfo/getSelectByCorpInfo',
        {
        }
      ).then((data) => {
        this.corpList = JSON.parse(data.corpInfoJson)
      }).catch((e) => {
      })
    },
    // 返回列表
    goBack() {
      this.$parent.activeName = 'List'
    }
  }
}
</script>

<style>
#cesiumContainer{
  width: 1000px;
  height: 500px;
  margin: auto;
}
.cesium-viewer-toolbar, .cesium-viewer-fullscreenContainer, .cesium-infoBox-visible {
  display: none !important;
}
</style>