<template>
  <div class="content">
    <!-- 头部 -->
    <div class="content-top">
      <el-form ref="form" :model="form" :inline="true" label-width="auto" size="small">
        <el-form-item label="排水分区名称">
          <el-input v-model="form.name" placeholder="输入排水分区名称" clearable></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="query()">查询</el-button>
          <el-button type="primary" @click="addPart()">新建</el-button>
          <el-button type="primary" @click="reset()">清除</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格 -->
    <div class="content-body">
      <el-table :data="tableData" stripe height="100%" ref="dTable" @row-dbclick="rowDbclick" :header-cell-style="{background:'#eaf1fd',color:'rgb(50,59,65)',height:'39px',textAlign:'center'}">
        <template slot="empty">
          <img src="@/assets/icon/null.png" alt />
        </template>
        <el-table-column prop="date" label="序号" align="center">
          <template slot-scope="scope">{{scope.$index+1}}</template>
        </el-table-column>
        <el-table-column prop="partitionName" label="分区名称" align="center"></el-table-column>
        <el-table-column prop="partitionArea" label="分区面积(KM²)" align="center"></el-table-column>
        <el-table-column label="监测点(个)" align="center">
          <template slot-scope="{row}">{{row.siteIds?row.siteIds.length:0}}</template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="{row}">
            <el-button type="text" style="padding:0" @click="showInMap(row)">定位</el-button>
            <el-button type="text" style="padding:0" @click="editor(row)">修改</el-button>
            <el-button type="text" style="padding:0" @click="remove(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="content-footer">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pagination.current" :page-sizes="[10, 25, 50, 100]" :page-size="pagination.size" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"></el-pagination>
    </div>
    <el-dialog v-dialogDrag :title="opType==1?'新增排水分区':'修改排水分区'" :visible.sync="dialogVisible" :modal="false" :append-to-body="true" width="430px" @close="closeDialog">
      <el-form :model="form" :inline="true" label-width="auto" size="small" ref="addForm">
        <el-form-item label="分区名称" prop="partitionName" :rules="[{ required: true, message: '请输入名称', trigger: 'blur' }]">
          <el-input v-model="form.partitionName" style="width:265px" placeholder="分区名称"></el-input>
        </el-form-item>
        <el-form-item label="分区面积">
          <el-input v-model="form.partitionArea" style="width:150px" placeholder="分区面积" readonly>
            <span slot="suffix">km²</span>
          </el-input>
          <el-button-group style="vertical-align: bottom;">
            <el-button type="primary" @click="drawPolygon()">绘制</el-button>
            <el-button type="primary" @click="clearDraw()">清除</el-button>
          </el-button-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remarks" style="width:265px"></el-input>
        </el-form-item>
        <el-form-item label="关联监测站点">
          <el-select v-model="form.siteIds" placeholder="选择站点" style="width:265px">
            <el-option v-for="item in []" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancel()">取 消</el-button>
        <el-button size="small" type="primary" @click="submit()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getPartition, delPartition, addPartition, editorPartition } from '@/views/spectrum/reform/api/api'
import * as turf from '@turf/turf'
export default {
  data() {
    return {
      form: {},
      tableData: [],
      pagination: { current: 1, size: 100, total: 0 },
      dialogVisible: false,
      handler: null,
      polygonDraw: null,
      opType: 1
    }
  },
  mounted() {
    this.getPartition()
  },
  destroyed() {
    window.viewer.entities.removeAll()
  },
  methods: {
    getPartition() {
      let params = JSON.parse(JSON.stringify(this.pagination))
      if (this.form.name) {
        params['name'] = this.form.name
      }
      getPartition(params).then((res) => {
        if (res.code && res.code == 1) {
          this.tableData = res.result.records
          this.pagination.total = res.result.total
        }
      })
    },
    /**
     * 查询
     */
    query() {
      this.pagination.current = 1
      this.pagination.size = 100
      this.getPartition()
    },
    /**
     * 重置
     */
    reset() {
      window.viewer.entities.remove(this.polygonDraw)
    },
    /**
     * 双击行
     */
    rowDbclick(row, column, event) {},
    handleSizeChange(size) {
      this.pagination.size = size
      this.getPartition()
    },
    handleCurrentChange(current) {
      this.pagination.current = current
      this.getPartition()
    },
    /**
     * 添加
     */
    addPart() {
      this.opType = 1
      this.dialogVisible = true
      this.form = {}
      this.$nextTick(() => {
        this.$refs['addForm'].clearValidate()
      })
    },
    /**
     * 定位
     */
    showInMap(row) {
      this.locationPolygon(row)
    },
    /**
     * 删除
     */
    remove(row) {
      this.$confirm('删除该排水分区?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delPartition(row.id).then((res) => {
            if (res.code == 1) {
              this.$message.success('删除排水分区成功')
              this.query()
            }
          })
        })
        .catch(() => {})
    },
    /**
     * 修改
     */
    editor(row) {
      this.opType = 2
      this.dialogVisible = true
      this.locationPolygon(row)
      let data = { ...row }
      this.form = {
        id: data.id,
        partitionArea: data.partitionArea,
        partitionName: data.partitionName,
        projectId: data.projectId,
        siteIds: data.siteIds,
        projectName: data.projectName,
        remarks: data.remarks,
        coordinate: data.coordinate
      }
      this.$nextTick(() => {
        this.$refs['addForm'].clearValidate()
      })
    },
    /**
     * 该方法用于绘制分区范围
     */
    drawPolygon(callback) {
      this.clearDrawHandler()
      this.clearDrawPolygon()
      const viewer = window.viewer
      this.handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas)
      viewer.enableCursorStyle = false
      viewer._element.style.cursor = ''
      // this._handler = handler
      // const tooltips = createTooltip(document.querySelector(AppX.appConfig.mainContainer))
      // this._tooltips = tooltips
      // this.getCursorStyle(true)
      //this.g_drawHandler = handler;
      let isDrawing = false
      let positions = []
      let polygon = null
      this.handler.setInputAction((e) => {
        const position = viewer.scene.pickPosition(e.position)
        if (!isDrawing) {
          positions.push(position)
          isDrawing = true
        } else {
          positions.push(position)
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
      this.handler.setInputAction((e) => {
        // tooltips.showAt(e.endPosition, '<p>左键单击绘制，右键单击结束绘制</p>')
        if (isDrawing) {
          const position = viewer.scene.pickPosition(e.endPosition)
          if (positions.length === 1) {
            positions.push(position)
            polygon = viewer.entities.add({
              polyline: {
                show: new Cesium.CallbackProperty(() => {
                  return positions.length >= 2
                }, false),
                positions: new Cesium.CallbackProperty(() => {
                  if (positions.length < 3) {
                    return positions
                  } else {
                    const line = positions.map((item) => item)
                    line.push(line[0])
                    return line
                  }
                }, false),
                followSurface: false,
                clampToGround: true,
                material: Cesium.Color.DODGERBLUE,
                width: 2.0
              },
              polygon: {
                hierarchy: new Cesium.CallbackProperty(() => {
                  return new Cesium.PolygonHierarchy(positions)
                }, false),
                material: Cesium.Color.DEEPSKYBLUE.withAlpha(0.3),
                perPositionHeight: false,
                outline: true,
                outlineColor: Cesium.Color.DODGERBLUE,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                outlineWidth: 1.0
              }
            })
            this.polygonDraw = polygon
            //viewer.dataSources.add(this.g_drawEntityCollection);
            console.log('多边形===》》', polygon)
          } else {
            positions[positions.length - 1] = position
          }
        }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
      this.handler.setInputAction((e) => {
        if (!isDrawing) {
          this.clearDrawHandler()
          return
        }
        if (positions.length > 2) {
          const position = viewer.scene.pickPosition(e.position)
          //const radius=Cesium.Cartesian3.distance(center,otherpoint);
          if (Cesium.defined(polygon)) {
            positions.push(position)
          }
          console.log('分区绘制', polygon, positions)
          // window.viewer.entities.add(polygon)
          // callback(polygon)
          this.getArea(polygon)
          isDrawing = false
          this.clearDrawHandler()
          // this.handler.destroy()
          window.viewer.enableCursorStyle = true
        }
      }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
    },
    /**
     * 获取面积
     */
    getArea(polygon) {
      const positions = polygon.polygon.hierarchy.getValue(Cesium.JulianDate.now())
      const scopePositions = positions.positions.map((position) => {
        const lonlat = Cesium.Cartographic.fromCartesian(position)
        return { x: Cesium.Math.toDegrees(lonlat.longitude), y: Cesium.Math.toDegrees(lonlat.latitude) }
      })
      this.form['coordinate'] = JSON.stringify(scopePositions) // 坐标
      //面积计算
      const newLonlat = scopePositions.map((item) => {
        return [item.x, item.y]
      })
      newLonlat.push(newLonlat[0])
      const turfpolygon = turf.polygon([newLonlat])
      const area = (turf.area(turfpolygon) / 1000000).toFixed(2)
      this.$set(this.form, 'partitionArea', area)
    },
    /**
     * 取消
     */
    cancel() {
      this.clearDrawHandler()
      this.clearDrawPolygon()
      this.dialogVisible = false
    },
    /**
     * 定位
     */
    locationPolygon(data) {
      //this.clearPolygon();
      let viewer = window.viewer
      const positions = data.coordinate
      if (!positions) return

      const jsonPosition = JSON.parse(positions)
      const newPositions = jsonPosition.map((item) => {
        return Cesium.Cartesian3.fromDegrees(item.x, item.y)
      })
      const linePositions = newPositions.map((item) => {
        return item
      })

      linePositions.push(linePositions[0])
      const bound = Cesium.PolygonGeometry.computeRectangle({
        polygonHierarchy: new Cesium.PolygonHierarchy(newPositions)
      })
      const center = Cesium.Rectangle.center(bound)
      center.height = 200
      const centercar3 = Cesium.Cartographic.toCartesian(center)
      //名称标识背景
      const color = 'rgb(56, 136, 205)'
      const canvas = document.createElement('canvas')
      let ratio = 2.0
      let width = 100
      let height = 200
      canvas.width = 120
      canvas.height = 80
      const ctx = canvas.getContext('2d')
      const img = new Image()
      img.src = require('@/assets/images/quantum/icon.png')
      img.onload = () => {
        ctx.lineWidth = 10
        ctx.strokeStyle = color
        ctx.font = '24px bold 宋体'
        const width = ctx.measureText(data.partitionName).width + 30
        canvas.width = width
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
        ctx.font = '24px bold 宋体'
        ctx.fillStyle = 'rgb(10,109,185)'
        ctx.textBaseline = 'middle'
        ctx.fillText(data.partitionName, 15, 27)
        let entity = {
          position: centercar3,
          billboard: {
            sizeInMeters: false,
            image: canvas,
            heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER
          },
          polyline: {
            show: true,
            followSurface: false,
            clampToGround: true,
            positions: linePositions,
            material: Cesium.Color.DODGERBLUE,
            width: 2.0
          },
          polygon: {
            hierarchy: new Cesium.PolygonHierarchy(newPositions),
            material: Cesium.Color.DEEPSKYBLUE.withAlpha(0.1),
            perPositionHeight: false,
            outline: false,
            outlineColor: Cesium.Color.GREEN,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            outlineWidth: 2.0
          }
        }
        const polygon = viewer.entities.add(entity)
        // viewer.entities.add(polygon)
        viewer.flyTo(polygon, {
          offset: new Cesium.HeadingPitchRange(0, Cesium.Math.toRadians(-90))
        })
      }
    },
    /**
     * 新增提交
     */
    addSubmit() {
      let projectId = this.$store.state.project.project.id
      let projectCode = this.$store.state.project.project.code
      if (!projectId || !projectCode) {
        this.$message.error('未获取到项目信息！')
        return
      }
      let data = JSON.parse(JSON.stringify(this.form))
      data['projectId'] = projectId
      data['projectCode'] = projectCode
      addPartition(data).then((res) => {
        if (res.code && res.code == 1) {
          this.$message.success('添加排水分区成功！')
          this.cancel()
          this.query()
        }
      })
    },
    /**
     * 修改提交
     */
    editorSubmit() {
      let data = JSON.parse(JSON.stringify(this.form))
      editorPartition(data).then((res) => {
        if (res.code && res.code == 1) {
          this.$message.success('修改排水分区成功！')
          this.cancel()
          this.query()
        }
      })
    },
    /**
     * 提交
     */
    submit() {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          if (this.opType == 1) this.addSubmit()
          else this.editorSubmit()
        } else {
          return false
        }
      })
    },
    /**
     * 弹窗关闭
     */
    closeDialog() {
      this.cancel()
    },
    /**
     * 清除绘制
     */
    clearDraw() {
      this.clearDrawHandler()
      this.clearDrawPolygon()
    },
    /**
     * 清除绘制
     */
    clearDrawPolygon() {
      if (this.polygonDraw) {
        window.viewer.entities.remove(this.polygonDraw)
        this.polygonDraw = null
      }
    },
    /**
     * 清除Hander
     */
    clearDrawHandler() {
      if (this.handler) {
        this.handler.destroy()
        this.handler = null
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.content {
  width: 100%;
  height: 100%;
  .content-top {
    width: 100%;
    height: 60px;
    padding: 10px 20px;
    .el-form {
      >>> .el-form-item {
        margin-bottom: 0 !important;
        vertical-align: sub !important;
      }
    }
  }
  .content-body {
    width: 100%;
    height: calc(100% - 120px);
    box-sizing: border-box;
    padding: 0 20px;
    padding-bottom: 5px;
    .el-table {
      >>> th > .cell {
        white-space: pre-line;
      }
      >>> .el-table__body {
        td.el-table__cell {
          padding: 0 !important;
          height: 34px;
        }
      }
    }
  }
  .content-footer {
    width: 100%;
    height: 55px;
    line-height: 35px;
    padding: 10px 20px;
  }
}
.el-dialog__wrapper {
  pointer-events: none;
  overflow: hidden;
  >>> .el-dialog {
    // 弹窗层元素不可穿透点击事件（不影响弹窗层元素的点击事件）
    pointer-events: auto;
    .el-dialog__header {
      background-color: #13479e;
      .el-dialog__title {
        color: #ffffff;
      }
      .el-dialog__close {
        color: #ffffff !important;
      }
    }
  }
}
</style>