<template>
  <el-container>
    <el-main>
      <div class="headerTop">
        <div>
          <el-button type="primary" class="el-icon-plus" @click="doAdd(1, '')">
            新增</el-button
          >
        </div>
        <div>
          <right-toolbar @queryTable="initList" :search="false"></right-toolbar>
        </div>
      </div>

      <el-table
        :data="list"
        height="calc(100% - 80px)"
        :row-style="{ height: '0px' }"
        :header-cell-style="{ 'text-align': 'center', padding: '0px' }"
        :cell-style="{ 'text-align': 'center', padding: '2px' }"
        style="width: 100%"
        row-key="id"
        :tree-props="{
          children: 'childList',
          hasChildren: 'hasChildren'
        }"
      >
        <el-table-column
          prop="areaName"
          show-overflow-tooltip
          label="区域名称"
          align="center"
        />
        <el-table-column
          prop="areaCode"
          show-overflow-tooltip
          label="NFC编码"
          align="center"
        />
        <el-table-column
          prop="postName"
          show-overflow-tooltip
          label="区域负责岗位"
          align="center"
        />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="doAdd(1, scope.row)">
              新增
            </el-button>
            <el-button type="text" @click="doAdd(2, scope.row)">
              编辑
            </el-button>
            <el-button type="text" @click="doDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-main>

    <!-- 新增/编辑 的dialog -->
    <el-dialog
      :visible.sync="dialogVisible"
      v-if="dialogVisible"
      width="600px"
      :title="isEdit"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleFormRef"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="区域名称：" prop="areaName">
          <el-input v-model="ruleForm.areaName" maxlength="100"></el-input>
        </el-form-item>
        <el-form-item label="区域负责岗位：" prop="postId">
          <el-select v-model="ruleForm.postId" clearable style="width: 100%">
            <el-option
              :label="item.postName"
              :value="item.postId"
              v-for="item in postList"
              :key="item.postId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="NFC编码：" prop="areaCode">
          <el-input v-model="ruleForm.areaCode" maxlength="100"></el-input>
        </el-form-item>
        <el-form-item label="经纬度：" prop="areaCode">
          <el-button type="primary" @click="start"> 地图选址 </el-button>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancle">取 消</el-button>
        <el-button type="primary" @click="submit">提 交</el-button>
      </span>
    </el-dialog>

    <!-- 查看 的dialog -->
    <el-dialog :visible.sync="LookdialogVisible" title="查看" width="700px">
      <el-row>
        <el-col :span="12">类目名称： {{ watchObj.categoriesName }} </el-col>
        <el-col :span="12">排序： {{ watchObj.classificationSort }} </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">创建时间： {{ watchObj.createDate }} </el-col>
        <el-col :span="12">创建人： {{ watchObj.createUserId }} </el-col>
      </el-row>
    </el-dialog>

    <el-dialog
      v-if="mapDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="地图选址"
      width="90%"
      :visible.sync="mapDialogVisible"
    >
      <el-button type="primary" @click="draw"> 开始选址 </el-button>
      <div id="mapDiv"></div>
      <div id="right-btn"></div>
    </el-dialog>
  </el-container>
</template>

<script>
import {
  areaTree,
  systemArea,
  systemAreaAdd,
  systemAreaDel
} from '@/api/risk/region.js'

import { postList } from '@/api/planClass/planClass.js'
export default {
  name: 'RuoyiPlanClass',
  data() {
    return {
      ansUrl: require('@/assets/images/dingwei.png'),
      mapDialogVisible: false,
      currentLnglatList: [],
      temporarilyList:[],
      currentPolygon: null,
      map: null,

      isSearch: false, //控制搜索框是否显示
      search: {
        categoriesName: ''
      },

      list: [],
      postList: [], // 岗位的下拉菜单
      watchObj: {}, // 查看的接收
      dialogVisible: false, //新增/修改的dialog
      LookdialogVisible: false, //查看的dialog
      isEdit: '',

      ruleForm: {
        areaName: '',
        id: '',
        parentId: '',
        currentLnglatList: [],
        address: null,
        areaCode: ''
      },
      rules: {
        areaName: [
          { required: true, message: '请输入区域名称', trigger: 'blur' }
        ],
        postId: [{ required: true, message: '请选择岗位', trigger: 'change' }],
        longitude: [{ required: true, message: '请输入经度', trigger: 'blur' }],
        latitude: [{ required: true, message: '请输入纬度', trigger: 'blur' }],
        areaCode: [
          { required: true, message: '请输入NFC编码', trigger: 'blur' }
        ]
      },
      loading: false // loading 效果
    }
  },

  mounted() {
    this.initList() // 列表初始化
    this.initPostOptions() // 列表初始化
  },

  methods: {
    // 列表初始化
    initList() {
      try {
        this.loading = true
        areaTree().then((res) => {
          this.list = res
          this.loading = false
        })
      } catch (error) {
        this.loading = false
      }
    },
    // 岗位的下拉
    initPostOptions() {
      postList().then((res) => {
        if (res.code === 200) {
          this.postList = res.rows
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    reset() {
      this.search.categoriesName = ''
      this.initList()
    },
    doAdd(type, val) {
      if (type === 1) {
        this.isEdit = '新增'
        if (val) {
          this.ruleForm.parentId = val.id || ''
        }
      } else {
        this.isEdit = '编辑'
        this.ruleForm = { ...val }
        this.temporarilyList =val.currentLnglatList
      }
      this.dialogVisible = true
    },
    // 取消按钮
    cancle() {
      this.$nextTick(() => {
        this.ruleForm = {
          areaName: '',
          id: '',
          parentId: '',
          currentLnglatList: [],
          areaCode: ''
        }
        this.$refs.ruleFormRef.resetFields()
      })
      this.ruleForm = {
        areaName: '',
        id: '',
        parentId: '',
        currentLnglatList: [],
        areaCode: ''
      }
      this.dialogVisible = false
    },
    // 确定按钮
    submit() {
      this.$refs.ruleFormRef.validate(async (valid) => {
        if (valid) {
          this.currentLnglatList.forEach((item) => {
            this.ruleForm.currentLnglatList.push({
              longitude: item.lat,
              latitude: item.lng
            })
          })
          if (!this.ruleForm.currentLnglatList.length)
            return this.$message.error('经纬度不能为空!')
          if (this.isEdit == '新增') {
            const res = await systemAreaAdd(this.ruleForm)
            if (res.code !== 200) return this.$message.error(res.msg)
          } else {
            const res = await systemArea(this.ruleForm)
            if (res.code !== 200) return this.$message.error(res.msg)
          }
          this.initList()
          this.$message.success(`${this.isEdit}成功!`)
          this.ruleForm = {
            areaName: '',
            id: '',
            parentId: '',
            currentLnglatList: [],
            areaCode: ''
          }
          this.dialogVisible = false
        } else {
          this.$message.warning('必传项不能为空!')
          return false
        }
      })
    },
    // 查看
    doWatch(val) {
      this.watchObj = val
      this.LookdialogVisible = true
    },
    // 删除1
    doDelete(val) {
      this.$confirm('此操作将永久删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await systemAreaDel(val.id)
          if (res.code !== 200) return this.$message.error(res.msg)
          this.initList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message.warning('已取消删除')
        })
    },
    start() {
      this.mapDialogVisible = true
      this.$nextTick(() => {
        this.onLoad()
      })
    },

    draw() {
      var polygonTool = new T.PolygonTool(this.map, {
        showLabel: false, // 不显示面积信息
        color: '#ffcd42',
        weight: 3,
        opacity: 0.5,
        fillColor: '#ffdc00',
        fillOpacity: 0.5
      })
      polygonTool.open()
      polygonTool.addEventListener('draw', this.drawFinish) // 监听双击绘制完成事件，调用drawFinish方法
    },
    // 圈地结束
    drawFinish(e) {
      this.ruleForm.currentLnglatList = []
      e.currentPolygon.addEventListener('dblclick', this.dblclickPolygon) // 绘制完成给覆盖物添加双击事件
      this.currentLnglatList = e.currentLnglats
      this.mapDialogVisible = false
      this.$message.success('选址成功!')

    },
    dblclickPolygon(e) {
      this.currentPolygon = e.target // 把当前操作的覆盖物赋值给一个全局变量
      let menu = document.getElementById('right-btn')
      let evt = window.event || arguments[0]
      menu.style.left = evt.clientX - 220 + 'px'
      menu.style.top = evt.clientY - 60 + 'px'
      menu.style.visibility = 'visible'
    },
    //地图初始化
    onLoad() {
      var imageURL =
        'http://t0.tianditu.gov.cn/img_w/wmts?' +
        'SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles' +
        '&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=c8d9cd645bd34ae0fc54995e1f6c87e9'
      let zoom = 18
      let lay = new T.TileLayer(imageURL, {
        minZoom: 1,
        maxZoom: 18,
        unlimited: false, //1.设置缩放级别为整数
        constrainResolution: true,
        //2.关闭无级缩放地图
        smoothResolutionConstraint: false
      })
      var config = { layers: [lay] }
      this.map = new T.Map('mapDiv', config)
      this.map.centerAndZoom(new T.LngLat(116.935, 39.07), zoom)
      this.map.isDrag(false)
      this.map.disableInertia()
      this.map.disableKeyboard()
      this.map.disableDoubleClickZoom() // 禁止双击地图放大
      this.map.isDrag() // 禁止双击地图放大

      var points = []
      this.temporarilyList.forEach((item) => {
        points.push(new T.LngLat(item.latitude, item.longitude))
      })
      //创建面对象
      var polygon = new T.Polygon(points, {
        color: '#ccc',
        weight: 3,
        opacity: 0.5,
        fillColor: '#eee',
        fillOpacity: 0.5
      })
      //向地图上添加面
      this.map.addOverLay(polygon)
    }
  }
}
</script>

<style lang="scss" scoped>
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}

::v-deep .el-loading-mask {
  background-color: rgba(0, 222, 240, 0.2) !important;
}
::v-deep .el-loading-spinner {
  top: 65% !important;
}
::v-deep .el-loading-spinner i {
  font-size: 0.1513rem !important;
}

#mapDiv {
  width: 100%;
  height: 80vh;
}
#right-btn {
  visibility: hidden;
  position: absolute;
  top: 0px;
  left: 0px;
  z-index: 999;
  background-color: #fff;
  cursor: pointer;
  border: 1px solid #1e4048;
}
</style>
