<template>
  <div id="drafts">
    <div class="tit">草稿箱</div>
    <div class="conent">
      <div class="left-nav">
        <Tree :data="treeData" @change="change" v-if="treeData.length"></Tree>
        <div v-else style="text-align: center;margin-top: 20px;">暂无数据</div>
        <!--          <el-tree ref="tree" :data="treeData" :props="defaultProps" @node-click="handleNodeClick"  node-key="id"    :expand-on-click-node="false"-->
        <!--                   :current-node-key="currentNodekey"-->
        <!--                   :default-expanded-keys="expandedkeys">-->
        <!--            <span class="span-ellipsis" slot-scope="{ node, data }">-->
        <!--		<span :title="node.label">{{ node.label }}</span>-->
        <!--	</span>-->
        <!--          </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="modalStatusTip=!modalStatusTip;grouptype='checked';grouptype1='uncheck';" :disabled="!floorName">删除</a-button>
<!--            <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="left" 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>
    <Modal
            :show="modalStatusTip"
            title="确定要删除吗？"
            mode="tip"
            type="error"
            @close="modalClose"
    >
      <template #content>
        <div style="font-size: 15px; padding-left: 16px;padding-top: 16px;"  v-if="categoryId=='XFBFYCFL'||categoryId=='FZQZL'" >
          <Radio :checked="grouptype" @change="grouptype='checked';grouptype1='uncheck'" >仅删除草稿</Radio>
          <br>
          <Radio :checked="grouptype1"  @change="grouptype1='checked';grouptype='uncheck'" >删除草稿和已发布的原理图</Radio>
<!--          <radio-group  v-if="categoryId=='XFBFYCFL'||categoryId=='FZQZL'" :group-data.sync="groupData" :type="grouptype" @change="handleChange" />-->
        </div>
      </template>
      <template #handle>
        <Button @click="modalClose" type="default">取消</Button>
        <Button @click="modalConfirm" type="error">确定</Button>
      </template>
    </Modal>
  </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,
  deleteByCategory
} 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";
import { Loading } from "element-ui";
import { getUrlMsg } from "@/components/urlMsg.js";
let fengmap = null;
export default {
  components: { Tree },
  data() {
    return {
      modalStatusTip:false,
      grouptype:'checked',
      grouptype1:'uncheck',
      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: "http://map.wanda.cn/editor",
      mapthemeUrl: `http://map.wanda.cn/editor/webtheme`,
      key: "23f30a832a862c58637a4aadbf50a566",
      appName: "万达可视化系统",
      defaultProps: {
        children: "Category",
        label: "Gcode"
      },
      projectId: "", //项目id
      fmapID: "", //蜂鸟地图id
      graphId: "", //绘制生成得图id
      legendLoading: false,
      systemName: "",
      floorName: "",
      floorId: "", //楼层id
      BuildingID: "1", // 建筑id
      categoryId: "", //系统类id
      currentNodekey: "", //默认选中的节点树
      expandedkeys: [] //默认展开的节点树
    };
  },
  methods: {
    // handleNodeClick(data, node) {
    //   this.legendData = [];
    //   this.systemName = "";
    //   this.floorName = "";
    //   if (data.Gname) {
    //     this.systemName = node.parent.data.Gcode;
    //     this.floorName = data.Gcode;
    //     this.floorId = data.Gname;
    //     this.categoryId = node.parent.data.Id;
    //     this.getLegend();
    //     this.checkFloor(data.Gname);
    //   }
    // },
    //初始化获取蜂鸟所有底图数据
    init() {
      const loadings = Loading.service({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      // const loadings = this.$loading({type: 'global'});
      document.getElementById(`canvas`).focus();
        if(this.fmapID.includes('null')){
          loadings.close();
          this.getTreeData();
      }
      fengmap = new SFengParser(
        "fengMap",
        this.mapServerURL + "/fmap/" + this.fmapID,
        this.key,
        this.appName,
        null,
        this.mapthemeUrl
      );
      fengmap.loadMap(this.fmapID, resp => {
        this.floorList = resp;
        fengmap
          .loadTheme(
            `${this.mapServerURL}/webtheme/${this.fmapID}/${this.fmapID}.theme`
          )
          .then(response => {
            // 获取楼层数据数据
            loadings.close();
            this.getTreeData();
          });
      });
    },
    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.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("楼层不正确");
        }
      }
    },
    change(id) {
      console.log(id);
      const data = this.treeData;
      (function recursion(newObj) {
        newObj.map(function(item, index) {
          item.open = false;
          item.checked = false;
          if (item.Category && item.Category.length > 0) {
            item.children = item.Category;
            recursion(item.Category);
          }
        });
      })(data);
      let items = null;
      data.forEach(ele => {
        ele.children.forEach(item => {
          ele.open = true;
          if (item.children) {
            item.children.forEach(item1 => {
              item.open = true;
              if (item1.id == id.id) {
                items = item;
                item1.checked = "checked";
              }
            });
          } else {
            if (item.id == id.id) {
              items = ele;
              ele.open = true;
              item.checked = "checked";
            }
          }
        });
      });
      this.legendData = [];
      this.systemName = "";
      this.floorName = "";
      this.systemName = items.Gcode;
      this.floorName = id.Gcode;
      this.floorId = id.Gname;
      this.categoryId = items.Id;
      // this.getLegend();
      this.checkFloor(id.Gname);
      console.log(items);
    },
    getTreeData() {
      const loadings = Loading.service({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      queryDraftGroup({ projectId: this.projectId })
        .then(res => {
          console.log(res);
          loadings.close();
          if (res.Result == "success") {
            const data = res.Data;
            this.systemName = "";
            this.floorName = "";
            this.floorId = "";
            this.categoryId = "";
            if (data.length) {
              (function recursion(newObj) {
                newObj.map(function(item, index) {
                  item.id = item.Id || item.Gname;
                  item.name = item.Gcode;

                  item.checked = false;
                  if (item.Category && item.Category.length > 0) {
                    item.children = item.Category;
                    item.open = false;
                    recursion(item.Category);
                  }
                });
              })(data);
              data.forEach(ele => {
                ele.children.forEach(item => {
                  ele.open = true;
                  if (item.children) {
                    item.open = true;
                    item.children.forEach(item1 => {
                      item1.id = item.Id + item1.Gname;
                    });
                  } else {
                    item.id = ele.Id + item.Gname;
                  }
                });
              });
              this.treeData = data;
              if (this.treeData[0].children[0].children) {
                this.treeData[0].open = true;
                this.treeData[0].children[0].open = true;
                this.treeData[0].children[0].children[0].checked = "checked";
                this.systemName = this.treeData[0].children[0].Gcode;
                this.floorName = this.treeData[0].children[0].children[0].Gcode;
                this.floorId = this.treeData[0].children[0].children[0].Gname;
                this.categoryId = this.treeData[0].children[0].Id;
                // this.getLegend();
                this.checkFloor(this.treeData[0].children[0].children[0].Gname);
              } else {
                this.treeData[0].open = true;
                this.treeData[0].children[0].checked = "checked";
                this.systemName = this.treeData[0].Gcode;
                this.floorName = this.treeData[0].children[0].Gcode;
                this.floorId = this.treeData[0].children[0].Gname;
                this.categoryId = this.treeData[0].Id;
                // this.getLegend();
                this.checkFloor(this.treeData[0].children[0].Gname);
              }
            } else {
              this.treeData = data;
            }
          } else {
            this.treeData = [];
            this.$message.error("获取楼层结构失败");
          }
          // 如果没有楼层则底图清空
          if (this.treeData.length == 0) {
            this.checkFloor("");
          }
        })
        .catch(() => {
          loadings.close();
          this.$message.error("请求失败");
        });
    },
    //获取补充图例
    getLegend() {
      this.legendLoading = true;
      this.legendData = [];
      queryStatistic({
        projectId: this.projectId,
        graphId: this.graphId,
        categoryId: this.categoryId
      }).then(res => {
        console.log(res);
        this.legendLoading = false;
        if (res.data.Result == "success") {
          const data = res.data.Data;
          data.map(item => {
            this.legendData.push(item);
          });
        } else {
          this.legendData = [];
          this.$message.error("获取楼层结构补充图例失败");
        }
      });
    },
    modalClose() {
      this.modalStatusTip = false;
    },
    modalConfirm() {
     this.deleteBtn();
      this.modalStatusTip = false;
    },
    //删除
    deleteBtn() {
      if(this.categoryId=='XFBFYCFL'||this.categoryId=='FZQZL'){
        if(this.grouptype=='checked'){
          this.deleteGraphMap();
        }else{
          this.deleteByCategoryMap();
        }
      }else{
       this.deleteGraphMap()
      }

    },
    //原理图删除
    deleteByCategoryMap(){
      const loadings = Loading.service({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      let params = {
        "BuildingID": this.BuildingID,
        "CategoryID": this.categoryId,
        "FloorID": this.floorId,
        "ProjectID": this.projectId
      }
      deleteByCategory(params).then(res=>{
        loadings.close();
        if (res.Result == "success") {
          this.$message.success("删除成功");
          this.getTreeData();
          // this.init();
          this.legendData = [];
        } else {
          this.$message.error(res.Message);
        }
      }).catch(()=>{
        loadings.close();
      });
    },
    //正常删除
    deleteGraphMap(){
      const loadings = Loading.service({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      deleteGraph([{ Id: this.graphId }]).then(res => {
        console.log(res);
        loadings.close();
        if (res.Result == "success") {
          this.$message.success("删除成功");
          this.getTreeData();
          // this.init();
          this.legendData = [];
        } else {
          this.$message.error(res.Message);
        }
      }).catch(()=>{
        loadings.close();
      });
    },
    //发布
    publishBtn() {
      const loadings = Loading.service({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      console.log(this.floorId);
      const data = {
        BuildingID: this.BuildingID,
        CategoryID: this.categoryId,
        FloorID: this.floorId,
        GraphId: this.graphId,
        ProjectID: this.projectId,
        Pub: false,
        PubUser: ""
      };
      publishGraph(data).then(res => {
        loadings.close();
        if (res.Result == "success") {
          this.$message.success("发布成功");
          this.getTreeData();
          this.legendData = [];
        } 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() {
      setTimeout(() => {
        /* const token = this.$store.getters["token"];
        const data = `categoryId=${this.categoryId}&projectId=${this.projectId}&BuildingID=1&FloorID=${this.floorId}&FloorName=${this.floorName}&fmapID=${this.fmapID}&token=${token}`;
        const url =
          window.location.origin +
          "/wandaEditer/editer?" +
          encodeURIComponent(data);
        window.open(url, true); */
         
        // 发布成功跳转草稿箱
        const token = this.$store.getters["token"];
        this.$router.push({
          path: "editer",
          query: {
            categoryId: this.categoryId,
            projectId: this.projectId,
            BuildingID: 1,
            FloorName: this.floorName,
            FloorID: this.floorId,
            fmapID: this.fmapID,
            token:token
          }
        });
      }, 1000);
    },
    // 切换草稿箱楼层
    checkFloor(floorid) {
      this.scene = new EditScence();
      this.scene.isEditStatus = false;
      this.clearGraphy();
      const loadings = Loading.service({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      if(!floorid){
        loadings.close();
        this.view.fitSceneToView();
        return
      }
      setTimeout(() => {
        this.view.scene = this.scene;
        this.parserData(floorid);
        this.readGroup(floorid).then(data => {
          if (data.Result == "success") {
            this.graphId = data.Data[0].ID;
            if (data.Data) {
              loadings.close();
              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();
              this.getLegend();
            }
          } else {
            loadings.close();
          }
        }).catch(()=>{
          loadings.close();
        });
      }, 100);
    }
  },
  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();
  }
};
</script>
<style lang="less" scoped>
#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;
        }
      }
      .span-ellipsis {
        width: 100%;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
    .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: 198px;
          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;
          background-color: #ffffff;
          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>