<template>
  <div id="handsontable" v-loading="isLoading">
    <el-row class="left">
      <!-- <div style="display: inline-block" v-show="zoneCode === 'OtherZone'">
        <el-button @click="addZoneBtn" type="primary">添加分区</el-button>
        <el-select v-model="OtherValue" placeholder="请选择分区类型" @change="changeOtherZone">
          <el-option v-for="item in OtherList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        &nbsp;&nbsp; | &nbsp;&nbsp;
      </div> -->
      <el-select
        v-model="onlyRead"
        @change="getData(false)"
        style="width: 100px; margin-right: 20px; vertical-align: bottom"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
      <el-select
        v-model="showType"
        @change="handleChangeShowType"
        style="width: 140px; margin-right: 10px; vertical-align: bottom"
      >
        <el-option
          v-for="item in showTypes"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
      <el-select
        v-show="zoneCode"
        v-model="showInfoList"
        filterable
        clearable
        multiple
        collapse-tags
        @change="initHot"
        style="width: 200px; margin-right: 8px; vertical-align: bottom"
        placeholder="请选择信息点"
      >
        <el-option
          v-for="item in headerOptions"
          :key="item.code"
          :label="item.name"
          :value="item.code"
        >
        </el-option>
      </el-select>
      <el-button v-show="!onlyRead" @click="addSp">添加</el-button>
      <el-button @click="reset">刷新</el-button>
      <el-button v-show="!onlyRead" @click="undo">撤销</el-button>
      <el-tooltip
        class="item"
        effect="dark"
        content="按照业务空间Id | 本地名称 | 本地编码关键字搜索"
        placement="top-start"
      >
        <el-input
          v-model="keyWord"
          clearable
          placeholder="请输入关键字"
          @keyup.enter.native="getData"
          style="display: inline-block; width: 500px; margin-left: 20px"
        >
          <i
            slot="suffix"
            class="el-input__icon el-icon-search"
            @click="getData"
          ></i>
        </el-input>
      </el-tooltip>
      <el-checkbox
        style="float: right"
        v-model="isShowDelivered"
        @change="getHeader(classCode, buildFloorSelectd)"
        >显示有值信息点</el-checkbox
      >
    </el-row>
    <div v-show="main && main.length" :id="id"></div>
    <div
      class="center"
      v-show="!main || !main.length"
      style="height: 400px; padding-top: 140px; box-sizing: border-box"
    >
      <i class="icon-wushuju iconfont"></i>
      暂无数据
    </div>
    <!-- <add-business :buildMess="buildMess" :dialog="dialog"></add-business> -->
    <el-pagination
      class="right"
      v-show="main && main.length"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page.pageNumber"
      :page-sizes="page.pageSizes"
      :page-size="page.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.total"
    >
    </el-pagination>
    <!-- <div class="right" v-show="main && main.length">
      <my-pagination :page="page" @change="pageChange"></my-pagination>
    </div> -->
    <!-- 二维码弹窗 -->
    <qrcode
      :dialog="dialog"
      :qrcodeUrl="qrcodeUrl"
      :addBody="true"
      ref="qrcode"
    ></qrcode>
    <!--      上传图片-->
    <upload-img-dialog
      :read="onlyRead"
      @changeFile="imgChange"
      :keysArr="imgsArr"
      :dialog="myDialog"
    />
    <dialogZone ref="zone" @createSuccess="getOtherType" />
    <!-- 多选枚举类型维护 -->
    <menum
      :dialog="myDialog"
      :updateInfoData="updateInfoData"
      :updateInput="updateInput"
      @change="handleChangeMenum"
    ></menum>
    <!-- 不支持的输入方式 -->
    <el-dialog
      title="临时维护信息点"
      :visible.sync="myDialog.update"
      @close="handleCloseUpdate"
      width="670px"
    >
      <el-row>
        该信息点未定义对应组件，现在维护数据不确定后续是否可用。如确实需要维护，请点击
        <el-link
          @click="updateInputShow = true"
          type="primary"
          :underline="false"
          >继续维护</el-link
        >
        。
      </el-row>
      <el-row style="margin-top: 20px" v-show="updateInputShow">
        <el-input
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 8 }"
          placeholder="请输入内容"
          v-model="updateInput"
        ></el-input>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="myDialog.update = false">取 消</el-button>
        <el-button type="primary" @click="handleClickUpdate">确 认</el-button>
      </span>
    </el-dialog>
    <!-- 新增业务空间 -->
    <el-dialog
      title="确定新增业务空间的分区类型"
      :visible.sync="myDialog.addSpace"
      width="670px"
    >
      <el-row>
        <space-cascader ref="cascader" @change="changeAddType"></space-cascader>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="toAddSpace">下 一 步</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
// 引用handsontable插件
import "@/assets/js/chosen.jquery.min";
import tools from "@/utils/old-adm/scan/tools";
import "@/assets/js/handsontable-chosen-editor";
import lStorage from "@/utils/old-adm/localStorage";
import myPagination from "@/components/old-adm/common/myPagination";
import showTools from "@/utils/old-adm/handsontable/notShow";
import handsonUtils from "@/utils/old-adm/hasontableUtils";
import Handsontable from "handsontable-pro";
import buildFloor from "@/utils/old-adm/handsontable/buildFloorData";
import spaceCascader from "@/components/old-adm/ledger/components/lib/spaceSelect";
import "handsontable-pro/dist/handsontable.full.css";
import uploadImgDialog from "@/components/old-adm/business_space/dialogs/list/uploadImgDialog";
import menum from "@/components/old-adm/dialogs/list/menum";
import qrcode from "@/components/old-adm/ledger/components/lib/qrcode";
import ScanController from "@/controller/old-adm/ScanController";
import { businessSpaceController } from "@/controller/old-adm/businessSpaceController";
import Dic from "@/controller/old-adm/dicController";
import { mapGetters } from "vuex";
import dialogZone from "../../ledger/components/addDialog/dialogZone";

export default {
  props: {
    id: {},
    zoneCode: {},
    otherType: String,
  },
  components: {
    qrcode, //二维码页面
    myPagination,
    uploadImgDialog,
    dialogZone,
    spaceCascader,
    menum,
  },
  computed: {
    ...mapGetters("layout", ["projectId", "secret", "userId", "group_code"]),
    showTypes() {
      return this.onlyRead
        ? [
            { value: "Visible", label: "只看需交付的" },
            { value: "all", label: "全部" },
          ]
        : [
            { value: "Visible", label: "只看需交付的" },
            { value: "all", label: "全部" },
          ];
    },
  },
  data() {
    return {
      dialog: {
        qrcode: false, //二维码弹窗
        addDevice: false,
      },
      qrcodeUrl: "", //二维码图片地址
      headers: null,
      main: [],
      hot: null,
      isLoading: true,
      options: [
        {
          value: true,
          label: "只读模式",
        },
        {
          value: false,
          label: "编辑模式",
        },
      ],
      onlyRead: true,
      showType: "Visible",
      page: {
        pageSize: 50,
        pageSizes: [10, 20, 50, 100],
        pageNumber: 1,
        total: 0,
      },
      param: {
        ProjId: this.projectId, //项目id
        UserId: this.userId, //用户id
        secret: this.secret,
      },
      buildMess: null,
      filtersArr: [], //表格数据被过滤后的下标
      copyMain: [], //深拷贝数组
      buildFloorData: [], //楼层数据
      keyWord: "",
      inputMap: {
        flowBuild: {
          editable: true,
          code: "flowBuild",
          name: "建筑楼层",
          path: "flowBuild",
          category: "STATIC",
          dataType: "ENUM",
        },
      }, //信息点和输入方式映射表
      updateInputShow: false, //是否显示临时维护输入框
      updateInfoData: {}, //当前信息点信息
      updateInfoPoint: "", //临时维护信息点
      updateInput: "", //临时维护信息点值
      myDialog: {
        uploadImgs: false, //上传图片弹窗
        update: false, //临时维护信息点
        addSpace: false, //批量添加业务空间
        menum: false, //临时多选枚举类型信息点
      },
      imgsArr: [], //空间图片
      OtherList: [], //其他分区筛选框
      OtherValue: "",
      addData: {},
      headerOptions: [], // 信息点选项列表
      showInfoList: [], // 筛选的信息点列表
      classCode: "", // 空间类型
      isShowDelivered: false, // 是否显示已交付的信息点
    };
  },
  created() {
    this.setData();
    buildFloor.getData(this.buildFloorData);
  },
  mounted() {},
  methods: {
    setData() {
      this.param.ProjId = this.projectId;
      this.param.UserId = this.userId;
      this.param.secret = this.secret;
    },
    //获取表格数据
    getHeader(classCode, buildFloorSelectd) {
      this.classCode = classCode;
      this.buildFloorSelectd = buildFloorSelectd;
      // 清空筛选的信息点列表
      this.showInfoList = [];
      // 查询已交付的信息点
      if (this.isShowDelivered) {
        this.getDeliveredInfos(classCode);
      } else {
        // 查询全部信息点
        this.getDataDictionary(classCode);
      }
    },
    /**
     * 查询已交付的信息点
     * @param classCode 设备类型
     */
    getDeliveredInfos(classCode) {
      let params = {
        classCode: classCode,
        objType: "space",
      };
      if (this.buildFloorSelectd.length === 1) {
        switch (this.buildFloorSelectd[0]) {
          case "noKnow":
            params.buildingId = "isNull";
            break;
          case "all":
            break;
        }
      } else if (this.buildFloorSelectd.length === 2) {
        switch (this.buildFloorSelectd[1]) {
          case "noKnow":
            params.buildingId = this.buildFloorSelectd[0];
            params.floorId = "isNull";
            break;
          case "all":
            params.buildingId = this.buildFloorSelectd[0];
            break;
          default:
            params.buildingId = this.buildFloorSelectd[0];
            params.floorId = this.buildFloorSelectd[1];
        }
      }
      Dic.deliveredInfos(params, (res) => {
        this.headers = res.content;
        this.codeToDataSource = {};
        this.headers.forEach((item) => {
          if (item.path) {
            this.inputMap[item.path] = item;
          }
          if (item.dataSource) {
            try {
              this.codeToDataSource[item.code] = {};
              item.dataSource.forEach((dic) => {
                this.codeToDataSource[item.code][dic.code] = dic.name;
              });
            } catch (e) {
              console.log(e);
            }
          }
        });
        this.page.pageNumber = 1;
        this.getData();
      });
    },
    /**
     * 查询全部信息点
     * @param classCode 设备类型
     */
    getDataDictionary(classCode) {
      let params = {
        orders: "sort asc, name desc",
        pageNumber: 1,
        pageSize: 1000,
        type: classCode,
      };
      Dic.getDataDictionary(params, (res) => {
        this.headers = res.content;
        this.codeToDataSource = {};
        this.headers.forEach((item) => {
          if (item.path) {
            this.inputMap[item.path] = item;
          }
          if (item.dataSource) {
            try {
              this.codeToDataSource[item.code] = {};
              item.dataSource.forEach((dic) => {
                this.codeToDataSource[item.code][dic.code] = dic.name;
              });
            } catch (e) {
              console.log(e);
            }
          }
        });
        this.page.pageNumber = 1;
        this.getData();
      });
    },
    getData() {
      this.zoneParam = {
        zoneType: this.zoneCode,
        pageNumber: this.page.pageNumber,
        pageSize: this.page.pageSize,
        orders: "createTime desc, localName desc, localId desc, id asc",
      };
      if (this.buildFloorSelectd.length === 1) {
        switch (this.buildFloorSelectd[0]) {
          case "noKnow":
            this.zoneParam.buildingId = "isnull";
            break;
          case "all":
            // params.BuildingId = '';
            break;
        }
      } else if (this.buildFloorSelectd.length === 2) {
        switch (this.buildFloorSelectd[1]) {
          case "noKnow":
            this.zoneParam.buildingId = this.buildFloorSelectd[0];
            this.zoneParam.floorId = "isnull";
            break;
          case "all":
            this.zoneParam.buildingId = this.buildFloorSelectd[0];
            // params.FloorId = '';
            break;
          default:
            this.zoneParam.buildingId = this.buildFloorSelectd[0];
            this.zoneParam.floorId = this.buildFloorSelectd[1];
        }
      }
      if (this.keyWord) {
        this.zoneParam.Filters = `id="${this.keyWord}" || localName contain '${this.keyWord}' || localId contain '${this.keyWord}'`;
      }
      this.isLoading = true;
      this.getZoneMessage(this.zoneParam);
      /**
       * TODO: 其他分区下已不再划分分区（注释的代码是其他分区下再划分分区的代码）
       */
      //   if (this.zoneCode != 'OtherZone') {
      // this.isLoading = true
      // this.getZoneMessage(this.zoneParam)
      //   } else {
      // 其他分区类型查询表数据接口
      // if (localStorage.getItem('otherZone')) {
      //   // this.OtherValue = (localStorage.getItem('otherZone'))
      //   localStorage.removeItem('otherZone')
      // }
      // if (this.OtherValue) {
      //   this.zoneParam.ZoneType = this.OtherValue;
      //   this.getZoneMessage(this.zoneParam)
      // } else {
      //   this.main = []
      // }
      // this.isLoading = false
      // this.getOtherType();
      //   }
    },
    //查询空间信息
    getZoneMessage(param) {
      let params = param;
      params.orders = "createTime desc,localName desc,id desc";
      ScanController.zoneQuery(params, (res) => {
        this.page.total = res.total;
        this.main = res.content.map((item) => {
          if (
            item.hasOwnProperty("buildingId") &&
            item.hasOwnProperty("floorId")
          ) {
            item.flowBuild = item.buildingId + "-" + item.floorId;
          } else if (
            item.hasOwnProperty("buildingId") &&
            !item.hasOwnProperty("floorId")
          ) {
            item.flowBuild = item.buildingId;
          }
          // if (item.outline) {
          //   item.outline = JSON.stringify(item.outline)
          // }
          return item;
        });

        if (this.main && this.main.length && this.main[0].id) {
          this.copyMain = tools.deepCopy(this.main);
          if (this.onlyRead) {
            this.getBatch(this.main);
          }
        }
        this.isLoading = false;
        this.getMain();
      });
    },
    //获取表格主体内容
    getMain() {
      if (!!this.hot) {
        this.hot.destroy();
        this.hot = null;
      }
      this.$nextTick(() => {
        this.initHot();
      });
    },
    /**
     * 筛选要展示的表头函数
     */
    filterShowInfo(list) {
      let arr = this.headers.filter((item) => {
        return (
          item.code === "localId" ||
          item.code === "localName" ||
          list.includes(item.code)
        );
      });
      return arr;
    },
    //初始化handsontable组件
    initHot() {
      var container = document.getElementById(this.id);
      let winHeight = document.documentElement.clientHeight;
      if (this.hot) {
        this.hot.destroy();
        this.hot = null;
      }
      this.hot = new Handsontable(container, {
        data: this.main,
        colHeaders: this.delHeader(
          this.showInfoList.length
            ? this.filterShowInfo(this.showInfoList)
            : this.headers
        ), //表头文案
        columns: this.getType(
          this.showInfoList.length
            ? this.filterShowInfo(this.showInfoList)
            : this.headers
        ), //数据显示格式
        filters: true,
        fixedColumnsLeft: 4,
        maxRows: this.main ? this.main.length : "",
        height: winHeight - 100 - 50 - 176,
        columnSorting: true, //添加排序
        sortIndicator: true, //添加排序
        renderAllRows: true,
        autoColumnSize: true,
        // observeChanges: false,
        language: "zh-CN",
        manualColumnResize: true,
        fillHandle: "vertical", //允许纵向填充
        manualColumnMove: true,
        dropdownMenu: [
          "filter_by_condition",
          "filter_by_value",
          "filter_action_bar",
        ],
        contextMenu: this.onlyRead
          ? false
          : {
              items: {
                remove_row: {
                  name: "删除该业务空间",
                },
              },
            },
        // 事件
        afterChange: this.tdChange, //修改后
        afterFilter: this.trimmedRows, //排序前
        afterRemoveRow: this.romoveFm, //右键删除
        afterOnCellMouseDown: this.eventClick, //鼠标点击
      });
      let pro = document.getElementById("hot-display-license-info");
      if (!!pro) {
        pro.parentNode.removeChild(pro);
      }
    },
    //表格中的查看详情
    eventClick(el, rowArr) {
      let filter = this.filtersArr;
      //被筛选过后的数组
      let trimmedArr = this.trimmedRows();
      //是否启用了排序
      let isSort = this.hot.getPlugin("columnSorting").isSorted();
      //
      if (trimmedArr.length && isSort) {
        let sortArr =
          this.myHotArr.getPlugin("columnSorting").rowsMapper.__arrayMap;
        let infos = this.main[trimmedArr[sortArr[rowArr.row]]];
        this.getInfors(infos, rowArr);
      } else if (isSort) {
        //排序后的数组
        let sortArr = this.hot.getPlugin("columnSorting").rowsMapper.__arrayMap;
        let infos = this.main[sortArr[rowArr.row]];
        this.getInfors(infos, rowArr);
      } else if (trimmedArr.length) {
        let infos = this.main[trimmedArr[rowArr.row]];
        this.getInfors(infos, rowArr);
      } else {
        let infos = this.main[rowArr.row];
        this.getInfors(infos, rowArr);
      }
    },
    getInfors(infos, row) {
      let val = this.hot.colToProp(row.col);
      this.row = row.row;
      let inputData = this.inputMap[val];
      lStorage.set("screen_data", {
        path: this.$route.path,
        data: { RoomID: infos.id, zone: this.zoneCode },
      });
      if (val == "point") {
        let query = {
          RoomID: infos.id,
          zone: this.zoneCode,
          isMyTab: 2,
          buildFloorSelectd: this.buildFloorSelectd,
        };
        this.$router.push({
          path: "/ledger/spaceDetail",
          query: query,
        });
      } else if (val == "RoomQRCode") {
        this.qrcodeUrl = this.main[row.row].RoomQRCode;
        if (!!this.qrcodeUrl) {
          this.dialog.qrcode = true;
        } else {
          this.$message("此空间没有二维码");
        }
      } else if (val == "pic") {
        let Picdata = tools.dataForKey(this.main[row.row], val);
        this.imgsArr = Picdata ? Picdata : [];
        if (!this.onlyRead || this.imgsArr.length) {
          this.myDialog.uploadImgs = true;
        }
      }
      // 维护多选枚举值
      if (!this.onlyRead && inputData.dataType == "MENUM") {
        this.updateInfoData = inputData;
        this.updateInfoPoint = val;
        this.updateInput = tools.dataForKey(this.main[row.row], val);
        this.myDialog.menum = true;
        return false;
      }
      if (!this.onlyRead && !inputData.editable) {
        this.$confirm("该信息点的值为自动生成，不可人工维护！", "提示", {
          confirmButtonText: "我知道了",
          showCancelButton: false,
          type: "warning",
          center: true,
        }).then(() => {
          return false;
        });
      }
      if (
        !this.onlyRead &&
        showTools.inputModeArr.indexOf(inputData.dataType) == "-1"
      ) {
        this.updateInfoPoint = val;
        this.updateInput = tools.dataForKey(this.main[row.row], val);
        this.myDialog.update = true;
        return false;
      }
    },
    //关闭临时维护弹窗回调
    handleCloseUpdate() {
      this.updateInputShow = false;
      this.updateInfoPoint = "";
      this.updateInput = "";
    },
    //更新临时维护信息点
    handleClickUpdate() {
      tools.setDataForKey(
        this.main[this.row],
        this.updateInfoPoint,
        this.updateInput
      );
      this.tdChange(
        [[this.row, this.updateInfoPoint, null, this.updateInput]],
        "edit"
      );
      this.updateInputShow = false;
      this.myDialog.update = false;
      this.updateInput = "";
    },
    //多选枚举类型值修改
    handleChangeMenum(newValue) {
      tools.setDataForKey(this.main[this.row], this.updateInfoPoint, newValue);
      this.tdChange([[this.row, this.updateInfoPoint, null, newValue]], "edit");
      this.myDialog.menum = false;
      this.updateInput = "";
    },
    //表格发生更改
    tdChange(changeData, source) {
      if (!this.onlyRead) {
        if (changeData) {
          let trimmedArr = this.trimmedRows();
          let param = handsonUtils.getParam(
            changeData,
            source,
            this.hot,
            trimmedArr
          );
          let data = [];
          for (let i = 0; i < param.length; i++) {
            if (param[i].id) {
              data.push(param[i]);
            } else {
              this.handleCreateZone(param[i]);
            }
          }
          //如果data中包含/且data长度为1,将其转换成.
          if (changeData.length == 1 && changeData[0][1].indexOf("/") > 0) {
            changeData[0][1] = changeData[0][1].split("/").join(".");
          }

          // 存在data进行修改请求
          if (data && data.length) {
            this.updateBusiness(data, changeData);
          }
        }
      }
    },
    //右键删除
    romoveFm() {
      let params = tools.differenceArr(this.main, this.copyMain);
      if (params.length < 1 || this.main > this.copyMain) {
        return;
      }
      let param = [];
      params.map((item) => {
        if (item.id) param.push({ id: item.id });
      });
      params.map(
        (i) =>
          (i.ObjectType = this.zoneParam.ZoneType
            ? this.zoneParam.ZoneType
            : i.ObjectType)
      );
      this.$confirm("此操作将删除业务空间，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          ScanController.zoneDelete(param, (res) => {
            switch (res.result) {
              case "success":
                this.$message.success("删除成功");
                this.getData();
                break;
              default:
                this.$message.error("删除失败" + res.message);
                break;
            }
          });
        })
        .catch(() => {
          this.getData();
          this.$message("取消删除");
        });
    },
    //创建业务空间
    handleCreateZone(param) {
      let keys = Object.keys(param);
      keys.map((key) => {
        //将值为空字符串的属性删除
        if (param[key] == "") {
          delete param[key];
        }
      });
      if (!param.localName) {
        this.$message("新增业务空间本地名称不能为空!");
        return;
      }
      if (!Object.keys(param).length) {
        this.$message("新添加业务空间内容不能为空!");
        return;
      }
      if (param.flowBuild) {
        param.buildingId = param.flowBuild.split("-")[0];
        param.floorId = param.flowBuild.split("-")[1] || null;
      } else {
        if (this.buildFloorSelectd) {
          if (
            this.buildFloorSelectd[0] != "all" &&
            this.buildFloorSelectd[0] != "noKnow"
          ) {
            param.buildingId = this.buildFloorSelectd[0];
          }
          if (
            this.buildFloorSelectd[1] &&
            this.buildFloorSelectd[1] != "all" &&
            this.buildFloorSelectd[1] != "noKnow"
          ) {
            param.floorId = this.buildFloorSelectd[1];
          }
        }
      }
      param.classCode = this.zoneParam.ZoneType
        ? this.zoneParam.ZoneType
        : this.zoneCode;
      let params = {
        content: [param],
      };
      ScanController.zoneCreate(params, (res) => {
        switch (res.result) {
          case "success":
            this.$message.success("添加成功");
            this.getData();
            break;
          default:
            this.$message.error("添加失败" + res.message);
            break;
        }
      });
    },
    // 修改
    updateBusiness(data, change) {
      let param = {
        data: {
          content: [],
          projection: [],
        },
        zone: this.zoneCode,
      };
      let keyList = [];
      //生成要修改字段列表
      change.map((item) => {
        /** 添加需更新的字段 */
        if (item[1] && keyList.indexOf(item[1]) == -1) {
          keyList.push(item[1]);
        }
        /** 添加建筑楼层字段（判断是否更新建筑楼层关系和空间的关系） */
        if (item[1] == "flowBuild" && keyList.indexOf(item[1]) == -1) {
          param.data.projection.push("BuildingId", "FloorId");
        }
      });
      //生成对应修改数据
      data.map((item, index) => {
        let nullList = [];
        keyList.map((value) => {
          if (value == "BuildingId") {
            let itemData = tools.dataForKey(item, "flowBuild");
            if (itemData == "") {
              tools.setDataForKey(item, "BuildingId", null);
              tools.setDataForKey(item, "FloorId", null);
              nullList.push("BuildingId", "FloorId");
            } else {
              let BuildingId = itemData.split("-")[0];
              let FloorId = itemData.split("-")[1];
              if (BuildingId && FloorId) {
                tools.setDataForKey(item, "BuildingId", BuildingId);
                tools.setDataForKey(item, "FloorId", FloorId);
              } else if (BuildingId && !FloorId) {
                tools.setDataForKey(item, "BuildingId", BuildingId);
                tools.setDataForKey(item, "FloorId", null);
                nullList.push("FloorId");
              }
            }
          } else {
            let itemData = tools.dataForKey(item, value);
            tools.setDataForKey(item, value, itemData == "" ? null : itemData);
            // 数据为空加入置空列表（空数据类型包含： undefind / "" / null ）
            itemData || nullList.push(value);
          }
        });
        // 置空列表不为空
        if (nullList.length) {
          // 深拷贝需更新的对象，并添加置空列表
          const updateItem = JSON.parse(JSON.stringify(item));
          updateItem.nullList = nullList;
          param.data.content.push(updateItem);
        } else {
          // 无置空内容
          param.data.content.push(item);
        }
      });
      if (param.data.projection.indexOf("BuildingId") > -1) {
        let pa = param.data.content.map((t) => {
          return {
            type: this.zoneCode,
            spaceId: t.id,
            id: t.FloorId || t.BuildingId || null,
          };
        });
        ScanController.handleZoneUpdateBd(pa, (res) => {
          switch (res.result) {
            case "success":
              this.$message.success("修改成功");
              break;
            default:
              this.$message.error("修改失败" + res.message);
              break;
          }
        });
        // Orders: "createTime desc, EquipLocalName desc, EquipLocalID desc, EquipID desc"
        // updateRelateInSpAndBuild(pa, res => {
        //   this.$message.success('修改成功')
        // })
      } else {
        // updateZone(param, (res) => {
        // })
        let obj = param.data.content.map((i) => {
          i.Outline =
            typeof i.Outline == "string" ? JSON.parse(i.Outline) : i.Outline;
          return {
            ...i,
            ObjectType: this.zoneParam.ZoneType || i.ObjectType,
          };
        });
        let updateParam = {
          content: obj,
        };
        ScanController.zoneUpdate(updateParam, (res) => {
          switch (res.result) {
            case "success":
              this.$message.success("更新成功");
              break;
            default:
              this.$message.error("更新失败" + res.message);
              break;
          }
        });
      }
    },
    //获取被筛选掉的行号
    trimmedRows() {
      // var plugin = hot.getPlugin('trimRows').trimmedRows;//获取被筛选掉的行号
      var plugin = this.hot.getPlugin("trimRows").trimmedRows;
      let dataLength = this.main.length;
      let dataArr = new Array();
      for (let i = 0; i < dataLength; i++) {
        dataArr.push(i);
      }
      if (plugin.length <= 0) {
        dataArr = undefined;
      } else {
        dataArr = this.array_diff(dataArr, plugin);
      }
      this.filtersArr = dataArr;
      return dataArr || [];
      // var DataArray = new Array();
      // for (var i = 0; i < plugin.length; i++) {
      //     // 通过行号获取数据
      //     DataArray.push(this.hot.getSourceDataAtRow(plugin[i]));
      // }
    },
    //去除数组中相同的元素
    array_diff(a, b) {
      for (var i = 0; i < b.length; i++) {
        for (var j = 0; j < a.length; j++) {
          if (a[j] == b[i]) {
            a.splice(j, 1);
            j = j - 1;
          }
        }
      }
      return a;
    },
    //获取动态参数
    getBatch(data) {
      let param = {
        groupCode: this.group_code,
        appId: "datacenter",
        projectId: this.projectId,
        data: [],
      };
      this.headers.map((head) => {
        if (head.category != "STATIC") {
          data.map((item) => {
            let cur = tools.dataForKey(item, head.path);
            if (cur) {
              param.data.push({
                objectId: item.id,
                infoCode: head.code,
              });
            }
          });
        }
      });
      if (param.data.length) {
        ScanController.BeatchQueryParam(param, (res) => {
          if (!this.onlyRead) {
            return false;
          }
          this.main = data.map((item) => {
            res.data.map((child) => {
              if (item.id == child.objectId) {
                if (child.data || child.data == 0) {
                  this.headers.map((head) => {
                    if (head.code == child.infoCode) {
                      let contentVal = child.data;
                      if (this.codeToDataSource[child.infoCode]) {
                        contentVal =
                          this.codeToDataSource[child.infoCode][child.data];
                      }
                      tools.setDataForKey(item, head.path, contentVal);
                    }
                  });
                } else {
                  this.headers.map((head) => {
                    if (head.code == child.infoCode) {
                      tools.setDataForKey(
                        item,
                        head.path,
                        child.error
                          ? child.value
                            ? "表号功能号格式错误"
                            : "表号功能号不存在"
                          : "暂未采集到实时数据"
                      );
                    }
                  });
                }
              }
            });
            return item;
          });
          this.hot.loadData(this.main);
        });
      }
    },
    /**
     * 切换信息点查看类型
     */
    handleChangeShowType() {
      this.showInfoList = [];
      this.initHot();
    },
    /**
     * 表头文案处理函数
     * @param list header数组数据
     *
     * @return 处理好的文案
     */
    delHeader(list) {
      let arr = tools.copyArr(list);
      let data = showTools.headerTextFilter(
        arr,
        "space",
        this.onlyRead,
        this.showType
      );
      data.unshift("是否关联平面图", "与空间相关联的设备");
      if (this.showType == "all") {
        data.splice(4, 0, "所属建筑楼层");
      }
      return data;
    },
    /**
     * 表头数据处理函数
     * @param arr header数组数据
     *
     * @return 处理好的数据格式
     */
    getType(list) {
      let arr = tools.copyArr(list);
      let data = showTools.headerTypeFilter(
        arr,
        "space",
        this.onlyRead,
        this.showType
      );
      this.headerOptions =
        this.showType === "all"
          ? tools.copyArr(this.headers)
          : this.headers.filter((item) => item.visible);
      data.unshift(
        {
          data: "outline",
          renderer: this.myRenderer,
          readOnly: true,
        },
        {
          data: "point",
          renderer: this.facilityRender,
          readOnly: true,
        }
      );
      if (this.showType == "all") {
        data.splice(4, 0, {
          data: "flowBuild",
          renderer: tools.customDropdownRenderer,
          editor: "chosen",
          chosenOptions: {
            data: this.buildFloorData,
          },
          readOnly: this.onlyRead,
        });
      }
      return data;
    },
    myRenderer(instance, td, row, col, prop, value, cellProperties) {
      if (value && value.length && value[0]) {
        td.innerHTML = "已关联";
      } else {
        td.innerHTML = "未关联";
      }
      return td;
    },
    facilityRender(instance, td, row, col, prop, value, cellProperties) {
      td.style.color = "#409EFF";
      td.style.cursor = "pointer";
      td.innerHTML = "点击查看";
      return td;
    },
    /**  页面中的按钮事件--------------------------- */
    addSp() {
      this.myDialog.addSpace = true;
      // 其他分区 已删除在其他分区下添加子分区
      // if (this.zoneCode && this.zoneCode != 'OtherZone') {
      this.$nextTick(() => {
        this.$refs.cascader.setValue([this.zoneCode]);
      });
      // } else if (this.zoneCode == 'OtherZone' && this.OtherValue) {
      //   this.$nextTick(() => {
      //     this.$refs.cascader.setValue([this.zoneCode, this.OtherValue])
      //   })
      // }
      // 以下是直接在列表中添加的方法
      // if (this.main && this.main.length && this.main[0].RoomID) {
      //   this.hot.destroy()
      //   this.hot = null
      //   this.main.unshift({})
      //   this.getMain()
      // } else {
      //   if (this.main && this.main.length) {
      //     this.$message("请添加完成后继续添加")
      //   } else {
      //     this.main.unshift({})
      //     this.getMain()
      //   }
      // }
    },
    //下一步
    toAddSpace() {
      if (this.addData.spaceType) {
        this.$router.push({
          path: "/ledger/spaceadd",
          query: this.addData,
        });
      } else {
        this.$message("请选择要添加的业务空间类型！");
      }
    },
    //选择业务空间类型-添加业务空间
    changeAddType(val, item, value) {
      // if (value.length == 2 && value[0] == "OtherZone") {
      //   this.addData.spaceType = val;
      //   this.addData.otherType = value[0]
      //   this.addData.spaceName = `其他分区-${item.name}`;
      //   this.addData.showType = this.showType;
      //   this.addData.buildFloorSelectd = this.buildFloorSelectd;
      // } else {
      this.addData.spaceType = val;
      this.addData.spaceName = item.name;
      this.addData.showType = this.showType;
      this.addData.buildFloorSelectd = this.buildFloorSelectd;
      // }
    },
    //刷新
    reset() {
      this.getData();
    },
    //撤回操作
    undo() {
      this.hot.undo();
    },
    /**  分页事件------------------------ */
    //切换每页显示多少条数据
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.page.pageNumber = 1;
      this.getData();
    },
    //切换页数
    handleCurrentChange(val) {
      this.page.pageNumber = val;
      this.getData();
    },
    //上传图片弹窗触发事件
    imgChange(keys) {
      this.setDataToMain(keys, "pic", this.row);
    },
    //判断是否有值，有值赋值
    setDataToMain(data, key, row) {
      if (!!data && data != "--") {
        if (!!this.main[row]) {
          tools.setDataForKey(this.main[row], key, data);
          this.tdChange([[row, key, null, data]], "edit");
        } else {
          this.main[row] = {};
          tools.setDataForKey(this.main[row], key, data);
        }
      } else {
        tools.setDataForKey(this.main[row], key, "");
      }
      this.hot.render();
    },
    addZoneBtn() {
      this.$refs.zone.dialogFormVisible = true;
    },
    //  其他分区类型查询
    getOtherType() {
      let param = {
        cascade: [
          { name: "zoneType", filters: `projectId='${this.projectId}'` },
        ],
        filters: `code="otherZone"`,
      };
      businessSpaceController.queryAllZoneType(param, (res) => {
        if (res.content[0].zoneType && res.content[0].zoneType.length) {
          this.OtherList = res.content[0].zoneType.map((t) => {
            t.value = t.code;
            t.label = t.name;
            return t;
          });
        } else {
          this.OtherList = [];
        }
        if (this.otherType) {
          this.OtherValue = this.otherType;
          this.changeOtherZone(this.otherType);
        }
      });
    },
    // 其他类型下拉change
    changeOtherZone(val) {
      this.zoneParam.ZoneType = val;
      this.getZoneMessage(this.zoneParam);
      // if (localStorage.getItem('otherZone')) {
      //   localStorage.setItem('otherZone', val)
      // } else {
      //   localStorage.setItem('otherZone', val)
      // }
      console.log(val);
    },
  },

  watch: {
    projectId() {
      this.buildFloorData = [];
      buildFloor.getData(this.buildFloorData);
      this.setData();
      this.main = null;
    },
    showTypes: {
      handler(newName, oldName) {
        if (newName && newName[0] && newName[0].value) {
          this.showType = newName[0].value;
        } else {
          this.showType = "Visible";
        }
      },
      immediate: true,
      deep: true,
    },
  },
};
</script>
<style lang="less" scoped>
#handsontable {
  padding: 0 10px;

  .left {
    padding: 0;
    margin-bottom: 10px;
  }

  .no-data {
    height: 150px;
    line-height: 150px;
    text-align: center;
    color: gray;
  }
  /deep/ .el-select__tags-text {
    display: inline-block;
    max-width: 80px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  /deep/ .el-select .el-tag__close.el-icon-close {
    right: -4px;
    top: -6px;
  }
}
</style>
