<template>
  <!-- 同屏对比弹窗 -->
  <el-dialog
    title="同屏对比"
    fullscreen
    v-loading="doPrintLoading"
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    @mousedown="changeMouseDownStatus(true)"
    @mouseup="changeMouseDownStatus(false)"
  >
    <template slot="title">
      <div class="dialogTitle">
        <div class="dialogTitleIcon"></div>
        同屏对比
      </div>
    </template>
    <!-- 同屏对比主题 -->
    <div class="ssc_main">
      <!-- 地图列表 -->
      <div class="ssc_main_mapList" id="doPrint" ref="doPrint">
        <div
          class="ssc_main_mapList_showList"
          :id="'map' + index"
          v-for="(mapIndex, index) in checkedCities"
          :key="index"
          :style="mapListBoxStyle()"
          @mouseover="changeMouseOverIndex(index)"
        >
          <span>{{ mapList[mapIndex].mapName }}</span>
          <Map
            ref="mapBox"
            :mapUrl="mapList[mapIndex].mapUrl"
            :index="index"
            :mouseIndex="mouseIndex"
            :centerZoom="centerZoom"
            :centerZoomInit="centerZoomInit"
            @changeCenterZoom="changeCenterZoom"
          />
        </div>
      </div>
      <!-- 底图列表 -->
      <div class="ssc_main_aimapList">
        <span>地图底图(最多选择6个) </span>
        <div>
          已选择<span class="checkLength">{{ checkedCities.length }}</span
          >个
        </div>
        <el-checkbox-group id="mapCheckBox" v-model="checkedCities" @change="handleCheckedCitiesChange" :min="2" :max="6">
          <el-checkbox
            class="mapCheckBox"
            :disabled="checkedCities.length >= 6 && checkedCities.indexOf(index) == -1"
            v-for="(city, index) in mapList"
            :checked="city.active"
            :label="index"
            :key="index"
            >{{ city.mapName }}</el-checkbox
          >
        </el-checkbox-group>
      </div>
    </div>
    <!-- 底部文本域 -->
    <div id="textareaBox">
      <div class="doPrintInfo">时间：{{ newTime }}</div>
      <div class="textareaTitle">描述记录:</div>
      <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 4 }" placeholder="请输入内容" v-model="textarea1"> </el-input>
    </div>
    <!-- 打印区域 -->
    <div id="imgBox">
      <span>基本农田被侵占</span>
      <img src="" id="imgOut" style="width: 1240px; background-repeat: no-repeat; background-size: 100% 100%" />
      <div class="doPrintInfo2">时间：{{ newTime }}</div>
      <span><div>描述记录:</div></span>
      <div>{{ textarea1 }}</div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="clearDialogVisible()">取 消</el-button>
      <el-button type="primary" @click="subMitDialogVisible()">打 印</el-button>
    </span>
  </el-dialog>
</template>

<script>
/**
 * 底部菜单（同屏对比）组件
 * @author: LiuMengxiang
 * @Date: 2022年11月21-25日
 */
import Map from "../../map/Map.vue";
import html2canvas from "html2canvas";
import { Canvg } from "canvg";
export default {
  name: "SameScreenComparison",
  components: { Map },
  data() {
    return {
      doPrintLoading: false,
      // 同屏对比弹窗显示状态
      dialogVisible: false,
      // 默认选中第一个
      checkedCities: [],
      // 定时器暂存
      interval: "",
      // 时间定时器暂存
      timeInterval: "",
      newTime: "",
      // 地图暂存显示变量
      centerZoom: {},
      // 外部地图暂存中心、层级信息
      centerZoomInit: {},
      // 当前光标是否为按下状态
      MouseDownStatus: false,
      // 光标作用的地图下标
      mouseIndex: -1,
      // 底部文本域
      textarea1: "",
      // 地图底图列表
      mapList: []
    };
  },
  created() {
    this.getBaseMap();
  },
  mounted() {
    // 同屏对比事件监听
    this.$bus.$off("tpdb");
    this.$bus.$on("tpdb", () => {
      this.changeShowBottomMenusStatus();
    });
    // 刷新实时时间
    if (!this.timeInterval) {
      this.timeInterval = setInterval(() => {
        this.newTime = this.$dayjs().format("YYYY-MM-DD HH:mm:ss");
      }, 1000);
    }
  },
  destroy() {
    // 当容器销毁时，需要停止监听该事件
    this.$bus.$off("tpdb");
    if (this.timeInterval) {
      clearInterval(this.timeInterval);
      this.timeInterval = "";
    }
  },
  props: [],
  methods: {
    // 获取地图底图服务
    getBaseMap() {
      this.mapList = [];
      let params = new FormData();
      params = {
        columnId: 35,
        states: 3,
        pageSize: 20,
        page: 0
      };
      this.$Post(this.urlsCollection.selectContentList, params).then(res => {
        if (res.code === 200 && res.content.data.length > 0) {
          let data = res.content.data;
          data.forEach(v => {
            this.mapList.unshift({
              mapName: v.title,
              mapUrl: v.c_url + "?AccessKey=lUaEMxqqhZKLSImGuP/Ergx47orYVyIqHVgxfyGpIurKAy9kdq5uU1cWuTuIXeOM",
              active: v.c_defined_show ? v.c_defined_show : false
            });
          });
        }
      });
    },

    // 当用户点击svg底座时，切换底部菜单显示隐藏状态。
    changeShowBottomMenusStatus() {
      // 打开弹窗
      this.dialogVisible = true;
      this.$emit("changeShowBottomMenusStatus", false);
      // 打开弹窗前首先同步一下地图定位
      let mapCenter = map2DViewer.map.getCenter();
      let mapZoom = map2DViewer.map.getZoom();
      if (mapCenter.lat && mapCenter.lng && mapZoom != undefined) {
        this.centerZoomInit = {
          lat: mapCenter.lat,
          lng: mapCenter.lng,
          zoom: mapZoom
        };
      }
      this.handleCheckedCitiesChange();
    },
    // 弹窗关闭询问
    handleClose() {
      if (this.dialogVisible) {
        this.clearDialogVisible();
      }
    },
    // 同屏对比取消
    clearDialogVisible() {
      // 关闭弹窗
      this.dialogVisible = false;
      // 获取地图光标暂存对象
      this.mouseIndex = -1;
      // 修改父级菜单变量（弹窗显示状态和显示底部菜单）
      this.$emit("changeShowBottomMenusStatus", true);
    },
    // 同屏对比表单提交
    subMitDialogVisible() {
      if (this.interval) {
        this.$message.info("正在打印，请稍后操作！");
      } else {
        this.cutDiv();
      }
    },
    // div转图片
    cutDiv() {
      try {
        this.doPrintLoading = true;
        var container = document.getElementById("doPrint").innerHTML;
        const _width = container.offsetWidth;
        const _height = container.offsetHeight;
        const ops = {
          _width,
          _height,
          useCORS: true,
          allowTaint: true
        };
        let that = this;
        let parentNodeList = [];
        let svgElemNodeList = [];
        let canvasList = [];
        //以下是对svg的处理(主要处理html2canvas插件显示SVG标签异常的问题)
        var svgElem = $("#doPrint").find("svg");
        svgElem.each(function (index, node) {
          var parentNode = node.parentNode;
          parentNodeList.push(parentNode);
          var svg = node.outerHTML.trim();
          svgElemNodeList.push(node);
          var canvas = document.createElement("canvas");
          canvas.className = "mapSvgCanvas";
          let cxt = canvas.getContext("2d");
          if (node.style.position) {
            canvas.style.position += node.style.position;
            canvas.style.left += node.style.left;
            canvas.style.top += node.style.top;
          }
          if (node.clientWidth && node.clientHeight) {
            canvas.setAttribute("width", node.clientWidth + "px");
            canvas.setAttribute("height", node.clientHeight + "px");
          }
          if (node.style.transform) {
            canvas.style.transform = node.style.transform;
          }
          const cv = Canvg.fromString(cxt, svg);
          cv.render();
          canvasList.push(canvas);
          // 隐藏原本的node元素
          parentNode.removeChild(node);
          // 添加svg转换后的canvas元素
          parentNode.appendChild(canvas);
        });
        // html2canvas插件实现dom转imageBase64
        html2canvas(this.$refs.doPrint, ops).then(
          canvas => {
            document.getElementById("imgOut").setAttribute("src", canvas.toDataURL("image/png"));
            setTimeout(() => {
              if (that.doPrintLoading) {
                that.doPrint(parentNodeList, svgElemNodeList, canvasList);
              }
            }, 1000);
          },
          error => {
            that.$message.error(error);
            this.showMapSvgAndRemoveMapCanvas(parentNodeList, svgElemNodeList, canvasList);
            this.doPrintLoading = false;
          }
        );
        setTimeout(() => {
          if (this.doPrintLoading) {
            this.$message.error("打印超时请稍后重试！");
            this.showMapSvgAndRemoveMapCanvas(parentNodeList, svgElemNodeList, canvasList);
            this.doPrintLoading = false;
          }
        }, 10000);
      } catch (e) {
        if (this.doPrintLoading) {
          this.$message.error("打印异常，异常信息：" + e);
          this.showMapSvgAndRemoveMapCanvas(parentNodeList, svgElemNodeList, canvasList);
          this.doPrintLoading = false;
        }
      }
    },
    // 显示原本的svg并删除svg转换为canvas的元素
    showMapSvgAndRemoveMapCanvas(parentNodeList, svgElemNodeList, canvasList) {
      try {
        parentNodeList.forEach((parentNodeListItem, index) => {
          parentNodeListItem.appendChild(svgElemNodeList[index]);
          parentNodeListItem.removeChild(canvasList[index]);
        });
      } catch (e) {
        this.$message.error("打印异常，异常信息：" + e);
        this.doPrintLoading = false;
      }
    },
    // div打印（iframe的方式为最优）
    doPrint(parentNodeList, svgElemNodeList, canvasList) {
      // 将包含转为图片的div获取。
      var new_iframe = document.createElement("IFRAME");
      var doc = null;
      document.body.appendChild(new_iframe);
      doc = new_iframe.contentWindow.document;
      var obj = document.getElementById("imgBox");
      doc.write(obj.innerHTML);
      doc.close();
      this.showMapSvgAndRemoveMapCanvas(parentNodeList, svgElemNodeList, canvasList);
      this.doPrintLoading = false;
      new_iframe.contentWindow.focus();
      new_iframe.contentWindow.print();
      document.body.removeChild(new_iframe);
    },
    // 修改选中地图
    handleCheckedCitiesChange(e) {
      setTimeout(() => {
        this.checkedCities.forEach((item, index) => {
          this.$refs["mapBox"][index].$nextTick(() => {
            this.$refs["mapBox"][index].changeMapSize();
            this.$refs["mapBox"][index].addSinglePolygon(false);
          });
        });
      }, 300);
    },
    // 根据地图列表，返回合适的样式
    mapListBoxStyle() {
      if (this.checkedCities.length >= 5) {
        return "width:calc(33% - 2px);height:calc(50% - 2px);";
      } else if (this.checkedCities.length === 4) {
        return "width:calc(50% - 2px);height:calc(50% - 2px);";
      } else if (this.checkedCities.length === 3) {
        return "width:calc(33% - 2px);height:calc(100%);";
      } else if (this.checkedCities.length === 2) {
        return "width:calc(50% - 2px);height:calc(100%);";
      } else {
        return "width:calc(100%);height:calc(100%);";
      }
    },
    // 当其中一个地图移动或缩放时
    changeCenterZoom(data) {
      this.centerZoom = data;
    },
    // 暂存当前光标所在map组件的下标
    changeMouseDownStatus(status) {
      this.MouseDownStatus = status;
    },
    changeMouseOverIndex(mouseIndex) {
      // 当鼠标按下后（this.MouseDownStatus = true）暂存当前光标所在map组件的下标将不再修改
      if (!this.MouseDownStatus) {
        this.mouseIndex = mouseIndex;
      }
    }
  },
  watch: {}
};
</script>
<style lang="less" scoped>
.ssc_main {
  display: flex;
  width: 100%;
  height: calc(100vh - 310px);
  position: relative;
  #textareaBox {
    width: calc(100% - 20px);
    height: 100px;
    position: absolute;
    bottom: 0;
  }
  &_mapList {
    width: calc(100% - 20rem);
    height: 100%;
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    box-sizing: border-box;
    overflow-x: hidden;
    overflow-y: auto;
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* IE 10+ */
    &::-webkit-scrollbar {
      display: none; /* Chrome Safari */
    }
    &_showList {
      border: 1px solid #ccc;
      text-align: right;
      position: relative;
      span {
        position: absolute;
        right: 10px;
        top: 10px;
        font-size: 22px;
        font-weight: bold;
        color: #fff;
        z-index: 999;
        -moz-user-select: none;
        -webkit-user-select: none;
        -ms-user-select: none;
        -khtml-user-select: none;
        user-select: none;
      }
    }
  }
  &_aimapList {
    width: 20rem;
    height: 100%;
    font-size: 20px;
    color: #fff;
    padding: 10px;
    box-sizing: border-box;
    background: #002645 !important;
    .checkLength {
      font-size: 24px;
      color: #74ffff;
    }
    #mapCheckBox {
      height: calc(100% - 58px);
      width: 100%;
      overflow-x: hidden;
      overflow-y: auto;
      scrollbar-width: none; /* Firefox */
      -ms-overflow-style: none; /* IE 10+ */
      border: 1px solid #fff;
      &::-webkit-scrollbar {
        display: none; /* Chrome Safari */
      }
    }
    .mapCheckBox:hover {
      color: #ffffff;
      background: #002645 !important;
    }
    .mapCheckBox[disabled] {
      color: #666666;
      cursor: not-allowed;
    }
    .mapCheckBox {
      width: 100%;
      padding: 10px 5px;
      border-bottom: 1px solid;
      color: #cccccc;
      font-size: 18px;
      background: #001e37 !important;
      .el-checkbox__label {
        font-size: 18px;
      }
    }
  }
}
.textareaTitle {
  font-size: 20px;
  font-weight: 400;
}
#imgBox {
  display: none;
  font-size: 16px;
  color: #000;
  font-weight: 400;
  span {
    font-size: 20px;
    color: #000000;
    font-weight: bold;
    padding: 20px 10px;
  }
}
.doPrintInfo {
  color: #ffffff;
}
.doPrintInfo2 {
  color: #000000;
}
</style>
