<!-- 新增实例 -->
<template>
  <Modal
    class="getItemModal"
    :show="isShowModel"
    title="添加实例对象"
    mode="full"
    @close="modalClose"
  >
    <template #content class="xxx">
      <div class="getItem">
        <div id="left" class="left">
          <div class="top">
            <Cascader
              caption="专业系统"
              multiple
              allText="全部"
              :all="false"
              :data="categoryList"
              showPanel
              width="300"
              @confirm="changeEquip"
            ></Cascader>
            <Cascader
              caption="建筑楼层"
              allText="全部"
              multiple
              :data="buildFloorList"
              @confirm="changeFloor"
              showPanel
              width="300"
            ></Cascader>
            <!-- <Cascader
              caption="分区类型"
              multiple
              :data="cascaderData6"
              showPanel
              width="300"
            ></Cascader> -->
            <Input
              iconType="search"
              v-model="queryText"
              placeholder="搜索设备名称或本地编码"
              @pressEnter="pressEnter"
            />
          </div>
          <div class="localDom" ref="localDom">
            <el-table
              v-if="tableHeight > 0"
              size="small"
              ref="multipleTable"
              :data="equiptable"
              tooltip-effect="dark"
              style="width: 100%"
              :height="tableHeight"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column type="localName" label="本地名称" width="300">
                <template slot-scope="scope">{{
                  scope.row.localName ? scope.row.localName : "--"
                }}</template>
              </el-table-column>
              <el-table-column prop="localId" label="本地编码" width="300">
                <template slot-scope="scope">{{
                  scope.row.localId ? scope.row.localId : "--"
                }}</template>
              </el-table-column>
              <el-table-column
                prop="bimLocation"
                label="位置"
                show-overflow-tooltip
                width="300"
              >
                <template slot-scope="scope">{{
                  scope.row.building || scope.row.floor
                    ? scope.row.building && scope.row.floor
                      ? scope.row.building.localName +
                        "-" +
                        scope.row.floor.localName
                      : scope.row.building
                      ? scope.row.building.localName
                      : scope.row.floor.localName
                    : "--"
                }}</template>
              </el-table-column>
              <el-table-column
                prop="codeName"
                label="类型"
                show-overflow-tooltip
                width="300"
              >
              </el-table-column>
            </el-table>
          </div>
          <Pagination
            class="page-box"
            :pageCountShow="true"
            :pageCount="tableTotal"
            :pageSizeSetting="true"
            @change="currentChangeHandle"
          />
        </div>
        <div class="right">
          <div class="top">
            <div class="top-l">
              <span class="equip-title">已选实例</span>
              <span class="equip-num">{{ choiceEquipList.length }}</span>
            </div>
            <div class="top-r" @click="clearChoiceEqipment">清空</div>
          </div>
          <ul class="choiceList">
            <li class="choiceList-item">
              <div
                class="treeList"
                v-for="(items, key) in equipData"
                :key="key"
              >
                <div class="title" @click="collapse(items)">
                  <i
                    v-bind:class="[
                      items.showChildren ? 'caret-icon-active' : 'caret-icon',
                      'el-icon-caret-bottom',
                    ]"
                  ></i>
                  <span class="equip-title">{{ items.title }}</span>
                  <span class="equip-num">{{ items.number }}</span>
                </div>
                <el-collapse-transition>
                  <ul class="treeList-bodys" v-show="items.showChildren">
                    <li
                      class="treeList-item"
                      v-for="(item, key) in items.children"
                      :key="key"
                    >
                      <div class="item-title">
                        {{ item.localName ? item.localName : "空" }}
                      </div>
                      <i
                        class="el-icon-error"
                        @click="deleteItem(items, key)"
                      ></i>
                    </li>
                  </ul>
                </el-collapse-transition>
              </div>
            </li>
          </ul>
        </div>
      </div>
      <div class="btn-list">
        <el-button @click="modalClose">取消</el-button>
        <el-button type="primary" @click="finish">确认</el-button>
      </div>
    </template>
  </Modal>
</template>
<script>
import { mapMutations, mapState } from "vuex";
import {
  buildiFloor,
  readCategory,
  queryEquip,
  queryLegend,
} from "@/api/editer";
import bus from "@/bus/bus";
export default {
  props: ["showAddItemModel"],
  computed: {
    ...mapState([
      "editCmd",
      "projectId",
      "equipmentItemNum",
      "equipmentItemList",
    ]),
  },
  data() {
    return {
      isShowModel: false,
      equipTypeString: "", //设备类型选中条件
      buildIdString: "", //建筑id 类型string
      floorIdString: "", // 楼层id 类型string
      tableTotal: 0, //搜索获取得设备总数
      equiptable: [], //table数据
      equipData: [], //选中得设备数组 右侧二级树
      buildFloorList: [], // 建筑查询数据
      categoryList: [], //设备类型
      tableHeight: 0, //table的高度
      choiceEquipList: [], // 选中得设备数组//非树机构
      pageSize: 20,
      currentPage: 1,
      local: null, //table loading
      local2: null, // 全局 loading
      queryText: "", //搜索框数据
      filtIdListString: "", // 要过滤的 id 字符串
    };
  },
  methods: {
    // 筛选设备
    changeEquip(list) {
      const classCode = []; // 设备类型
      this.currentPage = 1;
      list.forEach((val) => {
        if (val.index == 3) {
          classCode.push(val.id);
        }
      });
      //设备类型转换
      this.equipTypeString = classCode.length
        ? ";classCode in " + JSON.stringify(classCode)
        : "";
      // 调用设备接口
      this.queryEquip();
    },
    // 筛选楼层
    changeFloor(list) {
      let buildIdList = []; // 设备类型
      let floorIdList = [];
      let isfloornull = "";
      let isbuildnull = "";
      this.currentPage = 1;
      // 遍历获取对应得楼层id、建筑id
      list.forEach((val) => {
        if (val.index == 1) {
          if (val.id == "bisnull") {
            isbuildnull = "buildingId isNull";
          } else {
            buildIdList.push(val.id);
          }
        }
        if (val.index == 2) {
          if (val.id == "fisnull") {
            isfloornull = "floorId isNull";
          } else {
            floorIdList.push(val.id);
          }
        }
      });
      // 对id数组和or isnull 进行拼接
      if (buildIdList.length) {
        if (isbuildnull) {
          isbuildnull = "or " + isbuildnull;
        }
      }
      this.buildIdString = buildIdList.length
        ? ";buildingId in " + JSON.stringify(buildIdList) + isbuildnull
        : isbuildnull
        ? ";" + isbuildnull
        : "";
      if (floorIdList.length) {
        if (isfloornull) {
          isfloornull = "or " + isfloornull;
        }
      }
      this.floorIdString = floorIdList.length
        ? ";floorId in " + JSON.stringify(floorIdList) + isfloornull
        : isfloornull
        ? ";" + isfloornull
        : "";
      // 调用设备接口
      this.queryEquip();
    },
    // 搜索设备
    queryEquip() {
      let data = {
        cascade: [
          {
            name: "building",
            projection: ["id", "name", "localName"],
          },
          {
            name: "floor",
            projection: ["id", "name", "localName"],
          },
        ],
        orders: "name asc, createTime desc",
        pageNumber: this.currentPage,
        pageSize: this.pageSize,
        filters: `projectId='${this.projectId}'${this.filtIdListString}${this.buildIdString}${this.floorIdString}${this.equipTypeString};localName contain "${this.queryText}" or localId contain "${this.queryText}"`,
      };
      this.localLoading();
      queryEquip(data)
        .then((res) => {
          this.tableTotal = res.total;
          this.equiptable = res.content;
          this.$loading.close(this.local);
        })
        .catch((error) => {
          console.log("it is error!", error);
          this.$loading.close(this.local);
        });
    },
    // 关闭弹窗
    modalClose() {
      this.isShowModel = false;
      this.$emit("closeModel");
      // 清空搜索框信息
      this.queryText = ''
    },
    // 确认/提交
    finish() {
      // 获取选中图例得 iamge url
      if (!this.equipData.length) {
        this.modalClose();
      }
      const categoryList = [];
      this.equipData.forEach((item) => {
        categoryList.push(item.id);
      });
      // 获取设备得图片
      const categoryListString = JSON.stringify(categoryList);
      let data = {
        cascade: [
          {
            name: "anchorList",
          },
          {
            name: "state",
          },
        ],
        filters: `category in ${categoryListString}`,
        pageNumber: 1,
        pageSize: 1000,
      };
      this.local2 = this.$loading({ type: "global" });
      queryLegend(data)
        .then((res) => {
          if (res.content && res.content.length) {
            let list = this.choiceEquipList;
            res.content.forEach((contentType) => {
              list.forEach((item) => {
                if (item.classCode == contentType.category) {
                  item.url = contentType.state[0].pic;
                  item.state = contentType.state;
                }
              });
            });
            this.choiceEquipList = list;
          }
          // // 将选中的设备类存到vuex中
          bus.$emit("addEquipment", this.choiceEquipList);
          this.$loading.close(this.local2);
          this.modalClose();
        })
        .catch((res) => {
          console.log(res);
          this.$loading.close(this.local2);
          this.modalClose();
        });
    },
    // 搜索回车
    pressEnter() {
      this.currentPage = 1;
      this.queryEquip();
    },
    // /是否下拉折叠
    collapse(item) {
      item.showChildren = !item.showChildren;
    },
    // 删除item
    deleteItem(items, key) {
      let deleteItem = items.children.splice(key, 1);
      items.number = items.children.length;
      this.$refs.multipleTable.toggleRowSelection(deleteItem[0]);
      let index = -1;
      this.choiceEquipList.forEach((item, i) => {
        if (item.id == deleteItem[0].id) {
          index = i;
        }
      });
      if (index >= 0) {
        this.choiceEquipList.splice(key, 1);
      }
      this.handleSelectionChange(this.choiceEquipList);
    },
    clearChoiceEqipment() {
      this.$refs.multipleTable.clearSelection();
    },
    /**
     * 构建树list
     * list 需要递归得数组
     * arr  需要返回得结果
     * nameList 要递归得判断条件
     * index 树得层
     */
    mapList(
      list,
      arr = [],
      nameList = ["id", "localName", "floor"],
      index = 0
    ) {
      index++;
      if (list.length) {
        list.forEach((item) => {
          if (item[nameList[2]] && item[nameList[2]].length) {
            const obj = {
              title: item[nameList[1]],
              id: item[nameList[0]],
              index: index,
              children: [],
            };
            const children = this.mapList(
              item[nameList[2]],
              [],
              nameList,
              index
            );
            obj.children = children;
            arr.push(obj);
          } else {
            arr.push({
              title: item[nameList[1]],
              id: item[nameList[0]],
              index: index,
            });
          }
        });
      }
      return arr;
    },
    // 选中table回调
    handleSelectionChange(list) {
      let arr = [];
      // this.choiceEquipList = this.choiceEquipList.concat(...list);
      this.choiceEquipList = list;
      list.forEach((item) => {
        if (arr.length) {
          let index = -1;
          arr.forEach((aItem) => {
            if (aItem.id == item.classCode) {
              index = 1;
              aItem.children.push(_.cloneDeep(item));
              aItem.number++;
            }
          });
          if (index == -1) {
            let obj = {
              id: item.classCode,
              title: item.codeName,
              children: [_.cloneDeep(item)],
              number: 1,
              showChildren: true,
            };
            arr.push(obj);
          }
        } else {
          let obj = {
            id: item.classCode,
            title: item.codeName,
            children: [],
            number: 1,
            showChildren: true,
          };
          obj.children.push(_.cloneDeep(item));
          arr.push(obj);
        }
      });
      this.equipData = arr;
    },
    // 切换分页
    currentChangeHandle(pageMsg) {
      this.pageSize = pageMsg.newPageSize;
      this.currentPage = pageMsg.newPage;
      this.queryEquip();
    },
    //  局部加载
    localLoading() {
      this.local = this.$loading({
        el: this.$refs.localDom,
        type: "local",
        size: "min",
      });
    },
    // 打开窗口初始化弹窗
    initAddModel() {
      const data = {
        projectId: this.projectId,
      };
      // 建筑查询条件
      buildiFloor(data).then((res) => {
        this.buildFloorList = this.mapList(res.content);
      });
      // 设备类型查询条件
      readCategory(data).then((res) => {
        this.categoryList = this.mapList(
          res.content,
          [],
          ["code", "name", "children"]
        );
      });
      // 设置table的高
      setTimeout(() => {
        const domLeft = document.getElementById("left");
        if (domLeft) {
          this.tableHeight = domLeft.offsetHeight - 140;
          // 调取设备接口
          this.queryEquip();
        }
      });
      // 清空选中的item;
      this.choiceEquipList = [];
      // 清空右侧二级树
      this.equipData = [];
    },
  },
  watch: {
    // 是否打开弹窗
    showAddItemModel(val) {
      this.isShowModel = val;
      if (val) {
        this.initAddModel();
      }
    },
    // 监听设备变化，获取设备时做相应的过滤
    equipmentItemNum: {
      handler: function (val) {
        if (!val) return;
        const idList = [];
        this.equipmentItemList.forEach((item) => {
          idList.push(item.legendData.attachObjectIds[0]);
        });
        const filtIdListString = idList.length
          ? ";not id in " + JSON.stringify(idList)
          : "";
        this.filtIdListString = filtIdListString;
      },
      deep: true,
      immediate: true,
    },
  },
};
</script>
<style lang="less" scoped>
ul,
li {
  margin: 0;
  padding: 0;
  list-style-type: none;
}
.getItemModal {
  height: calc(~"100% - 110px");
  .getItem {
    height: calc(~"100% - 110px");
    display: flex;
    margin: 0 32px 16px 32px;
    border: 1px solid #e4e5e7;
    position: relative;
    top: 16px;
    .xxx {
      width: 100%;
      position: relative;
      // height: 100%;
    }
  }
  /deep/ .p-modal-main .p-modal-content-full {
    height: calc(100vh - 56px) !important;
  }
  /deep/ .p-modal-main .p-modal-content-full .p-modal-content-main {
    height: 100% !important;
  }

  .right {
    width: 420px;
    height: 100%;
    overflow-y: scroll;
    border-left: 1px solid #eff0f1;
    .top {
      height: 58px;
      border-bottom: 1px solid #eff0f1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      box-sizing: border-box;
      padding: 0 12px 0 12px;
      .top-l {
        display: flex;
        .equip-title {
          font-size: 14px;
          color: #8d9399;
        }
        .equip-num {
          font-size: 14px;
          margin-left: 12px;
          color: #1f2429;
          background: #eff0f1;
          padding: 0 10px 0 10px;
        }
      }
      .top-r {
        color: #0091ff;
        cursor: pointer;
      }
    }
    .choiceList {
      .choiceList-item {
        .treeList {
          width: 100%;
          .title {
            width: 100%;
            height: 40px;
            box-sizing: border-box;
            padding: 0 16px 0 16px;
            display: flex;
            align-items: center;
            line-height: 40px;
            .equip-title {
              font-size: 14px;
              color: #8d9399;
              line-height: 14px;
              cursor: pointer;
            }
            .equip-num {
              font-size: 14px;
              margin-left: 12px;
              color: #1f2429;
              background: #eff0f1;
              padding: 0 10px 0 10px;
              line-height: 24px;
            }
            .caret-icon {
              animation: nowhirling 0.2s linear forwards;
            }
            .caret-icon-active {
              animation: whirling 0.2s linear forwards;
            }
          }
          .treeList-bodys {
            .treeList-item {
              width: 100%;
              height: 40px;
              display: flex;
              align-items: center;
              justify-content: space-between;
              box-sizing: border-box;
              padding: 0 16px 0 50px;
              cursor: pointer;
              &:hover {
                background: #f5f6f7;
              }
            }
          }
        }
      }
    }
  }
  .left {
    flex: 1;
    position: relative;
    .top {
      width: 100%;
      height: 58px;
      border-bottom: 1px solid #eff0f1;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      &:first-child {
        margin-right: 24px;
      }
      &:last-child {
        margin-left: 24px;
      }
    }
    .page-box {
      position: absolute;
      right: 24px;
      bottom: 24px;
    }
  }
  .btn-list {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    margin-top: 24px;
    padding-right: 32px;
    box-sizing: border-box;
  }
}
@keyframes whirling {
  0% {
    transform: rotate(-90deg);
    -ms-transform: rotate(-90deg); /* Internet Explorer */
    -moz-transform: rotate(-90deg); /* Firefox */
    -webkit-transform: rotate(-90deg); /* Safari 和 Chrome */
    -o-transform: rotate(-90deg); /* Opera */
  }
  100% {
    transform: rotate(0deg);
    -ms-transform: rotate(0deg); /* Internet Explorer */
    -moz-transform: rotate(0deg); /* Firefox */
    -webkit-transform: rotate(0deg); /* Safari 和 Chrome */
    -o-transform: rotate(0deg); /* Opera */
  }
}
@keyframes nowhirling {
  0% {
    transform: rotate(0deg);
    -ms-transform: rotate(0deg); /* Internet Explorer */
    -moz-transform: rotate(0deg); /* Firefox */
    -webkit-transform: rotate(0deg); /* Safari 和 Chrome */
    -o-transform: rotate(0deg); /* Opera */
  }
  100% {
    transform: rotate(-90deg);
    -ms-transform: rotate(-90deg); /* Internet Explorer */
    -moz-transform: rotate(-90deg); /* Firefox */
    -webkit-transform: rotate(-90deg); /* Safari 和 Chrome */
    -o-transform: rotate(-90deg); /* Opera */
  }
}
</style>