<template>
  <div id="handsontable" v-loading="isLoading">
    <div style="overflow:hidden;margin-bottom:10px;margin-right:20px;height:50px;">
      <el-button
        @click="undo"
        size="small"
        style="float:right;margin-top:5px;margin-right:10px;"
        icon="iconfont icon-undo"
        circle
      ></el-button>
      <el-button
        @click="reset"
        size="small"
        style="float:right;margin-top:5px;margin-right:10px;"
        icon="iconfont icon-shuaxin"
        circle
      ></el-button>
      <el-button
        @click="addSp"
        size="small"
        style="float:right;margin-top:5px;margin-right:10px;"
        icon="iconfont icon-tianjia"
        circle
      ></el-button>
    </div>
    <div v-show="main &&main.length" :id="id"></div>
    <div class="no-data" v-show="!main || !main.length">暂无数据</div>
    <!-- <add-business :buildMess="buildMess" :dialog="dialog"></add-business> -->
    <my-pagination v-show="main &&main.length" :page="page" @change="pageChange"></my-pagination>
  </div>
</template>
<script>
// 引用handsontable插件
import "@/assets/js/chosen.jquery.min";
import tools from "@/assets/js/tools";
import "@/assets/js/handsontable-chosen-editor";
import myPagination from "@/components/lib/myPagination";
import addBusiness from "@/components/dialogs/addDialog/businessDialog"
import showTools from "@/utils/hansontable/notShow"
import {
  getSpaceHeader,
  getAllbusiness,
  updateBusiness,
  createBusiness,
  createBusinessList,
  delManySpace,
  isSpaceBuss
} from "@/api/request";
export default {
  props: {
    id: {
      type: String
    }
  },
  components: {
    myPagination,
    addBusiness
  },
  data() {
    return {
      dialog: {
        addDevice: false
      },
      headers: null,
      main: null,
      hot: null,
      tableData: [],
      isLoading: true,
      allData: null,
      page: {
        size: 50,
        sizes: [10, 30, 50, 100, 150, 200],
        total: 2,
        currentPage: 1
      },
      param: {
        ProjId: this.$route.query.projId, //项目id
        UserId: this.$route.query.userId, //用户id
        secret: this.$route.query.secret
      },
      buildMess: null,
      filtersArr: [], //表格数据被过滤后的下标
      copyMain: null, //深拷贝数组
      activeType: {}
    };
  },
  created() {
  },
  mounted() { },
  methods: {
    //获取表头
    getHeader(headers, activeTabType) {
      this.headers = headers.map(item => {
        let dataSoucse = item.DataSource
        console.log(dataSoucse)
        if (!dataSoucse) {
          return item
        }
        dataSoucse.map(keys => {
          if (!!keys.Content && keys.Content.length) {
            keys.Content.map(child => {
              dataSoucse.push({
                Code: child.Code,
                Name: child.Name,
              })
              if (!!child.Content && child.Content.length) {
                child.Content.map(node => {
                  dataSoucse.push({
                    Code: node.Code,
                    Name: node.Name,
                  })
                })
              }
            })
          }
        })
        return item
      });
      console.log(this.headers, "headers")
      this.activeType = activeTabType
    },


    getData(buildMess) {
      if (!!buildMess) {
        this.buildMess = buildMess;
      }
      let param = {
        id: this.buildMess.code,
        type: ["Sp"],
        data: {
          customInfo: true,
          criteria: {
            floor: this.buildMess.code, // 必填, 指定楼层id
            business_type: this.activeType.code, // 必填, 楼层下某个类型的业务空间PowerSupplyZone, 默认是空字符串
            rel_type: this.activeType.rel_type, // 必填, 指定业务类型的关系类型(参考数据平台),
            // 数字型字符串, 例如: 通用是99
          }
        },
        ProjId: this.param.ProjId,
        secret: this.param.secret
      };
      isSpaceBuss(param).then(res => {
        if (res.data.Result == "success") {
          this.allData = res.data.Content;
          this.page.total = res.data.Count;
          this.getMain(
            this.pagination(this.page.currentPage, this.page.size, this.allData)
          );
        } else {
          this.$message.error("请求错误");
        }
      });
    },

    //获取表格主体内容
    getMain(main) {
      this.main = main;
      if (this.main && this.main.length && this.main[0].id) {
        this.copyMain = tools.deepCopy(this.main);
      }
      this.isLoading = true;
      if (!!this.hot) {
        this.hot.destroy();
        this.hot = null;
      }
      this.$nextTick(() => {
        this.initHot();
      });
    },

    //初始化handsontable组件
    initHot() {
      let id = this.id
      console.log(id)
      var container = document.getElementById(this.id);
      let winHeight = document.documentElement.clientHeight;
      this.hot = new Handsontable(container, {
        data: this.main,
        colHeaders: this.delHeader(this.headers), //表头文案
        columns: this.getType(this.headers), //数据显示格式
        filters: true,
        maxRows: this.main.length,
        height: winHeight - 100 - 50 - 80,
        columnSorting: true, //添加排序
        sortIndicator: true, //添加排序
        renderAllRows: true,
        autoColumnSize: true,
        language: "zh-CN",
        manualColumnResize: true,
        manualColumnMove: true,
        dropdownMenu: [
          "filter_by_condition",
          "filter_by_value",
          "filter_action_bar"
        ],
        contextMenu: {
          items: {
            remove_row: {
              name: "删除该业务空间"
            }
          }
        },
        // 事件
        afterChange: this.tdChange, //修改后
        afterFilter: this.trimmedRows, //排序前
        beforeRemoveRow: this.romoveFm, //右键删除
        afterOnCellMouseDown: this.eventClick //鼠标点击
      });
      let pro = document.getElementById("hot-display-license-info");
      if (!!pro) {
        pro.parentNode.removeChild(pro);
      }
      this.isLoading = false;
    },

    //表格中的查看详情
    eventClick(el, rowArr) {
      let filter = this.filtersArr;
      //被筛选过后的数组
      let trimmedArr = this.trimmedRows();
      //是否启用了排序
      let isSort = this.hot.getPlugin("columnSorting").isSorted();
      // debugger
      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) {
      if (row.col == 1) {
        this.$emit("lookEqu", infos);
      } else {
        return false;
      }
    },

    //表格发生更改
    tdChange(changeData, source) {
      let filter = this.filtersArr;
      if (changeData) {
        let param = this.getParam(changeData, source);
        let data = [];
        for (let i = 0; i < param.length; i++) {
          if (!!param[i].id) {
            data.push(param[i]);
          } else {
            this.createSq(param[i], changeData);
          }
        }
        if (data && data.length) {
          this.updateBusiness(data, changeData);
        }
      }
    },

    //右键删除
    romoveFm(index, amout, physicalRows, source) {
      if (physicalRows && physicalRows.length) {
        let items = [],
          text = null;
        physicalRows.map(item => {
          text = text
            ? this.copyMain[item].infos.RoomName + "、" + text
            : this.copyMain[item].infos.RoomName;
          items.push(this.copyMain[item].id);
        });
        this.$confirm("您正在删除" + text + ", 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.delBusiness(items);
          })
          .catch(() => {
            this.hot.loadData(tools.deepCopy(this.copyMain));
          });
      }
    },

    delBusiness(items) {
      let param = {
        ProjId: this.param.ProjId,
        secret: this.param.secret,
        data: {
          criteria: {
            ids: items
          }
        }
      };
      delManySpace(param)
        .then(res => {
          if (res.data.Result == "success") {
            this.$message.success("删除成功");
            this.getData();
          } else {
            this.$message.error("删除失败");
          }
        })
        .catch(() => {
          this.$message.error("请求发生错误");
        });
    },

    // 新建
    createSq(param, change) {
      let seedData = {
        building_id: this.buildMess.buildCode,
        floor_id: this.buildMess.code,
        business_type: this.activeType.code == "GeneralZone" ? null : this.activeType.code,
        infos: {}
      };
      for (let i = 0; i < change.length; i++) {
        let arr = change[i][1].split(".");
        seedData[arr[0]][arr[1]] = [{ value: change[i][3] != "" ? change[i][3] : null }];
      }
      this.createSpace(seedData);
    },

    // 修改
    updateBusiness(data, change) {
      let param = {
        ProjId: this.param.ProjId,
        secret: this.param.secret,
        data: {
          criterias: []
        }
      };
      data.map((item, index) => {
        console.log(change[index][1]);
        let arr = change[index][1].split(".");
        let info = {};
        info[arr[1]] = [{ value: change[index][3] != "" ? change[index][3] : null }];
        param.data.criterias.push({
          id: item.id,
          infos: info
        });
      });
      updateBusiness(param).then(res => {
        console.log(res);
      });
    },

    /**    请求部分 ------------------------------------ */
    createSpace(data) {
      let param = {
        ProjId: this.param.ProjId,
        secret: this.param.secret,
        data: { criterias: [data] }
      };
      createBusinessList(param).then(res => {
        if (res.data.Result == "success") {
          console.log(this.main);
          this.main.map(item => {
            if (!item.id) {
              item.id = res.data.id;
              item.infos.RoomID = res.data.id;
              item.infos.RoomName = res.data.RoomName;
            }
          });
          this.hot.loadData(this.main);
          this.reset()
        } else {
          this.$message.error("创建发生错误：" + res.data.ResultMsg);
        }
      });
    },

    /**
     * 获取被排序后的数组
     *
     * @param changeData 发生改变的数据
     * @param source     数组
     *
     * @return array     经过排序后或者经过搜索后的数组
     */
    getParam(changeData, source) {
      let param = "";
      //被筛选过后的数组
      let trimmedArr = this.trimmedRows();
      //是否启用了排序
      let isSort = this.hot.getPlugin("columnSorting").isSorted();
      if (trimmedArr.length && isSort) {
        //排序后的数组
        let sortArr = this.hot.getPlugin("columnSorting").rowsMapper.__arrayMap;
        param = changeData.map(item => {
          return this.hot.getSourceDataAtRow(trimmedArr[sortArr[item[0]]]);
        });
      } else if (isSort) {
        //排序后的数组
        let sortArr = this.hot.getPlugin("columnSorting").rowsMapper.__arrayMap;
        param = changeData.map(item => {
          return this.hot.getSourceDataAtRow(sortArr[item[0]]);
        });
      } else if (trimmedArr.length) {
        param = changeData.map(item => {
          return this.hot.getSourceDataAtRow(trimmedArr[item[0]]);
        });
      } else {
        param = changeData.map(item => {
          return this.hot.getSourceDataAtRow(item[0]);
        });
      }
      return param;
    },

    //获取被筛选掉的行号
    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;
    },

    /**
     * 表头文案处理函数
     * @param list header数组数据
     *
     * @return 处理好的文案
     */
    delHeader(list) {
      let arr = tools.copyArr(list)
      // 如果不是只读状态，添加四大厂商选择
      let readArr = ["A1", "A2", "B1", "C5", "D1", "D2", "X", "L", "L1", "L2", "M"]
      if (!this.onlyRead) {
        arr = showTools.arrToArr(arr)
        readArr.push("Own")
      }
      let data = showTools.changeHeader(arr, readArr, false, false, true, true, true)
      data.unshift("是否关联平面图", "与空间相关联的设备");
      console.log("header", data)
      return data;
    },

    /**
     * 表头数据处理函数
     * @param arr header数组数据
     *
     * @return 处理好的数据格式
     */
    getType(list) {
      let arr = tools.copyArr(list)
      let data = showTools.showTypes(arr, false, false, true, true, ["F1", "F2"])
      data.unshift(
        {
          data: "hasSi",
          renderer: this.myRenderer,
          readOnly: true
        },
        {
          data: "point",
          renderer: this.facilityRender,
          readOnly: true
        }
      );
      data = data.filter(item => item);
      console.log(data)
      return data;
    },

    myRenderer(instance, td, row, col, prop, value, cellProperties) {
      if (value) {
        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;
    },

    //下拉插件修改
    customDropdownRenderer(
      instance,
      td,
      row,
      col,
      prop,
      value,
      cellProperties
    ) {
      var selectedId;
      var optionsList = cellProperties.chosenOptions.data;
      if (
        typeof optionsList === "undefined" ||
        typeof optionsList.length === "undefined" ||
        !optionsList.length
      ) {
        Handsontable.renderers.TextRenderer(
          instance,
          td,
          row,
          col,
          prop,
          value,
          cellProperties
        );
        return td;
      }
      var values = (value + "").split(",");
      value = [];
      for (var index = 0; index < optionsList.length; index++) {
        if (optionsList[index].content && optionsList[index].content.length) {
          for (let i = 0; i < optionsList[index].content.length; i++) {
            if (
              optionsList[index].content[i] &&
              optionsList[index].content[i].length
            ) {
              for (let j = 0; j < optionsList[index].content[i].length; j++) {
                if (
                  values.indexOf(
                    optionsList[index].content[i].content[j].code + ""
                  ) > -1
                ) {
                  selectedId = optionsList[index].content[i].content[j].code;
                  value.push(optionsList[index].content[i].content[j].name);
                }
              }
            } else {
              if (
                values.indexOf(optionsList[index].content[i].code + "") > -1
              ) {
                selectedId = optionsList[index].content[i].code;
                value.push(optionsList[index].content[i].name);
              }
            }
          }
        } else {
          if (values.indexOf(optionsList[index].code + "") > -1) {
            selectedId = optionsList[index].code;
            value.push(optionsList[index].name);
          }
        }
      }
      value = value.join(", ");
      Handsontable.renderers.TextRenderer(
        instance,
        td,
        row,
        col,
        prop,
        value,
        cellProperties
      );
      return td;
    },

    /**  页面中的按钮事件--------------------------- */
    addSp() {
      //   this.dialog.addDevice = true
      //   this.hot.downloadFile()
      //   this.hot.getPlugin('exportFile').downloadFile("csv", { columnHeaders: true, exportHiddenRows: true, exportHiddenColumns: true, rowHeaders: true })
      if (this.main && this.main.length && !!this.main[0].id) {
        this.hot.destroy();
        this.hot = null;
        this.main.unshift([]);
        this.getMain(this.main);
      } else {
        if (this.main && this.main.length) {
          this.$message.error("请添加完成后继续添加");
        } else {
          this.main.unshift([]);
          this.getMain(this.main);
        }
      }
    },

    //刷新
    reset() {
      this.getData();
    },

    //撤回操作
    undo() {
      this.hot.undo();
    },

    /**  分页事件------------------------ */
    pageChange() {
      this.getMain(
        this.pagination(this.page.currentPage, this.page.size, this.allData)
      );
    },

    pagination(pageNo, pageSize, array) {
      let offset = (pageNo - 1) * pageSize;
      return offset + pageSize >= array.length
        ? array.slice(offset, array.length)
        : array.slice(offset, offset + pageSize);
    }
  }
};
</script>
<style lang="less" scoped>
#handsontable {
  .no-data {
    height: 150px;
    line-height: 150px;
    text-align: center;
    color: gray;
  }
}
</style>