<template>
  <div id="handsontable" v-loading="isLoading">
    <el-row class="left">
<!--      <div style="display: inline-block">-->
<!--        &lt;!&ndash;      <div v-show="!onlyRead && zoneCode === 'other'">&ndash;&gt;-->
<!--        <el-button @click="addZoneBtn">添加分区</el-button>-->
<!--        <el-select v-model="zoneValue" placeholder="请选择">-->
<!--          <el-option-->
<!--            v-for="item in addZone"-->
<!--            :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="initHot" style="width:100px;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-button v-show="!onlyRead" @click="addSp">添加</el-button>
      <el-button @click="reset">刷新</el-button>
      <el-button v-show="!onlyRead" @click="undo">撤销</el-button>
      <el-input v-model="zoneItemID" placeholder="请输入业务空间id" @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-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"/>
  </div>
</template>
<script>
  // 引用handsontable插件
  import "@/assets/js/chosen.jquery.min";
  import tools from "@/utils/scan/tools";
  import "@/assets/js/handsontable-chosen-editor";
  import lStorage from '@/utils/localStorage'
  import myPagination from "@/components/common/myPagination";
  import addBusiness from "@/components/business_space/dialogs/addDialog/businessDialog"
  import showTools from "@/utils/handsontable/notShow"
  import handsonUtils from "@/utils/hasontableUtils"
  import Handsontable from "handsontable-pro"
  import buildFloor from '@/utils/handsontable/buildFloorData'
  import 'handsontable-pro/dist/handsontable.full.css'
  import zhCN from 'handsontable-pro/languages/zh-CN';
  import uploadImgDialog from "@/components/business_space/dialogs/list/uploadImgDialog"
  import qrcode from "@/components/ledger/lib/qrcode";
  import {
    queryZone,
    updateZone,
    deleteZone,
    createZone,
    BeatchQueryParam,
    updateRelateInSpAndBuild
  } from "@/api/scan/request";
  import {mapGetters, mapActions} from "vuex";
  import dialogZone from "../../ledger/addDialog/dialogZone";

  export default {
    props: {
      id: {},
      zoneCode: {}
    },
    components: {
      qrcode, //二维码页面
      myPagination,
      addBusiness,
      uploadImgDialog,
      dialogZone
    },
    computed: {
      ...mapGetters("layout", ["projectId", "secret", "userId"]),
      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: "",
        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: [], //楼层数据
        zoneItemID: '',
        myDialog: {
          uploadImgs: false, //上传图片弹窗
        },
        imgsArr: [], //空间图片
        addZone: [{
          value: '选项1',
          label: '黄金糕'
        }, {
          value: '选项2',
          label: '双皮奶'
        }, {
          value: '选项3',
          label: '蚵仔煎'
        }, {
          value: '选项4',
          label: '龙须面'
        }, {
          value: '选项5',
          label: '北京烤鸭'
        }],
        zoneValue: '',
      };
    },
    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(headers, buildFloorSelectd) {
        this.headers = headers
        this.buildFloorSelectd = buildFloorSelectd
        this.page.pageNumber = 1
        this.getData()
      },
      getData() {
        this.isLoading = true
        let params = {
          zone: this.zoneCode,
          data: {
            Filters: ``,
            Orders: "createTime desc, RoomID asc",
            PageNumber: this.page.pageNumber,
            PageSize: this.page.pageSize
          }
        }
        if (this.buildFloorSelectd[0] == "noKnow") {
          params.data.Filters += `buildingId isNull`
        } else if (this.buildFloorSelectd[0] && this.buildFloorSelectd[0] != "all") {
          params.data.Filters += `buildingId='${this.buildFloorSelectd[0]}'`
        }
        if (this.buildFloorSelectd.length > 1) {
          if (this.buildFloorSelectd[1] == "noKnow") {
            params.data.Filters += `;floorId isNull`
          } else if (this.buildFloorSelectd[1] && this.buildFloorSelectd[1] != "all") {
            params.data.Filters += `;floorId='${this.buildFloorSelectd[1]}'`
          }
        }
        if (this.zoneItemID) {
          params.data.Filters += `;RoomID='${this.zoneItemID}'`
        }
        if (!params.data.Filters) {
          delete params.data.Filters
        }
        // if (this.buildFloorSelectd.length && this.buildFloorSelectd[0] && this.buildFloorSelectd[1]) {
        //   params.data.Filters = `BuildingId='${this.buildFloorSelectd[0]}';FloorId='${this.buildFloorSelectd[1]}'`
        // }
        // else if (buildFloorSelectd.length && buildFloorSelectd[0] && !buildFloorSelectd[1]) {
        //   params.data.Filters = `BuildingId='${buildFloorSelectd[0]}'`
        // } else {
        //   params.data.Filters = `BuildingId='';FloorId=''`
        // }
        queryZone(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
            }
            return item
          });
          if (this.main && this.main.length && this.main[0].RoomID) {
            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();
        });
      },
      //初始化handsontable组件
      initHot() {
        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,
          fixedColumnsLeft: 4,
          maxRows: this.main.length,
          height: winHeight - 100 - 50 - 176,
          columnSorting: true, //添加排序
          sortIndicator: true, //添加排序
          renderAllRows: true,
          autoColumnSize: true,
          observeChanges: false,
          language: "zh-CN",
          manualColumnResize: true,
          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();
        // 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) {
        let val = this.hot.colToProp(row.col);
        this.row = row.row;
        lStorage.set('screen_data', {path: this.$route.path, data: {RoomID: infos.RoomID, zone: this.zoneCode}})
        if (val == "point") {
          let query = {
            RoomID: infos.RoomID,
            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;
          }
        } else {
          return false;
        }
      },
      //表格发生更改
      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].RoomID) {
                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 = {
          data: [],
          zone: this.zoneCode
        }
        params.map(item => {
          if (item.RoomID)
            param.data.push({RoomID: item.RoomID})
        })
        this.$confirm("此操作将删除业务空间，是否继续？", "提示", {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteZone(param, res => {
            this.$message.success("删除成功!")
            this.getData()
          })
        }).catch(() => {
          this.getData()
          this.$message("取消删除")
        })
      },
      //创建业务空间
      handleCreateZone(param) {
        let keys = Object.keys(param)
        keys.map((key) => { //将值为空字符串的属性删除
          if (param[key] == "") {
            delete param[key]
          }
        })
        if (!param.RoomLocalName) {
          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]
            }
          }
        }
        let params = {
          zone: this.zoneCode,
          data: {
            Content: [param]
          }
        }
        createZone(params, res => {
          this.$message.success("添加成功!")
          this.getData()
        })
      },
      // 修改
      updateBusiness(data, change) {
        let param = {
          data: {
            Content: [],
            Projection: []
          },
          zone: this.zoneCode
        };
        let keyList = [];
        //生成要修改字段列表
        change.map((item) => {
          let key = item[1].split(".")[0]
          if (key == "flowBuild" && keyList.indexOf(key) == -1) {
            keyList.push("BuildingId", "FloorId")
            param.data.Projection.push("BuildingId", "FloorId")
          }
          if (item[1] && keyList.indexOf(key) == -1) {
            keyList.push(key)
          }
          if (item[1] && item[3] == "" && param.data.Projection.indexOf(key) == -1) {
            param.data.Projection.push(key)
          }
        })
        //生成对应修改数据
        data.map((item, index) => {
          keyList.map(value => {
            if (value == "BuildingId") {
              let itemData = tools.dataForKey(item, "flowBuild")
              if (itemData == "") {
                tools.setDataForKey(item, "BuildingId", null)
                tools.setDataForKey(item, "FloorId", null)
              } 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)
                }
              }
            } else {
              let itemData = tools.dataForKey(item, value)
              tools.setDataForKey(item, value, itemData == "" ? null : itemData)
            }
          })
          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.RoomID,
              id: t.FloorId || t.BuildingId || null,
            }
          })
          updateRelateInSpAndBuild(pa, res => {
            this.$message.success('修改成功')
          })
        } else {
          updateZone(param, (res) => {
          })
        }
      },
      //获取被筛选掉的行号
      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 = {
          secret: this.secret,
          ProjId: this.projectId,
          data: {
            criterias: []
          }
        };
        this.headers.map(head => {
          if (
            head.InputMode == "L" ||
            head.InputMode == "L1" ||
            head.InputMode == "L2" ||
            head.InputMode == "M"
          ) {
            data.map(item => {
              let cur = tools.dataForKey(item, head.Path);
              if (cur) {
                param.data.criterias.push({
                  id: item.RoomID,
                  code: head.InfoPointCode
                });
              }
            });
          }
        });
        if (param.data.criterias.length) {
          BeatchQueryParam(param, res => {
            if (!this.onlyRead) {
              return false
            }
            this.main = data.map(item => {
              res.Content.map(child => {
                if (item.RoomID == child.id) {
                  if (child.data || child.data == 0) {
                    this.headers.map(head => {
                      if (head.InfoPointCode == child.code) {
                        tools.setDataForKey(item, head.Path, child.data);
                      }
                    });
                  } else {
                    this.headers.map(head => {
                      if (head.InfoPointCode == child.code) {
                        tools.setDataForKey(
                          item,
                          head.Path,
                          // child.error ? "表号功能号格式错误" : "表号功能号不存在"
                          child.error ? child.value ? "表号功能号格式错误" : "表号功能号不存在" : "暂未采集到实时数据"
                        );
                      }
                    });
                  }
                }
              });
              return item;
            });
            this.hot.loadData(this.main);
          });
        }
      },
      /**
       * 表头文案处理函数
       * @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)
        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() {
        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()
          }
        }
      },
      //刷新
      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
      }
    },
    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 = ""
          }
        },
        immediate: true,
        deep: true
      }
    }
  };
</script>
<style lang="less" scoped>
  #handsontable {
    .left {
      padding-top: 0;
      padding-bottom: 10px;
    }

    .no-data {
      height: 150px;
      line-height: 150px;
      text-align: center;
      color: gray;
    }
  }
</style>
