<template>
  <div class="newDirectory H100">
    <div class="head_box">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>内容管理</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/serviceDirectoryPage'}">网点服务地图</el-breadcrumb-item>
        <el-breadcrumb-item>热点管理/{{form.name}}</el-breadcrumb-item>
      </el-breadcrumb>
      <h4>新增网点地图</h4>
    </div>
    <div class="content_box">
      <div class="reject_box" v-show="isShow == 1 || isShow == 6">
        <p><i></i><span>驳回原因:</span>&nbsp;  {{rejectReason}}</p>
      </div>
      <div class="map_content">
        <div class="map_content_left">
          <div class="scrool">
             <div>
              <el-table :data="hotSpotList" stripe style="width: 300px; height:calc(100% - 50px)"
                      @dblclick="toggleSelection(props.row,feature)">
              <el-table-column prop="name" label="热点名称"></el-table-column>
              <el-table-column label="操作" header-align="center" align="center">
                <template slot-scope="scope">
                  <el-button-group>
                    <el-button title="编辑" size="mini" type="text" @click="setMapCenterByFeature(scope.row)">定位 |
                    </el-button>
                    <el-button title="删除" type="text" size="mini" @click="handleDelete(scope.row)">删除</el-button>
                  </el-button-group>
                </template>
              </el-table-column>
            </el-table>
             </div>
          </div>
          <el-button @click="submit" style="float: right;margin: 10px 20px 0 0" size="mini" type="primary">提交</el-button>
        </div>
        <div class="map_content_right">
          <div id="map"></div>
          <div class="btn_group">
            <el-upload class="avatar-uploader" action=" " :show-file-list="false" name="headMap"
                       :before-upload="beforeHeadUpload" :http-request="handleUploadImg"
                       accept="image/gif, image/jpeg, image/png">
              <el-button size="mini" v-if="flag" type="primary" style="padding: 9px 15px;">上传底图</el-button>
            </el-upload>
            <el-button size="mini" v-if="!flag" @click="clearUploadImg" type="primary" style="padding: 9px 15px;">删除底图</el-button>
            <el-button class="button-new-tag" style="margin-left: 10px;" size="small" @click="drawFeature(POINT_TYPE)">添加热点</el-button>
            <el-button class="button-new-tag" size="small"  @click="drawFeature(POLYGON_TYPE)">添加热区</el-button>
          </div>
          <div id="popup" class="ol-popup portlet box">
            <div class="portlet-title">
              <div class="caption">
                <i class="icon icon-info-20"></i>
                <span class="caption-subject" v-show="hotSpot.type == POINT_TYPE">添加热点</span>
                <span class="caption-subject" v-show="hotSpot.type == POLYGON_TYPE">添加热区</span>
              </div>
              <div class="actions">
                <a href="#" id="popup-closer"  class="ol-popup-closer"></a>
              </div>
            </div>
            <div id="popup-content">
              <el-row>
                <el-form ref="form" :model="form" label-width="100px">
                  <el-col :span="24">
                    <el-form-item label="热点名称" v-show="hotSpot.type == POINT_TYPE" prop="name">
                      <el-input placeholder="请输入热点名称" size="mini" v-model="hotSpot.name" class="hotSpotNum"></el-input>
                    </el-form-item>
                    <el-form-item label="热区名称" v-show="hotSpot.type == POLYGON_TYPE" prop="name">
                      <el-input placeholder="请输入热区名称" size="mini" v-model="hotSpot.name" class="hotSpotNum"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24" >
                    <el-form-item  label="热点说明" v-show="hotSpot.type == POINT_TYPE">
                    <el-input  type="textarea" size="mini" :rows="2" style="height: 50px;"  placeholder="请输入对该热点的描述"  v-model="hotSpot.note"></el-input>
                    </el-form-item>
                    <el-form-item  label="热区说明" v-show="hotSpot.type == POLYGON_TYPE">
                    <el-input  type="textarea" size="mini" :rows="2" style="height: 50px;"  placeholder="请输入对该热区的描述"  v-model="hotSpot.note"></el-input>
                    </el-form-item>
                    <el-form-item  label="上传图标" v-show="hotSpot.type == POINT_TYPE" >
                      <el-upload class="avatar-uploader" name="headMap"  action="" :show-file-list="false"
                                 :before-upload="beforeAvatarUpload"
                                 :http-request="addPointImage"
                                 accept="image/gif, image/jpg, image/png">
                        <img v-if="hotSpot.imageUrl" :src="hotSpot.imageUrl" class="avatar" style="width: 70px;height: 70px">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        <div slot="tip" class="el-upload__tip" style="margin-top: -18px;min-width: 240px;">支持.png .jpg 格式, 大小要求 16px*16px</div>
                      </el-upload>
                    </el-form-item>
                    <div style="height:30px;line-height: 30px;text-align: right;padding-right: 10px;margin-top: 10px">
                      <el-button @click="clearFeature" size="mini">取消</el-button>
                      <el-button @click="saveFeature" size="mini" type="primary">保存</el-button>
                    </div>
                  </el-col>
                </el-form>
              </el-row>

            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>


<style>
  @import '../../js/openlayers/map.css';
  /*@import 'https://openlayers.org/en/v5.2.0/css/ol.css';*/
  @import '../../style/ol.css';

  .el-row.is-align-middle * {
    vertical-align: middle;
  }
</style>
<script>
  import {ColorChange} from '../../js/front/colorChange';
  import {createMap} from '../../js/front/map';
  import {startDataClass} from '../../js/front/getData';
  import {startDraw} from '../../js/front/drawFeature';
  import {FeatureStyle} from '../../js/front/FeatureStyle'
  import {ChangeBaseLayer} from '../../js/front/ChangeBaseLayer';
  import {Measure} from '../../js/tools/Measure';
  import store from '../../store'
  let mapControl;
  let maoObj;
  let drawFeatureObj;
  let editFeatureStyle;
  let changeBaseLayer;
  let measure;

  export default {
    inject: ['reload'],
    data() {
      return {
        rejectReason:"",
        isShow:"",
        flag: true,
        icon: '',
        dialogImageUrl: '',
        dialogVisible: false,
        formLabelWidth: "110px",
        tempImageLayer: null,
        POINT_TYPE: 'Point',
        POLYGON_TYPE: 'Polygon',
        hotSpotList: [],

        hotSpot: {
          id: null,
          type: "",// 1 ,2点还是面
          bankBranchId: null,
          name: "",
          note: "",
          coordinate: "",
          width: "",
          height: "",
          rotationAngle: "",
          imageUrl: ""  //图标地址
        },
        form: {
          id: null,
          name: "",
          imageUrl: '',
          width: '',
          height: '',
          bankQrCode: '',
        },
        inputVisible: false,
        inputValue: '',
      }
    },
    computed: {},
    beforeRouteLeave(to,from,next){
      //判断是否处于编辑状态
      let flag = true;
      if(this.hotSpot.type){
        flag = false;
      }
      if(!flag){
        this.$confirm('检测到未保存的内容,是否离开本页面?', '确认信息', {
          distinguishCancelAndClose: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
          .then(() => {
            ///路由不跳转
            sessionStorage.setItem('isModify',false)   //编辑不保留
            store.commit('setLeave',true);             //离开
            next()
          })
          .catch(action => {
            //路由跳转
            sessionStorage.setItem('isModify',true)   //编辑保留
            store.commit('setLeave',false);           //不离开
          });
      }else{
          next()
      }
    },
    mounted() {
      this.init();
    },

    watch:{
      isShow(val){
        if(val != 1 || val != 6){
          $('.map_content').css('height','96%')
          $('.map_content').css('margin-top','20px')
        }else{
          $('.map_content').css('height','calc(100% - 50px)')
          $('.map_content').css('margin-top','0px')
        }
      },
    },
    components: {},
    methods: {
      init() {
        let vm = this;
        vm.getParams();

        let colorChange = ColorChange();
        maoObj = createMap();
        mapControl = startDataClass(maoObj, this);
        drawFeatureObj = startDraw(maoObj, this);
        changeBaseLayer = new ChangeBaseLayer(vm, maoObj);
        measure = new Measure(vm, maoObj);
        editFeatureStyle = new FeatureStyle(this, maoObj);
        editFeatureStyle.setToken(vm.backToken);
        drawFeatureObj.setCilckCallBack(function (type, fe, event) {
          editFeatureStyle.popupWindow(type, event, fe)
        });
        vm.getFeatureList(false);
      },
      // 提交当前热点信息
      submit(){
        let vm = this;
        if(vm.form.imageUrl == ""){
          vm.$message({
            type: 'error',
            message: '当前没有可提交的内容,请添加后再提交!'
          });
        }else{
          vm.$confirm('是否已完成热点编辑, 并提交审核?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            vm.hotSpot.type = '';
            vm.$https({
              url: 'bankBranchInfo/submit?id='+vm.form.id,
              authType: vm.backToken,
              method: 'put'
            }).then((res) => {
              if(res.data.status== 201) {
                vm.$message({
                  type: 'success',
                  message: res.data.message
                });
                vm.$router.push('/serviceDirectoryPage');
              }
            }, (error) => {
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });
        }
      },
      //获取feature数据信息
      getFeatureList(isResh) {
        let vm = this;
        editFeatureStyle.getFeaturePageByLayerId(this.form.id, {}, function (data) {
          vm.hotSpotList = data;
          if (!isResh) {
            let layerData = {};
            layerData.id = vm.form.id;
            layerData.featureList = data
            vm.addLayerOnView(layerData);
          }

        });

      },

      getParams() {
        let vm = this;
        this.form.id = this.$route.query.pId;
        if (this.form.id) {
          this.hotSpot.bankBranchId = this.form.id;
          vm.$https({
            url: "bankBranchInfo/getById?id=" + this.form.id,
            method: 'get',
            authType: this.backToken
          }, {}).then((res) => {
            if (res.status == 200) {
              vm.form = res.data;
              vm.rejectReason = res.data.rejectReason;
              vm.isShow = res.data.isShow;
              if (vm.form.imageUrl) {
                vm.changeMapBaseLayerMap(vm.form);
              }
            }
          }).catch(function (err) {
          })
        }
      },
      //绘制
      drawFeature(type) {
        let vm = this;
        vm.clearn();
        vm.hotSpot.type = type;
        drawFeatureObj.addInteraction(type, function () {
          editFeatureStyle.closePopupWindow();
        });
      },

      clearn() {
        let vm = this;
        for (let key in  vm.hotSpot) {
          vm.hotSpot[key] = null;
        }
        this.hotSpot.bankBranchId = this.form.id;
      },

      //上传图标大小限制
      beforeAvatarUpload(file) {
        // let _this = this
        const isSize = new Promise(function (resolve, reject) {
          let width = 16;
          let height = 16;
          let _URL = window.URL || window.webkitURL;
          let img = new Image();
          img.onload = function () {
            let valid = img.width == width && img.height == height;
            valid ? resolve() : reject();
          }
          img.src = _URL.createObjectURL(file);
        }).then(() => {
          return file;
        }, () => {
          this.$message({
            type: 'error',
            message: '上传的icon必须是等于16*16!'
          });
          return Promise.reject();
        });
        return isSize
      },

      //上传图标
      addPointImage(file) {
        let vm = this;
        vm.createReader(file.file);
        vm.handleUpload(file.file).then(function (response) {
          vm.hotSpot.imageUrl = response.data.url;
          vm.changeImageStyle();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });

      },

      changeImageStyle() {
        //调用修改属性值方法
        editFeatureStyle.setFeatureStyle();
      },


      //文件上传   地图图片
      handleUploadImg(file) {
        let vm = this;
        if (!vm.form.id && vm.form.id.trim() == "") {
          vm.$message({
            type: 'fail',
            message: "操作失败!"
          });
          return;
        }
        vm.createReader(file.file);
        vm.handleUpload(file.file).then(function (response) {
          vm.form.imageUrl = response.data.url;
          var param = vm.$qs.stringify({
            id: vm.form.id,
            imageUrl: vm.form.imageUrl,
            width: vm.form.width,
            height: vm.form.height
          });
          vm.$https({
            url: 'bankBranchInfo/uploadImage',
            authType: vm.backToken,
            method: 'put'
          }, param).then((res) => {
            console.log(res);
            if(res.data.status== 201) {
              vm.$message({
                type: 'success',
                message: res.data.message
              });
            }
            vm.changeMapBaseLayerMap(response.data);
            vm.flag = false;
          }, (error) => {
          })

        })
      },
      clearUploadImg() {
        let vm = this;
        vm.$confirm('将要清除原有底图, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
        //编辑
          vm.$https({
            url: 'bankBranchInfo/deleteImage?id='+vm.form.id,
            authType: vm.backToken,
            method: 'delete'
          }).then((res) => {
            if(res.data.status== 201) {
              vm.$message({
                type: 'success',
                message: res.data.message
              });
              this.reload();
            }
          }, (error) => {
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
      },
      changeMapBaseLayerMap(data) {
        let extent = [0, 0, Number(this.form.width) / 1000, Number(this.form.height) / 1000,];
        if (data.imageUrl) {
          data.url = data.imageUrl;
          this.flag = false;
        }
        this.tempImageLayer = changeBaseLayer.setImageLayer(extent, data.url, this.tempImageLayer);
        maoObj.setCenterAndZoom([Number(this.form.width) / 2000, Number(this.form.height) / 2000], 9);
      },
      createReader(file) {
        let vm = this;
        var reader = new FileReader;
        reader.onload = function (evt) {
          var image = new Image();
          image.onload = function () {
            var width = this.width;
            var height = this.height;
            vm.form.width = width;
            vm.form.height = height;
          };
          image.src = evt.target.result;
        };
        reader.readAsDataURL(file);
      },

      handleUpload(file) {
        let vm = this;
        let formData = new FormData();
        formData.append("bc_cover", file);
        return new Promise(function (resolve, reject) {
          vm.$https({
            url: 'pic/upload',
            authType: vm.backToken,
            method: 'post'
          }, formData, 'file', 60000).then((res) => {
            resolve(res)
          }, (error) => {
          })
        })
      },
      beforeHeadUpload(file) { //底图文件
        const isLt30M = file.size / 1024 / 1024 < 30;
        if (!isLt30M) {
          this.$message.error('文件大小不能超过 30MB!');
        }
        this.hotSpot.type = 'UPLOAD_IMG';
        return isLt30M;
      },


      openEdit(data) {


      },
      handleDelete(data) {
        let vm = this;
        editFeatureStyle.deleteFeatureFromLayer(data.id, function (res) {
          changeBaseLayer.removeFeatureFromLayer(vm.form.id, data.id);
          vm.getFeatureList(true);
        });
      },
      //热点
      saveFeature() {
        let vm = this;
        if (!this.hotSpot.name || !this.hotSpot.note || this.hotSpot.name == ""|| this.hotSpot.note == "" ) {
          this.$message({
            type: 'error',
            message: '请输入热点或热区名称/说明!'
          });
          return;
        }

        if (/^\s+$/gi.test(this.hotSpot.name) || /^\s+$/gi.test(this.hotSpot.note)) {
          this.$message({
            type: 'error',
            message: '热点或热区名称和说明不能为空!'
          });
          return;
        }
        if(this.hotSpot.name.length > 10 || this.hotSpot.note.length > 100){
          this.$message({
            type: 'error',
            message: '热点或热区名称不超过10个字符,说明不超过100个字符!'
          });
          return;
        }
        if (vm.hotSpot.type == this.POINT_TYPE && (vm.hotSpot.imageUrl == "" || !vm.hotSpot.imageUrl)) {
          //如果是点则必须要加图标
          this.$message({
            type: 'error',
            message: '请上传热点图标!'
          });
          return;
        }
        if(vm.form.imageUrl == ""){
          this.$message({
            type: 'error',
            message: '请先上传底图!'
          });
          return;
        }
        let parameter = this.getParm();
        //保存数据  在相应的图层增加对应的feature 之后刷新列表
        editFeatureStyle.addFeature(parameter, function (res) {
          //succ
          drawFeatureObj.cleanModifyOrDraw();
          editFeatureStyle.closePopupWindow();
          let feData = res.data.data;
          let layer = changeBaseLayer.getLayerClassById(vm.form.id);
          if (layer) {
            layer.removeFeatureById(feData.id);//清除以前的feature  同一图层feature需要唯一
            layer.addfeature(feData);
          }

          vm.getFeatureList(true);
        }, function () {
          //fail

        });
      },
      clearFeature(){
        drawFeatureObj.cleanModifyOrDraw();
        editFeatureStyle.closePopupWindow();
      },
      getParm() {
        let subject = {};
        subject = JSON.parse(JSON.stringify(this.hotSpot));
        subject.coordinate = editFeatureStyle.getWkt();
        subject.bankBranchId = this.form.id;
        return subject;
      },
      cancel() {
        // 清除数据
        let vm = this;
        let modifyFe = editFeatureStyle.getFeature();
        if (modifyFe && modifyFe.getId() && modifyFe.get('data')) {
          //属于修改的部分
          let data = modifyFe.get('data');
          editFeatureStyle.deleteFeatureFromLayer(data.id, data.layerId, function () {
            drawFeatureObj.cleanModifyOrDraw();//删除之后清空绘制的地图  这个方法不需要提示
            editFeatureStyle.closePopupWindow();
            //从图层中移除数据
            changeBaseLayer.removeFeatureFromLayer(data.layerId, data.id);
            vm.$refs.controlPanel.refreshLayerData(data.layerId);
          })
        } else {
          //自定义编辑部分
          drawFeatureObj.cleanAllFeature(function () {
            //关闭弹出框
            editFeatureStyle.closePopupWindow();
          });
        }
      }
      ,
      setMapCenterByFeature(featureItem) {
        changeBaseLayer.getFeatureById(this.form.id, featureItem.id);
      },

      //热点底图
      addLayerOnView(data) {
        let vm = this;
        changeBaseLayer.changeLayerVisable(data, true, function (event, feature, layerName) {
          let modifyArr = drawFeatureObj.getModifyFeature();
          if (modifyArr && modifyArr.length > 0) {
            if (modifyArr[0].getId() == feature.getId()) {
              editFeatureStyle.popupModifyFeature(event, null);//沿用开始I编辑的和后面做区分
            } else {
              //清除以前修改的部分
              drawFeatureObj.remoaveEditFeature(function () {
                //点击确认清除之后
                drawFeatureObj.setEditFeature(feature);
                editFeatureStyle.popupModifyFeature(event, feature);
              });
            }
          } else {
            drawFeatureObj.setEditFeature(feature);
            editFeatureStyle.popupModifyFeature(event, feature);
          }

        });
      },
      getBack() {
        history.back(-1);
      }
    },
  }
</script>

<style lang="less">
  @import '../../style/common';
  .newDirectory {
    .content_box {
      position: relative;
      height: calc(100% - 97px);
      overflow-y: scroll;
      .reject_box{
        width:cale(100% - 40px);
        background: #fff;
        margin: 10px 20px;
        border-radius:4px;
        p{
          padding: 5px;
          i{
            width: 10px;
            height: 10px;
            display: inline-block;
            margin: 0px 10px;
            background: url("../../../static/images/icon/reject.png") no-repeat 100%;
          }
        }
      }
      .map_content {
        height: calc(100% - 50px);
        padding: 0px 20px;
        font-size: 0;
        .map_content_left {
          display: inline-block;
          float: left;
          width: 300px;
          height: 100%;
          border-top-left-radius: 4px;
          border-bottom-left-radius: 4px;
          background-color: #fff;
          .scrool {
            width: 100%;
            height: calc(100% - 48px);
            overflow-x: hidden;
            overflow-y: scroll;
          }
        }
        .map_content_right {
          position: relative;
          display: inline-block;
          width: calc(100% - 300px);
          height: 100%;
          border-top-right-radius: 4px;
          border-bottom-right-radius: 4px;
          background: url("../../../static/images/map-background.jpg");
          #map{
            width: 100%;
            height: 100%;
            background: url("../../../static/images/map-background.jpg") repeat;
            .ol-overlaycontainer-stopevent .ol-overlay-container.ol-selectable{
              #popup { /*窗体*/
                width: 374px;
                /*height: 325px;*/
                .portlet-title{
                  height: 40px;
                  line-height: 40px;
                  padding-left: 10px;
                  background-color: #409EFF;
                  border-bottom: 1px solid #E9E9E9;
                }
                #popup-content {
                  .el-row{
                    .el-form {
                      .el-col-24{
                        padding: 0px 10px;
                      }
                      .el-form-item {
                        margin-bottom: 10px;
                        .el-form-item__content{
                          width: calc(100% - 100px);
                          .avatar-uploader .el-upload {
                            width: 70px;
                            height: 70px;
                            border: 1px dashed #d9d9d9;
                            border-radius: 6px;
                            cursor: pointer;
                            position: relative;
                            overflow: hidden;
                            .el-icon-plus.avatar-uploader-icon {
                              line-height: 5;
                            }
                          }
                        }
                      }
                      .el-input__inner {
                        height: 32px;
                      }
                      .el-upload--picture-card {
                        width: 468px;
                        height: 270px;
                        line-height: 270px;
                      }
                    }
                    .dialog-footer {
                      text-align: center;
                      .el-button {
                        padding: 6px 13px;
                      }
                    }

                  }
                }
              }
            }
          }
          .btn_group {
            position: absolute;
            bottom: 10px;
            right: 20px;
            .avatar-uploader {
              display: inline-block
            }
          }
        }
      }
    }
  }


</style>