<template>
  <div
    ref="graphyMain"
    class="canvasGraphy"
    style="width:100%;"
    v-loading="loading.show"
    :element-loading-text="loading.num + '/' + loading.total"
  >
    <div v-show="hasMap" class="header-search">
      <!-- 初始两个按钮 -->
      <div v-show="type == 1">
        <el-button size="small" @click=" type = 2" icon="el-icon-search">查找业务空间</el-button>
        <el-button size="small" @click="myDialogVisible = true">创建业务空间</el-button>
        <span style="font-size:13px;color:#fff;margin-left:40px;display:inline-block;">
          提示：
          <i style="color:red;">红色字体</i>的业务空间为不相邻元空间组成，请检查是否要修改
        </span>
      </div>
      <!-- 搜索下拉列表定位 -->
      <div v-show="type == 2">
        <el-autocomplete
          popper-class="my-autocomplete"
          v-model="search"
          :fetch-suggestions="querySearch"
          placeholder="输入平面图中已有的业务空间名称进行查找"
          size="small"
          width="180px"
          @select="handleSelect"
        >
          <i class="el-icon-search el-input__icon" slot="suffix" @click="handleIconClick"></i>
          <template slot-scope="{ item }">
            <div class="name" style="position: relative;">
              {{ item.infos.RoomLocalName |cutString(8) }}
              <span
                class="addr"
                style="position: absolute;right:10px;color:#409EFF;"
              >定位</span>
            </div>
          </template>
        </el-autocomplete>
        <el-button style="margin-left:10px;" type="text" @click="clearDimension">收起</el-button>
      </div>
      <!-- 点击元空间显示 -->
      <div v-show="type == 3">
        <div class="div50">
          <el-button
            class="float-right"
            size="small"
            @click="SpaceDialog"
            type="primary"
            plain
          >从未关联元空间的业务空间中选择</el-button>
        </div>
        <div class="div50">
          <el-button @click="clearDimension" size="small" plain>取 消</el-button>
          <el-button size="small" @click="createSP" type="primary">创建新的业务空间</el-button>
        </div>
      </div>
      <!-- 点击业务空间显示 -->
      <div v-show="type == 4">
        <div class="div50">
          <el-button class="float-right" size="small" @click="divide" type="primary" plain>重新划分业务空间</el-button>
        </div>
        <div class="div50">
          <el-button @click="clearDimension" size="small" plain>取 消</el-button>
          <el-button @click="bussinDea" size="small" type="primary">查看详情</el-button>
        </div>
      </div>
      <!-- 点击业务空间后点击元空间 -->
      <div v-show="type == 5">
        <div class="div50">
          <el-button @click="clearDimension" class="float-right" size="small" plain>取 消</el-button>
        </div>
        <div class="div50">
          <el-button size="small" @click="saveChange" type="primary">保存修改</el-button>
        </div>
      </div>
      <el-button
        v-show="type == 1"
        @click="getPiss"
        style="position: absolute;top: 10px;right: 10px;"
        size="small"
        type="text"
      >未关联元空间的业务空间 {{num}} 条</el-button>
    </div>
    <div
      v-show="hasMap"
      ref="canvasWidth"
      class="canvasWidth"
      v-loading="myLoading"
      style="width:100%;"
    >
      <canvas :id="canvasId + 'canvas' " :width="canvasW" :height="canvasH"></canvas>
      <div
        style="height: 30px;overflow: hidden;z-index:99;transform: translateX(-50%);position: absolute;bottom: 10%;left: 50%;"
      >
        <el-button size="small" @click="smallSize" type="primary">- 缩小</el-button>
        <el-button size="small" @click="suitableSize" type="primary">合适比例</el-button>
        <el-button size="small" @click="bigSize" type="primary">+ 放大</el-button>
      </div>
    </div>
    <div
      v-show="!hasMap"
      style="width:100%;line-height:500px;font-size:20px;text-align:center;color:#ccc;"
    >请初始化平面图</div>
    <el-dialog title="提示" :visible.sync="dialogVisible" :before-close="clearDimension" width="30%">
      <p style="color:red;line-height:24px;margin-bottom: 10px;" v-show="isAbutMsg">注意：您选择的元空间并未相邻!</p>
      <p style="line-height:24px;margin-bottom: 10px;">请输入创建的业务空间名：</p>
      <!-- <p>
        <el-input
          placeholder="请输入业务空间名"
          v-model="name"
          size="small"
          clearable>
        </el-input>
      </p>-->
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label label-width="0" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="clearDimension">取 消</el-button>
        <el-button type="primary" @click="isTrue">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="myDialogVisible" width="30%">
      <p style="line-height:26px;">方法1：直接在平面图中点击单个或多个带⬇️标记的元空间创建业务空间</p>
      <p style="line-height:26px;">方法2：根据未关联业务空间的元空间批量创建业务空间</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="createBatchSq">批量创建业务空间</el-button>
        <el-button type="primary" @click="myDialogVisible = false">返回平面图手动选择</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";

//引擎的引用
import {
  SGraphyView,
  SGraphyScene,
  SGraphyRectItem
} from "@/assets/node-templete";
import pako from '@/assets/pako/pako'

//ele动画组件
//item组件
import SGraphyLineItem from "@/assets/js/items/SGraphyLineItem";
import SGraphyPolygonItem from "@/assets/js/items/SGraphyPolygonItem";
import SGraphyVirtualItem from "@/assets/js/items/SGraphyVirtualItem";
import SGraphyImageItem from "@/assets/js/items/SGraphyImageItem";
import SGraphyPillarItems from "@/assets/js/items/SGraphyPillarItems";
import tools from "@/assets/js/tools";
let data = "";
let scale = 120; //缩放比例
let myData = [
  {
    Id: "1221512",
    PointList: { X: -35146.875, Y: 40680 }
  }
];
// let colorArr = [
//   "rgba(0,245,255,.2)",
//   "rgba(255,218,185,.2)",
//   "rgba(132,112,255,.2)",
//   "rgba(127,255,0,.2)",
//   "rgba(238,92,66,.2)",
//   "rgba(255,255,224,.2)",
//   "rgba(238,233,233,.2)",
//   "rgba(156,156,156,.2)",
//   "rgba(144,238,144,.2)",
//   "rgba(180,205,205,.2)"
// ];
let colorArr = [
  "#F9C3C3",
  "#FFD1BF",
  "#FFF3BF",
  "#D8F7C6",
  "#C6F2F6",
  "#DCE3C0",
  "#FAE6C9",
  "#E3D7F7",
  "#C4CBF8",
  "#DEC3F6"
];

// function hexify(color) {
//   var values = color
//     .replace(/rgba?\(/, '')
//     .replace(/\)/, '')
//     .replace(/[\s+]/g, '')
//     .split(',');
//   var a = parseFloat(values[3] || 1),
//       r = Math.floor(a * parseInt(values[0]) + (1 - a) * 255),
//       g = Math.floor(a * parseInt(values[1]) + (1 - a) * 255),
//       b = Math.floor(a * parseInt(values[2]) + (1 - a) * 255);
//   return "#" +
//     ("0" + r.toString(16)).slice(-2) +
//     ("0" + g.toString(16)).slice(-2) +
//     ("0" + b.toString(16)).slice(-2);
// }
// colorArr = colorArr.map(item => {
//   return hexify(item)
// })

class MainScene extends SGraphyScene {
  constructor() {
    super();
    //资产id
  } // Function constructor()

  /**
   * 绘制背景
   *
   * @param   canvas      画布
   * @param   rect        更新绘制区域
   */
  // drawBackground(canvas, rect) {}
}
import {
  formBIMToPri, // 将bimId转换成物理世界id
  createBusiness, //添加业务空间
  createRelation, //添加关系
  getGraphyId, //获取图类型
  getBussines2, //获取业务空间
  getRelation, //获取业务空间下的元空间id
  deleteRelation, //删除关系
  isAbut
} from "@/api/request";

export default {
  name: "HelloWorld",
  props: {
    canvasId: {
      type: String
    }
  },
  data() {
    return {
      view: "",
      num: "",
      mainScene: new MainScene(),
      dataMax: "", //最大值最小值数据
      scene: {
        x: 0,
        y: 0
      },
      dialogVisible: false, //浮层
      id: null,
      canvasH: 600,
      canvasW: 800,
      param: {
        ProjId: this.$route.query.projId, //项目id
        UserId: this.$route.query.userId, //用户id
        secret: this.$route.query.secret
      },
      myDialogVisible: false,
      wallList: [], //处理后的墙的线条
      type: 1, //1  默认显示初始按钮， 2搜索下拉， 3点击元空间， 4点击业务空间
      restaurants: [],
      search: "",
      idList: [],
      buildMess: null,
      loading: {
        show: false,
        num: 0,
        total: 0,
        errorNum: 0
      },
      graphyId: "",
      relationList: [],
      myLoading: false,
      hasMap: true,
      ruleForm: {
        name: ""
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入需要创建的业务空间名称",
            trigger: "blur"
          }
        ]
      },
      isAbutMsg: false, //是否相邻提示
      businessData: "", //新建业务空间数据
      spaceType: {},//space类型code
    };
  },
  created() {
    // this.getJson("Fl110108000327d8f006c39f49feb40e24a7ef22323220181119025802bim.jsonz")
    // this.getJson("bim.jsonz")
  },
  mounted() {
    console.log(this.canvasId)
    // this.resetSize();
    // window.addEventListener("click",this.typeTo1)
  },
  methods: {
    //获取数据
    getData(floorMap, buildMess, data) {
      this.spaceType = data
      this.loading.show = false;
      this.type = 1;
      this.idList = [];
      this.buildMess = buildMess;
      if (!floorMap) {
        this.hasMap = false;
      } else {
        this.getJson(floorMap);
        this.hasMap = true;
      }
    },
    clearList() {
      this.idList = []
    },

    //未关联元空间的业务空间
    getPiss() {
      this.$emit("getSp", [{}], this.buildMess, this.graphyId);
    },

    //查询绑定了元空间的业务空间
    getHasSpace() {
      console.log(this.spaceType, "spaceType")
      let param = {
        data: {
          criteria: {
            id: this.buildMess.code,
            // graphId: this.graphyId,
            // relType: this.spaceType.rel_type,
            // exclude: false,
            // side: 1,
            type: [this.spaceType.code],
            "include": [            // 可选, 只查询指定图/关系中的对象
              {
                "graphId": this.graphyId,
                "graphType": this.spaceType.code,
                "relType": this.spaceType.rel_type,
                "side": "toId",
                // "fromId": "",                 // 选填
                // "toId": ""                    // 选填
              }
            ]
          },
        },
        ProjId: this.param.ProjId,
        secret: this.param.secret
      }
      getBussines2(param)
        .then(res => {
          if (res.data.Result == "success") {
            this.restaurants = res.data.Content;
            let nameList = [];
            if (res.data.Content && res.data.Content.length) {
              this.relationList = res.data.Content.map(item => {
                nameList.push(item.infos.RoomLocalName);
                return item.id;
              });
              this.locationPath(this.relationList, nameList);
            }
          } else {
            this.$message.error(res.data.ResultMsg);
          }
          this.myLoading = false;
        })
        .catch(() => {
          // console.log("请求出错");
        });
    },

    //确定新建
    isTrue() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.loading.show = true;
          this.loading.num = 0;
          this.loading.total = 1 * 2;
          this.businessData.infos.RoomLocalName[0].value = this.ruleForm.name;
          this.createSpace(this.businessData, this.idList, true);
          this.dialogVisible = false;
        } else {
          // console.log("error submit!!");
          return false;
        }
      });
    },

    //查询未绑定元空间的业务空间
    getNoSpace() {
      getBussines2({
        data: {
          criteria: {
            id: this.buildMess.code,
            // graphId: this.graphyId,
            // relType: this.spaceType.rel_type,
            // exclude: false,
            // side: 1,
            type: [this.spaceType.code],
            "exclude": [            // 可选, 只查询指定图/关系中的对象
              {
                "graphId": this.graphyId,
                "graphType": this.spaceType.code,
                "relType": this.spaceType.rel_type,
                "side": "toId",
                // "fromId": "",                 // 选填
                // "toId": ""                    // 选填
              }
            ]
          },
        },
        ProjId: this.param.ProjId,
        secret: this.param.secret
      })
        .then(res => {
          if (res.data.Result == "success") {
            this.num = res.data.Content.length;
          } else {
            this.$message.error(res.data.ResultMsg);
          }
        })
        .catch(() => {
          // console.log("请求出错");
        });
    },

    //当type=2时点击变成1
    typeTo1() {
      if (this.type == 2) {
        this.type = 1;
      }
    },

    getJson(jsonId) {
      axios({
        method: 'get',
        url: "/img/image-service/common/file_get/" + jsonId + "?systemId=revit",
        data: {},
        responseType: 'blob',
        // contentType: "charset=utf-8"
      }
      )
        .then(res => {
          // console.log(res.data, "res.data")
          let data = null
          var blob = res.data;
          var reader = new FileReader();
          reader.readAsBinaryString(blob)
          // console.log("获取到了数据")
          let _this = this
          reader.onload = function (readerEvt) {
            // console.log("reader获取完毕")
            var binaryString = readerEvt.target.result;
            // let base64Data = btoa(binaryString)
            let base64Data = btoa(binaryString)
            let unGzipData = pako.unzip(base64Data)
            // console.log(unGzipData)
            // console.log(unGzipData, "atob")
            data = unGzipData
            _this.dataMax = tools.getPoint(data);
            console.log(unGzipData, data)
            if (data.WallList && data.WallList.length) {
              tools.changeMap(data.WallList, -1, "PointList");
            }
            if (data.SpaceList && data.SpaceList.length) {
              tools.changeMap(data.SpaceList, -1, "Paths");
            }
            if (data.ColumnList && data.ColumnList.length) {
              tools.changeMap(data.ColumnList, -1, "Path");
            }
            if (data.VirtualWallList && data.VirtualWallList.length) {
              tools.changeMap(data.VirtualWallList, -1, "PointList");
            }
            if (data.EquipmentList && data.EquipmentList.length) {
              tools.changeMap(data.EquipmentList, -1, "PointList");
            }
            let ids = [];
            if (data.SpaceList && data.SpaceList.length) {
              data.SpaceList.map(items => {
                items.BimId = _this.buildMess.code + ":" + items.BimId;
                ids.push(items.BimId);
              });
            } else {
              _this.$message("没有元空间数据")
            }
            _this.bimIdToId(ids, data);
            _this.myLoading = true;
          };
          // console.log(reader)
        });
    },

    //获取图实例关系
    getGraphy() {
      getGraphyId({
        type: "ElementSptoSpace",
        ProjId: this.param.ProjId,
        secret: this.param.secret
      })
        .then(res => {
          if (res.data.Result == "success") {
            this.graphyId = res.data.graph_id;
            this.getHasSpace();
            this.getNoSpace();
          } else {
            this.$message.error(res.data.ResultMsg);
          }
        })
        .catch(() => {
          this.$message.error("请求错误");
        });
    },

    bimIdToId(ids, data) {
      formBIMToPri({
        type: ["Si"],
        ids: ids,
        ProjId: this.param.ProjId,
        secret: this.param.secret
      })
        .then(res => {
          if (res.data.Result == "success") {
            data.SpaceList.map((item, index) => {
              res.data.Content.map((i, li) => {
                //判断bimId是否相同
                if (item.BimId == i.infos.BIMID) {
                  item.id = i.id;
                }
              });
            });
            this.createCanvas();
            this.initGraphy(data);
            console.log("请求完毕")
          } else {
            this.$message.error(res.data.ResultMsg);
          }
        })
        .catch(() => {
          this.$message.error("请求出错");
        });
    },

    //创建实例
    createCanvas() {
      //初始化
      if (this.view.scene) {
        this.view.scene.root.children = [];
        this.view = null;
      }
      this.view = new SGraphyView(this.canvasId + "canvas", this.mainScene);
      this.view.onDraw();
      // this.view.canvasView.addEventListener("mouseup", this.dataChange);
      // this.view.canvasView.addEventListener("mousemove", this.canvasMove);
    },

    //初始化canvas大小
    resetSize() {
      this.canvasW =
        document.getElementById("app").offsetWidth - 2;
      this.canvasH = document.getElementById("app").offsetHeight - 110;
      let classs = document.getElementsByClassName("canvasWidth");
      // for(let i = 0; i < classs.length;i++){
      //   classs[i].style.height = this.canvasH + 'px'
      // }
      this.$refs.canvasWidth.style.height = this.canvasH + "px";
    },

    //实例化视图
    initGraphy(data) {
      this.resetSize();
      this.view.pos.x = this.view.pos.y = -50;
      let equip = data.EquipmentList,
        wall = data.WallList,
        virtual = data.VirtualWallList,
        space = data.SpaceList,
        column = data.ColumnList,
        spaceStr;

      //空间
      if (space && space.length) {
        for (let i = 0; i < space.length; i++) {
          if (space[i].Paths[1] && space[i].Paths[1].length >= 2) {
            spaceStr = new SGraphyPolygonItem(
              space[i].Paths[0],
              1,
              "rgba(111,111,111,0.5)",
              "#fff",
              space[i].id,
              {
                x: space[i].LocationPoint.X,
                y: space[i].LocationPoint.Y * -1
              },
              space[i].Name,
              space[i].Paths
            );
            this.mainScene.addItem(spaceStr);
          }
        }
        for (let i = 0; i < space.length; i++) {
          if (space[i].Paths[0] && space[i].Paths[0].length >= 2 && !!!space[i].Paths[1]) {
            spaceStr = new SGraphyPolygonItem(
              space[i].Paths[0],
              1,
              "rgba(111,111,111,0.5)",
              "#fff",
              space[i].id,
              {
                x: space[i].LocationPoint.X,
                y: space[i].LocationPoint.Y * -1
              },
              space[i].Name
            );
            this.mainScene.addItem(spaceStr);
          }
        }
      }

      //获取中心点
      let rect = this.view.scene.worldRect();

      //初始化画布缩放比例
      this.view.scale = 1;
      //计算缩放比例
      this.view.scale = Math.min(
        this.view.width / (rect.width * 1.2),
        this.view.height / (rect.height * 1.2)
      );
      this.view.minScale = this.view.scale / 10
      this.view.maxScale = this.view.scale * 10
      // 移动画布
      this.view.pos.x =
        (-(rect.right + rect.left) / 2) * this.view.scale + this.view.width / 2;
      this.view.pos.y =
        (-(rect.bottom + rect.top) / 2) * this.view.scale +
        this.view.height / 2;

      //点击事件
      this.view.canvasView.addEventListener("click", this.checkSpace);
      this.getGraphy();
    },

    /** canvas事件------------------------------------------------------------------------------------*/

    //点击元空间
    checkSpace(e) {
      let item = tools.mouseInElement(this.view, e);
      console.log(item)
      let items = this.mainScene.root.children;

      //点击业务空间
      if (
        item.falg &&
        item.item.businessId &&
        (item.item.isBusiness == 2 || item.item.isBusiness == 7)
      ) {
        // console.log("点击不可点击的业务空间", item);
        if (this.type == 2) {
          this.idList = [];
          items.map(i => {
            if (i.isBusiness == 3) {
              i.isBusiness = 2;
            }
          });
        }
        items.map(i => {
          if (i.isBusiness == 6) {
            i.isBusiness = 2;
          } else if (i.isBusiness == 3) {
            i.isBusiness = 1;
          }
        });
        this.type = 4;
        items.map(i => {
          if (i.isBusiness == 6) {
            i.isBusiness = 2;
          }
          if (i.businessId == item.item.businessId) {
            i.isBusiness = 6;
          }
        });
        this.idList.push({ id: item.item.businessId, name: item.item.businessName || item.item.name });
      }

      //点击没有业务空间的元空间
      if (
        item.falg &&
        !item.item.businessId &&
        (item.item.isBusiness == 4 || item.item.isBusiness == 1) &&
        this.type != 5
      ) {
        // console.log("点击的是没有业务空间的元空间", item);
        if (this.type == 4) {
          this.idList = [];
          items.map(i => {
            if (i.isBusiness == 6) {
              i.isBusiness = 2;
            } else if (i.isBusiness == 3) {
              i.isBusiness = 1;
            }
          });
          // console.log("清空", this.idList);
        }
        this.type = 3;
        item.item.isBusiness = 3;
        this.idList.push({ id: item.item.id, name: item.item.businessName || item.item.name });
      }

      //在重新编辑业务空间状态
      if (
        this.type == 5 &&
        item.falg &&
        !item.item.businessId &&
        (item.item.isBusiness == 4 || item.item.isBusiness == 1)
      ) {
        item.item.isBusiness = 3;
        this.idList.push({ id: item.item.id, name: item.item.businessName || item.item.name });
      }

      //在重新编辑时的提示
      if (
        item.falg &&
        item.item.businessId &&
        (item.item.isBusiness == 4 || item.item.isBusiness == 1)
      ) {
        // console.log("44444");
        item.item.isBusiness = 3;
        this.idList.push({
          id: item.item.id,
          name: item.item.businessName || item.item.name,
          parentId: item.item.businessId
        });
      }

      if (item.falg && item.item.isBusiness == 5) {
        this.$message("该空间为业务空间，请勿点击");
      }

      // if(item.falg && item.item.businessId)
    },

    /**  搜索 ------------------------------------------------------------------------------ */
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return restaurant => {
        return restaurant.infos.RoomLocalName.indexOf(queryString) > -1;
      };
    },

    handleSelect(item) {
      this.locationPath(item.id);
    },
    handleIconClick(ev) {
      this.locationPath(ev.id);
    },

    //定位
    locationPath(id, name) {
      let param = {
        criterias: {},
        ProjId: this.param.ProjId,
        secret: this.param.secret
      },
        falg = false;

      //查询多个关系
      if (id instanceof Array) {
        falg = true;
        param.criterias.criterias = [];
        id.map(item => {
          param.criterias.criterias.push({
            to_id: item,
            graph_id: this.graphyId,
            rel_type: this.spaceType.rel_type
          });
        });
      } else {
        //查询单个关系
        param.criterias.criteria = {
          to_id: id,
          graph_id: this.graphyId,
          rel_type: this.spaceType.rel_type
        };
      }
      getRelation(param)
        .then(res => {
          if (res.data.Result == "success") {
            if (falg) {
              //多个关系渲染颜色
              this.relationList = [];
              id.map((item, index) => {
                let children = res.data.Content[index].Content.map(i => {
                  if (!!i) {
                    return i.from_id;
                  } else {
                    return undefined;
                  }
                });
                this.relationList.push({
                  id: item,
                  name: name[index],
                  children: children,
                  isAdjacent: true
                });
              });
              this.relationList.reverse();
              // this.getColor(this.relationList);
              //判断相邻代码
              this.spaceIsAbut(this.relationList);
            } else {
              //单个是定位
              this.getPathToCanvas(res.data.Content[0].from_id);
            }
          } else {
            this.$message.error(res.data.ResultMsg);
          }
        })
        .catch(() => {
          this.$message.error("请求错误");
        });
    },

    //给canvas的items渲染色彩
    getColor(list) {
      let items = this.mainScene.root.children;
      list.map(item => {
        if (item.children && item.children.length) {
          item.children.map(space => {
            items.map(canvas => {
              if (canvas.id == space) {
                canvas.businessId = item.id;
                canvas.businessName = item.name;
              }
            });
          });
        }
      });
      this.applyColor(list);
    },

    //渲染业务空间色彩
    applyColor(list) {
      let items = this.mainScene.root.children;
      items.map(item => {
        item.businessId = null;
        item.businessName = null;
        item.businessColor = "rgba(0,0,0,0)";
        item.isBusiness = 1;
      });
      list.map((item, index) => {
        if (item.children && item.children.length) {
          item.children.map(space => {
            items.map(canvas => {
              if (canvas.id == space) {
                canvas.businessId = item.id;
                canvas.businessName = item.name;
                canvas.businessColor = colorArr[index % 10];
                canvas.isBusiness = 2;
                //判断相邻代码

                if (!item.isAbut) {
                  canvas.isBusiness = 7;
                }
              }
            });
          });
        }
      });
    },

    spaceIsAbut(list) {
      let data = list.map(item => {
        return {
          ids: item.children
        };
      });
      let param = {
        data: {
          floor: this.buildMess.code,
          criterias: data
        },
        ProjId: this.param.ProjId,
        secret: this.param.secret
      };
      // console.log(param);
      isAbut(param)
        .then(res => {
          if (res.data.Result == "success") {
            res.data.Content.map((item, index) => {
              this.relationList[index].isAbut = item.abut;
            });
            this.getColor(this.relationList);
          } else {
            this.$message.error(res.data.ResultMsg);
          }
        })
        .catch(() => {
          this.$message.error("请求出错");
        });
    },

    getPathToCanvas(id) {
      let items = this.mainScene.root.children;
      items.map(item => {
        if (item.id == id) {
          //定位算法
          this.view.pos.x =
            -item.centerOfGravityPoint.x * this.view.scale +
            this.view.width / 2;
          this.view.pos.y =
            -item.centerOfGravityPoint.y * this.view.scale +
            this.view.height / 2;
          this.view.scale = this.view.scale;
          item.isBusiness = 3;
          this.idList = [];
          console.log(item)
          this.idList.push({ id: item.businessId, name: item.businessName || '--' });
        } else if (item.businessId) {
          item.isBusiness = 2;
        } else {
          item.isBusiness = 1;
        }
      });
    },

    /**  按钮事件  ---------------------------------------------------------------------- */
    SpaceDialog() {
      this.$emit("dimension", this.idList, this.buildMess, this.graphyId);
    },

    bussinDea() {
      this.$emit("businessDetails", this.idList[this.idList.length - 1]);
    },

    //保存修改
    saveChange() {
      let id = ""
      this.idList.map(item => {
        if (!!item.parentId) {
          id = item.parentId
        }
      })
      this.deleteRela(id);
    },

    //调整到合适比例
    suitableSize() {
      //获取中心点
      let rect = this.view.scene.worldRect();
      //计算缩放比例
      this.view.scale = Math.min(
        this.view.width / (rect.width * 1.2),
        this.view.height / (rect.height * 1.2)
      );
      // 移动画布
      this.view.pos.x =
        (-(rect.right + rect.left) / 2) * this.view.scale + this.view.width / 2;
      this.view.pos.y =
        (-(rect.bottom + rect.top) / 2) * this.view.scale +
        this.view.height / 2;
    },

    //调整到小比例
    smallSize() {
      //获取中心点
      let rect = this.view.scene.worldRect();
      //计算缩放比例
      this.view.scale = this.view.scale * 0.9;
      // 移动画布
      this.view.pos.x =
        (-(rect.right + rect.left) / 2) * this.view.scale + this.view.width / 2;
      this.view.pos.y =
        (-(rect.bottom + rect.top) / 2) * this.view.scale +
        this.view.height / 2;
    },

    bigSize() {
      //获取中心点
      let rect = this.view.scene.worldRect();
      //计算缩放比例
      this.view.scale = this.view.scale * 1.1;
      // 移动画布
      this.view.pos.x =
        (-(rect.right + rect.left) / 2) * this.view.scale + this.view.width / 2;
      this.view.pos.y =
        (-(rect.bottom + rect.top) / 2) * this.view.scale +
        this.view.height / 2;
    },

    //删除关系
    deleteRela(id) {
      let param = {
        data: {
          criterias: [
            {
              to_id: id, //选填
              graph_id: this.graphyId, //选填
              rel_type: this.spaceType.rel_type //选填
            }
          ]
        },
        ProjId: this.param.ProjId,
        secret: this.param.secret
      };
      if (id) {
        deleteRelation(param)
          .then(res => {
            if (res.data.Result == "success") {
              this.loading.show = true;
              this.loading.num = 0;
              this.loading.total = 1;
              this.addRelation(id, this.idList);
            } else {
              this.$message.error(res.data.ResultMsg);
            }
          })
          .catch(() => {
            this.$message.error("请求失败");
          });
      } else {
        this.$message.error("请选择包含原业务空间的区域块")
      }
    },

    //点击元空间后点击取消
    clearDimension() {
      this.myLoading = true;
      let indexs = tools.clear(
        this.mainScene.root.children,
        3,
        this.idList,
        "id"
      );
      this.myDialogVisible = false;
      this.dialogVisible = false;
      for (let i = 0; i < indexs.length; i++) {
        this.mainScene.root.children[indexs[i]].isBusiness = 1;
      }
      this.idList = [];
      this.type = 1;
      this.getHasSpace();
    },

    //创建新的业务空间
    createSP() {
      let businessData = {
        building_id: this.buildMess.buildCode,
        floor_id: this.buildMess.code,
        business_type: this.spaceType.code,
        infos: {
          RoomLocalName: [{ value: tools.getText(this.idList, "name") }]
        }
      };
      let data = [];
      this.idList.map(i => {
        data.push(i.id);
      });
      let param = {
        data: {
          floor: this.buildMess.code,
          criterias: [{ ids: data }]
        },
        ProjId: this.param.ProjId,
        secret: this.param.secret
      };
      // this.createSpace(businessData, this.idList, true);
      //判断相邻代码
      isAbut(param)
        .then(res => {
          if (res.data.Result == "success") {
            this.dialogVisible = true;
            this.ruleForm.name = businessData.infos.RoomLocalName[0].value;
            this.businessData = businessData;
            if (res.data.Content[0].abut) {
              this.isAbutMsg = false;
              // this.createSpace(businessData, this.idList, true);
            } else {
              this.isAbutMsg = true;
              // this.$confirm(
              //   "您选择的元空间并未相邻，确定继续创建业务空间？",
              //   "提示",
              //   {
              //     confirmButtonText: "确定",
              //     cancelButtonText: "取消",
              //     type: "warning"
              //   }
              // )
              //   .then(() => {
              //     this.loading.show = true;
              //     this.loading.num = 0;
              //     this.loading.total = 1 * 2;
              //     this.createSpace(businessData, this.idList, true);
              //   })
              //   .catch(() => {
              //     this.$message({
              //       type: "info",
              //       message: "已取消"
              //     });
              //     this.clearDimension();
              //     this.loading.show = false;
              //   });
            }
          } else {
            this.$message.error(res.data.ResultMsg);
          }
        })
        .catch(() => {
          this.$message.error("请求失败");
        });
    },

    //比较两个元空间是否相邻
    compareSpace(ids) {
      // console.log(ids);
    },

    //重新划分业务空间
    divide() {
      this.type = 5;
      let id = this.idList[this.idList.length - 1],
        items = this.mainScene.root.children;
      items.map(item => {
        if (item.businessId == id.id) {
          item.isBusiness = 4;
        } else if (item.businessId) {
          item.isBusiness = 5;
        }
      });
      this.idList = [];
    },

    //批量生成业务空间
    createBatchSq() {
      let items = this.mainScene.root.children;
      let map = [];
      items.map(item => {
        if (!item.businessId) {
          map.push({
            id: item.id,
            name: item.name
          });
        }
      });

      let text = tools.getText(map, "name");
      this.$confirm(
        // "您确定批量创建业务空间：" +
        //   tools.cutString(text, 10, "等业务空间") +
        //   ", 是否继续?",
        "<p>确定根据未关联业务空间的元空间批量创建业务空间</p>" +
        "<p>涉及的元空间：</p>" +
        "<p style='line-height:20px;max-height:60px;overflow-y:auto;'>" +
        text +
        "</p>",
        // tools.cutString(text, 60, "等业务空间")
        "提示",
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          this.loading.show = true;
          this.loading.num = 0;
          this.loading.total = map.length * 2;
          this.myDialogVisible = false;
          map.map(item => {
            this.createSpace(
              {
                building_id: this.buildMess.buildCode,
                floor_id: this.buildMess.code,
                business_type: this.spaceType.code,
                infos: {
                  RoomLocalName: [{ value: item.name }]
                }
              },
              item.id,
              true
            );
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消批量创建"
          });
        });
    },

    //创建空间
    createSpace(data, id, falg) {
      let param = {
        ProjId: this.param.ProjId,
        secret: this.param.secret,
        data: data
      };
      createBusiness(param).then(res => {
        if (res.data.Result == "success") {
          if (falg) {
            this.loading.num++;
            this.addRelation(res.data.id, id);
          } else {
          }
        } else {
          this.loading.num++;
          this.$message.error("修改发生错误：" + res.data.ResultMsg);
        }
      });
    },

    //添加关系
    addRelation(SpId, SiId) {
      let data = {};
      if (SiId instanceof Array) {
        data.criterias = [];
        SiId.map(item => {
          data.criterias.push({
            from_id: item.id,
            to_id: SpId,
            graph_id: this.graphyId,
            rel_type: this.spaceType.rel_type
          });
        });
      } else {
        data = {
          from_id: SiId,
          to_id: SpId,
          graph_id: this.graphyId,
          rel_type: this.spaceType.rel_type
        };
      }
      createRelation({
        data: data,
        ProjId: this.param.ProjId,
        secret: this.param.secret
      })
        .then(res => {
          if (res.data.Result == "success") {
            this.loading.num++;
            if (this.loading.num == this.loading.total) {
              this.loading.show = false;
              this.getHasSpace();
              this.idList = [];
              this.$message.success("添加成功");
              this.type = 1;
            }
          } else {
            this.$message.error(res.data.ResultMsg);
            this.loading.errorNum++;
          }
        })
        .catch(() => {
          this.$message.error("请求出错");
          this.loading.errorNum++;
        });
    }
  },
  filters: {
    cutString: function (str, len) {
      //length属性读出来的汉字长度为1
      if (!!str && typeof str == "string" && str.length > len) {
        return str.substring(0, len) + "...";
      } else {
        return str || "--";
      }
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
.canvasGraphy {
  position: relative;
  canvas {
    border: 1px solid #ccc;
  }
  .header-search {
    position: absolute;
    top: 0;
    height: 50px;
    line-height: 50px;
    padding-left: 20px;
    background-color: rgba(205, 197, 191, 0.4);
    left: 0;
    right: 0;
    top: 0;
    z-index: 99;
    > div {
      height: 50px;
    }
    .div50 {
      float: left;
      width: 50%;
      height: 100%;
      .float-right {
        float: right;
        margin-top: 11px;
        margin-right: 10%;
      }
    }
  }
  .el-autocomplete {
    width: 320px;
  }
  .my-autocomplete {
    li {
      line-height: normal;
      padding: 7px;

      .name {
        text-overflow: ellipsis;
        overflow: hidden;
      }
      .addr {
        font-size: 12px;
        color: #b4b4b4;
      }

      .highlighted .addr {
        color: #ddd;
      }
    }
  }
}
</style>
