<template>

    <div id="drafts">
      <a-spin :spinning="spinning">
      <div class="tit">草稿箱</div>
      <div class="conent">
        <div class="left-nav">
          <!--        <Tree :data="treeData" @change="change"></Tree>-->
          <el-tree :data="treeData" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
        </div>
        <div class="conent-right">
          <div class="conent-tit">
            <div class="tit-left" v-if="floorName">{{systemName}}-{{floorName}}</div>
            <div class="tit-right">
              <a-button @click="deleteBtn" :disabled="!floorName">删除</a-button>
              <a-button @click="publishBtn" :disabled="!floorName">发布</a-button>
              <a-button type="primary" @click="goToEditer" :disabled="!floorName">编辑</a-button>
            </div>
          </div>
          <div class="concent-bottom">
            <div class="map">
              <div class="canvas-container" ref="draftsCanvas">
                <div id="fengMap"></div>
                <canvas
                  id="canvas"
                  :width="canvasWidth"
                  :height="canvasHeight"
                  ref="canvas"
                  tabindex="0"
                ></canvas>
              </div>
            </div>
            <div v-show="!legend" class="legend-btn" @click="legend = !legend">
              <a-icon type="right" style="color: #8D9399;font-size: 10px" />
            </div>
            <div v-show="legend" class="legend-btn legend-btn-close" @click="legend = !legend">
              <a-icon type="right" style="color: #8D9399;font-size: 10px" />
            </div>
            <div class="legend" v-if="legend">
              <div
                style="font-size:14px;color: #1F2429;padding-left: 12px;height: 40px;line-height: 40px"
              >可能需要补充的图例</div>
              <a-table
                v-loading="legendLoading"
                :columns="columns"
                :rowKey="(record,index)=>{return index}"
                :data-source="legendData"
                size="middle"
                :pagination="false"
              >
                <div slot="Url" slot-scope="text,record">
                  <img
                    v-if="record.Url"
                    style=" width: 20px;height: 22px;"
                    :src="'/serve/topology-wanda/Picture/query/'+ record.Url"
                    alt
                  />
                  <span v-else>---</span>
                </div>
                <span></span>
              </a-table>
            </div>
          </div>
        </div>
      </div>
      </a-spin>
    </div>

</template>
<script>
import Tree from "./../components/Tree/Tree.vue";
import { SFengParser } from "@saga-web/feng-map";
import { SFloorParser } from "@saga-web/big";
import { FloorView } from "./../lib/FloorView";
import { EditScence } from "@/components/mapClass/EditScence";
import bus from "@/bus";
import {
  readGroup,
  queryDraftGroup,
  queryStatistic,
  deleteGraph,
  publishGraph
} 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 {
  components: { Tree },
  data() {
    return {
      treeData: [],
      columns: [
        {
          title: "名称", // 列的名称
          dataIndex: "Name", // 列的标识
          scopedSlots: { customRender: "Name" }
        },
        {
          title: "图例", // 列的名称
          dataIndex: "Url", // 列的标识
          scopedSlots: { customRender: "Url" }
        }
      ],
      legendData: [],
      legend: true,
      canvasWidth: 700,
      canvasHeight: 600,
      view: null,
      urlMsg: null,
      floorList: {},
      mapServerURL: "/wdfn",
      key: "23f30a832a862c58637a4aadbf50a566",
      appName: "万达可视化系统",
      defaultProps: {
        children: "Category",
        label: "Gcode"
      },
      projectId: "", //项目id
      fmapID: "", //蜂鸟地图id
      graphId: "", //绘制生成得图id
      legendLoading: false,
      spinning: false, //全局加载
      systemName: "",
      floorName: "",
      BuildingID: "1", // 建筑id
      categoryId: "" //系统类id
    };
  },
  methods: {
    handleNodeClick(data, node) {
      this.legendData = [];
      this.systemName = "";
      this.floorName = "";
      if (data.Gname) {
        this.systemName = node.parent.data.Gcode;
        this.floorName = data.Gcode;
        console.log(node.parent.data.Id)
        this.categoryId = node.parent.data.Id;
        this.getLegend();
        this.checkFloor(data.Gname);
      }
    },
    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.fmapID,
        this.key,
        this.appName,
        null
      );
    },
    clearGraphy() {
      if (this.view) {
        this.view.scene = null;
        return;
      }
      this.view = new FloorView("canvas");
      document.getElementById("canvas").focus();
    },
    parserData(floor) {
      if (floor == "g80") {
        // 屋顶
        if (fengmap.frImg) {
          const imgItem = new SImageItem(
            null,
            `${this.mapServerURL}/webtheme/${this.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("楼层不正确");
        }
      }
    },
    getTreeData() {
      queryDraftGroup({ projectId: this.projectId }).then(res => {
        console.log(res);
        if (res.Result == "success") {
          this.treeData = res.Data;
        } else {
          this.treeData = [];
          this.$message.error("获取楼层结构失败");
        }
      });
    },
    //获取补充图例
    getLegend() {
      this.legendLoading = true;
      this.legendData = [];
      queryStatistic({
        projectId: this.projectId,
        flag: true,
        graphId: this.graphId
      }).then(res => {
        console.log(res);
        this.legendLoading = false;
        if (res.data.Result == "success") {
          const data = res.data.Data;
          data.map(item => {
            if (item.RealNum == 0) {
              this.legendData.push(item);
            }
          });
        } else {
          this.legendData = [];
          this.$message.error("获取楼层结构补充图例失败");
        }
      });
    },
    //删除
    deleteBtn() {
      this.spinning = true;
      deleteGraph([{ Id: this.graphId }]).then(res => {
        console.log(res);
        this.spinning = false;
        if (res.Result == "success") {
          this.$message.success('删除成功');
        } else {
          this.$message.error(res.Message);
        }
      });
    },
    //发布
    publishBtn() {
      this.spinning = true;
      publishGraph({ graphId: this.graphId, pubUser: "" }).then(res => {
        this.spinning = false;
        if (res.Result == "success") {
          this.$message.success(res.Message);
        } else {
          this.$message.error(res.Message);
        }
      });
    },
    // 读取数据
    readGroup(floorid) {
      const data = {
        categoryId: this.categoryId,
        projectId: this.projectId,
        BuildingID: this.BuildingID, // 建筑ID
        FloorID: floorid, // 楼层id
        Pub:false   //是否获取草稿 //获取草稿
      };
      return readGroup(data);
    },
    /**
     * @name goToEditer
     * @description t跳转editer编辑器
     */
    goToEditer() {
      console.log(this.$cookie);
      const FloorID = this.$cookie.get("floorMapId") || "f1";
      const categoryId = this.$cookie.get("categoryId");
      const { conf } = window.__systemConf,
        { editerUrl } = conf;
      const data = `categoryId=${categoryId}&projectId=${this.plazaId}&BuildingID=1&FloorID=${FloorID}&fmapID=${this.fmapID}`;
      const url = editerUrl + "editer?" + encodeURIComponent(data);
      window.open(url, true);
    },
    // 切换草稿箱楼层
    checkFloor(floorid) {
      fengmap.loadMap(this.fmapID, resp => {
        this.floorList = resp;
        fengmap
          .loadTheme(
            `${this.mapServerURL}/webtheme/${this.fmapID}/${this.fmapID}.theme`
          )
          .then(response => {
            console.log("获取rf成功", response);
            this.parserData(floorid);
          });
        this.view.fitSceneToView();
        // 获取
        // 获取主题数据
        this.readGroup(floorid).then(data => {
          this.graphId = data.Data[0].ID;
          if (data.Data) {
            const parserData = new STopologyParser(null);
            parserData.parseData(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();
          }
        });
      });
    }
  },
  mounted() {
    this.canvasWidth = this.$refs.draftsCanvas.offsetWidth - 10;
    this.canvasHeight = this.$refs.draftsCanvas.offsetHeight - 10;

    const href = window.location.href;
    let params = href.split("?")[1];
    if (!params) {
      // 参数有问题
      return false;
    }
    params = decodeURIComponent(params);
    const paramsArr = params.split("&");
    const obj = {};
    paramsArr.map(item => {
      const arr = item.split("=");
      obj[arr[0]] = arr[1];
    });
    console.log("obj", obj);
    this.projectId = obj.projectId ? obj.projectId : "1000423";
    this.fmapID = obj.fmapID ? obj.fmapID : "1000423_120";
    this.init();
    this.getTreeData();
  }
};
</script>
<style lang="less" scoped>
  /deep/ .ant-spin-nested-loading{
    height: 100% !important;
   .ant-spin-container{
     height: 100% !important;
   }
  }
#drafts {
  widows: 100%;
  height: 100%;
  background: #f7f9fa;
  position: relative;
  .tit {
    width: 100%;
    height: 48px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-bottom: #e4e5e7 solid 1px;
    font-size: 16px;
    font-weight: bold;
  }
  .conent {
    width: 100%;
    height: calc(100% - 48px);
    display: flex;
    position: relative;

    .left-nav {
      width: 224px;
      height: 100%;
      overflow-y: scroll;
      padding: 0 12px;
      /deep/ .el-tree {
        background: #f7f9fa;
        .el-tree-node__content {
          height: 38px;
        }
        /deep/.el-tree-node:focus > .el-tree-node__content {
          background-color: #e1f2ff !important;
          color: #0091ff !important;
        }
      }
    }
    .conent-right {
      flex: 1;
      height: 100%;
      background: #fff;
      .conent-tit {
        width: 100%;
        display: flex;
        height: 59px;
        border: 1px solid #eff0f1;
        align-items: center;
        justify-content: space-between;
        padding: 0 16px 0 16px;
        box-sizing: border-box;
        .tit-left {
          font-size: 16px;
          font-weight: bold;
          color: rgba(31, 35, 41, 1);
        }
        .tit-right {
          width: 246px;
          display: flex;
          justify-content: space-between;
          margin-left: auto;
        }
      }
      .concent-bottom {
        height: calc(100% - 61px);
        display: flex;
        position: relative;
        .map {
          flex: 1;
          position: relative;
          height: 100%;
          /*height: calc(100% - 61px);*/
          /*background: red;*/
        }
        .legend {
          position: absolute;
          right: 0;
          top: 0;
          width: 200px;
          border-left: 1px solid #eff0f1;
          height: 100%;
          overflow-y: scroll;
        }
        .legend-btn {
          position: absolute;
          right: 0px;
          top: 9px;
          width: 10px;
          height: 24px;
          background: rgba(228, 229, 231, 1);
          display: flex;
          justify-content: center;
          align-items: center;
          cursor: pointer;
        }
        .legend-btn-close {
          right: 200px;
        }
      }
    }
  }
}
#fengMap {
  position: absolute;
  width: 100px;
  height: 100px;
  z-index: -1;
}
.canvas-container {
  width: 100%;
  height: 100%;
}
</style>