<template>
  <div id="baseEditer" ref="graphy">
    <div id="fengMap"></div>
    <div class="canvas-container">
      <canvas id="canvas" :width="canvasWidth" :height="canvasHeight" ref="canvas" tabindex="0"></canvas>
    </div>
  </div>
</template>
<script>
import { SFengParser } from "@saga-web/feng-map";
import { SFloorParser } from "@saga-web/big";
import { FloorView } from "./../lib/FloorView";
import { EditScence } from "./mapClass/EditScence";
import bus from "@/bus";
import { saveGroup, readGroup } from "@/api/editer.js";
import { STopologyParser } from "./../lib/parsers/STopologyParser";
import { uuid } from "@/components/mapClass/until";
import { SImageItem } from '@saga-web/graph/lib'
import store from "../store";

let fengmap = null;

export default {
  props: {
    cmdType: {
      type: String,
      default: "choice",
      required: false
    },
    changeTextMsg: {
      type: String,
      default: "",
      required: false
    }
  },
  data() {
    return {
      appName: "万达可视化系统",
      key: "23f30a832a862c58637a4aadbf50a566",
      mapServerURL: "/wdfn",
      canvasWidth: 700,
      canvasHeight: 800,
      fParser: null,
      scene: null,
      view: null,
      floorList: {},
      urlMsg: {}
    };
  },
  mounted() {
    this.canvasWidth = this.$refs.graphy.offsetWidth;
    this.canvasHeight = this.$refs.graphy.offsetHeight - 10;
    this.init();
    // 挂在bus
    this.getBus();
    store.dispatch("getElementType", { PageSize: 1000 });
  },
  methods: {
    init() {
      // const loadings = this.$loading({type: 'global'});
      document.getElementById(`canvas`).focus();
      this.clearGraphy();
      this.scene = new EditScence();
      fengmap = new SFengParser(
        "fengMap",
        this.mapServerURL + "/fmap/" + this.urlMsg.fmapID,
        this.key,
        this.appName,
        null
      );
      console.log(this.urlMsg.fmapID)
      const floorid = this.urlMsg.FloorID;
      fengmap.loadMap(this.urlMsg.fmapID, resp => {
        this.floorList = resp;
        fengmap.loadTheme(`${this.mapServerURL}/webtheme/${this.urlMsg.fmapID}/${this.urlMsg.fmapID}.theme`).then(response => {
          console.log('获取rf成功', response)
          this.parserData(floorid);
        })
        this.view.fitSceneToView();
      });
      // 获取主题数据
      this.readGroup().then(data => {
        const parserData = new STopologyParser(null);
        parserData.parseData(data.data.Data[0].Elements);
        // 多边形
        parserData.zoneLegendList.forEach(t => {
          this.scene.addItem(t);
          this.scene.Nodes.push(t);
        });
        // 增加文字
        parserData.textMarkerList.forEach(t => {
          this.scene.addItem(t);
          this.scene.Markers.push(t);
        });
        // 增加图片
        parserData.imageMarkerList.forEach(t => {
          this.scene.addItem(t);
          this.scene.Markers.push(t);
        });
        // 增加直线
        parserData.lineMarkerList.forEach(t => {
          this.scene.addItem(t);
          this.scene.Markers.push(t);
        });
        // 增加图标类图例
        parserData.imageLegendList.forEach(t => {
          this.scene.addItem(t);
          this.scene.Nodes.push(t);
        });
        // 增加管线类
        // 增加图标类图例
        parserData.relationList.forEach(t => {
          this.scene.addItem(t);
          this.scene.Relations.push(t);
        });
        this.view.fitSceneToView();
      });

      this.scene.emitChange = this.emitChange;
    },
    parserData(floor) {
      if (floor == 'g80') {
        // 屋顶
        if (fengmap.frImg) {
          const imgItem = new SImageItem(null, `${this.mapServerURL}/webtheme/${this.urlMsg.fmapID}/${fengmap.frImg}`)
          this.scene.addItem(imgItem)
          this.view.scene = this.scene
          this.view.fitSceneToView()
          this.loading = false
          this.isQuerying = false
        }
      } else {
        if (this.floorList[floor]) {
          fengmap.parseData(this.floorList[floor], res => {
            if (res.err) {
              console.log(res.err);
              return;
            }
            this.fParser = new SFloorParser(null);
            this.fParser.parseData(res);
            this.fParser.spaceList.forEach(t => {
              t.selectable = true;
              this.scene.addItem(t);
            });
            this.fParser.wallList.forEach(t => this.scene.addItem(t));
            this.fParser.virtualWallList.forEach(t => this.scene.addItem(t));
            this.fParser.doorList.forEach(t => this.scene.addItem(t));
            this.fParser.columnList.forEach(t => this.scene.addItem(t));
            this.fParser.casementList.forEach(t => this.scene.addItem(t));
            this.view.scene = this.scene;
            this.view.fitSceneToView();
            this.loading = false;
            this.isQuerying = false;
            console.log("success");
          });
        } else {
          console.log("楼层不正确");
        }
      }
    },
    // 监听变化
    emitChange(itemMsg) {
      this.$emit("changeFocusItem", itemMsg);
      bus.$emit("FocusItemChanged", itemMsg);
    },
    clearGraphy() {
      if (this.view) {
        this.view.scene = null;
        return;
      }
      this.view = new FloorView("canvas");
      document.getElementById("canvas").focus();
    },
    getBus() {
      bus.$on("changeText", val => {
        this.scene.updatedText(val);
      });
      bus.$on("changeFont", val => {
        this.scene.updatedFontSize(val);
      });
      bus.$on("changeLineWidth", val => {
        this.scene.updatedLineWidth(val);
      });
      bus.$on("changeBorderColor", val => {
        this.scene.updatedBorderColor(val);
      });
      bus.$on("changeFontColor", val => {
        this.scene.updatedFontColor(val);
      });
      bus.$on("changeFontColor", val => {
        this.scene.updatedFontColor(val);
      });
      bus.$on("itemWidth", val => {
        this.scene.updatedWidth(Number(val));
      });
      bus.$on("itemHeight", val => {
        this.scene.updatedHeight(Number(val));
      });
      bus.$on("itemPositon", (x, y) => {
        this.scene.updatedPosition(Number(x), Number(y));
      });
      bus.$on("changebackColor", val => {
        this.scene.updatedbackColor(val);
      });
      bus.$on("deleiteItem", () => {
        this.scene.deleiteItem();
      });
      bus.$on("changeAlignItem", val => {
        this.scene.changeAlignItem(val);
      });
      bus.$on("extractItem", () => {
        const map = {};
        this.fParser.spaceList.forEach(t => {
          if (map[t.data.Type]) {
            map[t.data.Type]++;
          } else {
            map[t.data.Type] = 1;
          }
        });
        const data = [];
        for (const key in map) {
          data.push({
            key: key,
            name: key,
            age: "",
            number: map[key],
            address: "提取"
          });
        }
        bus.$emit("exportItem", data);
      });
      bus.$on("saveMsgItem", () => {
        const Elements = this.scene.saveMsgItem();
        const data = {
          Elements,
          Name: this.appName, // 名称
          categoryId: this.urlMsg.categoryId,
          ProjectID: this.urlMsg.projectId, // 项目ID
          BuildingID: this.urlMsg.BuildingID, // 建筑ID
          FloorID: this.urlMsg.FloorID // 楼层id
        };
        saveGroup(data).then(res => {
          console.log("aaaaaaaaaaaaaa", res);
        });
      });
      bus.$on("exportByKey", val => {
        const list = this.fParser.spaceList
          .map(t => {
            if (t.data.Type == val.key) {
              return {
                ID: uuid(),
                Name: val.name,
                GraphElementType: val.properties.Type,
                GraphElementId: "273d633cc5c54a4882794b34843d1a00",
                AttachObjectIds: [],
                Pos: { x: t.x, y: t.y },
                OutLine: t.pointArr[0],
                Properties: {
                  strokeColor: "#3d73c0",
                  fillColor: "#eda986"
                },
                Num: 123
              };
            }
          })
          .filter(item => item);
        const parserData = new STopologyParser(null);
        parserData.parseData({ Nodes: list });
        parserData.zoneLegendList.forEach(t => {
          this.scene.addItem(t);
          this.scene.Nodes.push(t);
        });
      });
      // 设备图例样式对象
      bus.$on("setLenged", obj => {
        this.scene.setlegend = obj;
      });
      //  修改图片url
      bus.$on("upadataImageUrl", val => {
        this.scene.upadataImageUrl(val);
      });
      // 改变边框样式
      bus.$on("changeBorder", val => {
        this.scene.upadataBorder(val);
      });
      // 改变图例名称
      bus.$on("changeLengedName", val => {
        this.scene.upadataLengedName(val);
      });
    },
    // 读取数据
    readGroup() {
      const data = {
        categoryId: this.urlMsg.categoryId,
        projectId: this.urlMsg.projectId
      };
      return readGroup(data);
    }
  },
  watch: {
    cmdType: {
      handler(cmd) {
        if (cmd == null || cmd == "") {
          cmd = "choice";
        }
        this.scene.setCmd = cmd;
      },
      deep: true
    },
    "scene.cmd": {
      handler(cmd) {
        this.$emit("setCmdType", cmd);
      },
      deep: true
    }
  },
  created() {
    const href = window.location.href;
    // 路由
    // const route = href.split("?")[0];
    // 参数处理
    let params = href.split("?")[1];
    if (!params) {
      // 参数有问题
      return false
    }
    params = decodeURIComponent(params);
    // params = "categoryId=NTXT&ProjectID=5&BuildingID=1&FloorID=1"; // mock 参数
    const paramsArr = params.split("&");
    console.log('paramsArr', paramsArr)
    const obj = {};
    paramsArr.map(item => {
      const arr = item.split("=");
      obj[arr[0]] = arr[1];
    });
    this.urlMsg = obj;
    /**
 * obj:

 */
  }
};
</script>
<style lang="less" scoped>
#baseEditer {
  background: #f7f9fa;
  width: 100%;
  height: 100%;
  // overflow: hidden;
  // position: relative;
  #fengMap {
    position: absolute;
    width: 100px;
    height: 100px;
    z-index: -1;
  }
  .canvas-container {
    width: 100%;
    height: 100%;
  }
}
</style>