<template>
  <div id="deviceList">
    <!-- <div class="search-header">
      <floor-cascader @change="changeFloor"></floor-cascader>
    </div> -->
    <el-row class="right">
      <span style="float:left;">当前筛选条件下共{{page.total || '--'}}租户</span>
      <el-select v-model="onlyRead" @change="getTableHeader" style="width:100px;margin-right:10px;vertical-align:bottom;">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <div v-show="onlyRead" style="width:200px;display:inline-block;text-align:left;color:gray;">
        <span>只看要采集的信息</span>
        <el-checkbox v-model="allMess" @change="getTableHeader"></el-checkbox>
      </div>
      <el-button @click="handleCreateTableData">添加租户</el-button>
      <el-button @click="getTableHeader">刷新</el-button>
      <el-button v-show="!onlyRead" @click="undo">撤销</el-button>
    </el-row>
    <div class="tableBox">
      <div class="center middle_sty" style="flex:2;" v-show="tableData && !tableData.length">
        <p>
          <i class="iconwushuju iconfont"></i>
          暂无数据
        </p>
      </div>
      <div class="tableLeft" v-show="tableData && tableData.length">
        <handson-table ref="table"></handson-table>
      </div>
      <div class="tableRight">
        <div v-show="isTableRightShow">
          <div class="table_right_box"><span class="iconfont close_right" @click="handleCloseRight">&#xe66b;</span></div>
          <h5>管理租赁空间</h5>
          <p style="margin-bottom: 10px;">以下为关联的业务空间id</p>
          <el-input
            type="textarea"
            :autosize="{ minRows: 6, maxRows: 10}"
            :disabled="onlyRead"
            placeholder="请输入业务空间id，以“,”分割"
            v-model="roomId">
          </el-input>
          <el-row class="right" v-show="!onlyRead">
            <el-button @click="handleCloseRight">取消</el-button>
            <el-button type="primary" @click="saveSpaceList">保存</el-button>
          </el-row>
        </div>
      </div>
    </div>
    <el-pagination
      class="right"
      v-show="tableData && tableData.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>
</template>
<script>
import tools from "@/utils/scan/tools"
import handsonUtils from "@/utils/hasontableUtils"
import showTools from "@/utils/handsontable/notShow"
import text from "@/utils/handsontable/mainText"

import floorCascader from "@/components/ledger/lib/floorCascader"
import handsonTable from "@/components/common/handsontable"
import { getRentTableHeader, getRentTableData, updataRentTableData, deleteRentTableData, saveRentRelateSpace } from "@/api/scan/request"
import { mapGetters, mapActions } from "vuex";
export default {
  components: {
    floorCascader,
    handsonTable
  },
  data() {
    return {
      buildId: null,//建筑id
      floorId: null,//楼层id
      tenantID: "",//要操作的租户id
      isTableRightShow: false,
      roomId: "",//关联的空间id
      options: [{
        value: true,
        label: '只读模式'
      }, {
        value: false,
        label: '编辑模式'
      }],
      onlyRead: true,
      allMess: true,
      tableHeader: [],
      page: {
        pageSize: 50,
        pageSizes: [10, 20, 50, 100],
        pageNumber: 1,
        total: 0
      },
      tableData: [],
      copyTableData: []
    };
  },
  computed: {
    ...mapGetters("layout", [
        "projectId",
        "secret",
        "userId"
    ])
  },
  created() {
    this.getTableHeader()
  },
  watch: {
      projectId() {
        this.getTableHeader()
      }
  },
  methods: {
    // 获取表头数据(初始化表格)
    async getTableHeader() {
      let param = {
        ProjId: this.projectId,
        secret: this.secret,
        data: {
          "CollectFlag": this.allMess
        }
      }
      await getRentTableHeader(param, res => {
        this.tableHeader = res.Content;
        this.getTableData()
      })
    },
    async getTableData() {//获取表格数据
      let data = {
        Filters: `ProjectId='${this.projectId}'`,
        PageNumber: this.page.pageNumber,
        PageSize: this.page.pageSize
      }
      const params = {
        ProjId: this.projectId,
        secret: this.secret,
        data: data
      }
      await getRentTableData(params, (res) => {
        this.tableData = res.Content
        this.copyTableData = tools.deepCopy(res.Content)
        this.page.pageNumber = res.PageNumber
        this.page.total = res.Total
        if(this.tableData && this.tableData.length){
          this.initTable()
        }
      })
    },
    // 修改表格内容
    async updateTableData(data, change) {
      let param = {
        ProjId: this.projectId,
        secret: this.secret,
        data: {
          Content: [],
          Projection: []
        }
      };
      //生成要修改字段列表
      change.map((item) => {
        if(item[1] && param.data.Projection.indexOf(item[1]) == -1) {
          param.data.Projection.push(item[1])
        }
      })
      //生成对应修改数据
      data.map((item, index) => {
        let keyarr = change[index][1].split(".")
        if (keyarr && keyarr.length > 1) {
          item[keyarr[0]][keyarr[1]] = item[keyarr[0]][keyarr[1]] != ""? item[keyarr[0]][keyarr[1]]: null
        } else {
          item[keyarr[0]] = item[keyarr[0]] != ""? item[keyarr[0]]: null
        }
        param.data.Content.push(item);
      });

      await updataRentTableData(param, (res) => {
        
      })
    },
    //保存元空间关联
    async saveSpaceList() {
      let data = {
        TenantID: this.tenantID,
        RoomID: this.roomId
      }
      const params = {
        ProjId: this.projectId,
        secret: this.secret,
        data: data
      }
      await saveRentRelateSpace(params, (res) => {
        this.$message.success("关联成功!")
        this.getTableHeader()
      })
    },
    // 删除表格数据
    async deleteTableData(params) {
      await deleteRentTableData(params, (res) => {
        this.$message.success("删除成功")
        this.getTableHeader()
      })
    },
    // 添加租户数据
    handleCreateTableData() {
      this.$router.push({ name: 'rentadd' })
    },
    // 删除表格行
    handleDeleteTableRow() {
      let params = tools.differenceArr(this.tableData, this.copyTableData)
      if (params.length < 1) {
        return
      }
      let param = {
        ProjId: this.projectId,
        secret: this.secret,
        data: []
      }
      params.map(item => {
        param.data.push(item.TenantID)
      })
      this.$confirm("此操作将删除租户，是否继续？", "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteTableData(param)
      }).catch(() => {
        this.getTableHeader()
        this.$message("取消删除")
      })
    },
    //修改
    handleUpdataTable(changeData, source) {
      if (!this.onlyRead) {
        if (changeData) {
          let trimmedArr = this.trimmedRows();
          let param = handsonUtils.getParam(changeData, source, this.tableExample, trimmedArr);
          let data = [];
          for (let i = 0; i < param.length; i++) {
            data.push(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.updateTableData(data, changeData);
          }
        }
      }
    },
    //撤回
    undo() {
      this.tableExample.undo();
    },
    //切换租户类型
    changeFloor(value) {
      if (value[0]) {
        this.buildId = value[0]
      }
      if (value[1]) {
        this.floorId = value[1]
      } else {
        this.floorId = null
      }
      this.getTableHeader()
    },
    //关闭右侧关联元空间输入按钮
    handleCloseRight() {
      this.isTableRightShow = false
    },
    //切换每页显示多少条数据
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getTableHeader()
    },
    //切换页数
    handleCurrentChange(val) {
      this.page.pageNumber = val
      this.getTableHeader()
    },
    formatHeaderData(list) {//格式化表头显示的数据
      let arr = tools.copyArr(list)
      arr.map((item) => {
        item.Visible = true
      })
      let readArr = ["A1", "A2", "B1", "C5", "D1", "D2", "E1", "F1", "F2", "L", "L1", "L2", "X"]
      if (!this.onlyRead) {
        readArr.push("Own")
      }
      let data = showTools.changeHeader(arr, readArr, this.onlyRead, false, this.allMess)
      data.unshift("操作","所属楼层","租赁空间");
      return data;
    },
    formatHeaderType(list) {//格式化表头头映射的数据
      let arr = tools.copyArr(list);
      arr.map((item) => { //缺少信息点
        item.Visible = true
      })
      let readArr = ["A1", "A2", "B1", "C5", "D1", "D2", "E1", "F1", "F2", "L", "L1", "L2", "X"]
      let data = showTools.showHeaderTypes(arr, readArr, this.onlyRead, false, this.allMess)
      data.unshift({
        data: "caozuo",
        renderer: tools.lookDetails,
        readOnly: true
      }, {
        data: "FloorId",
        readOnly: true
      }, {
        data: "RoomCount",
        renderer: tools.num,
        readOnly: true
      })
      return data;
    },
    initTable() {//实例化表格
      let settings = {
        data: this.tableData,
        colHeaders: this.formatHeaderData(this.tableHeader),
        columns: this.formatHeaderType(this.tableHeader),
        rowHeights: 30,
        maxRows: this.tableData.length,
        contextMenu: {
          items: {
            remove_row: {
              name: "删除租户"
            }
          }
        },
        // 事件
        afterChange: this.handleUpdataTable, //修改后
        afterFilter: this.trimmedRows, //排序前
        afterRemoveRow: this.handleDeleteTableRow, //右键删除
        afterOnCellMouseDown: this.handleTdClick //鼠标点击
      };
      this.$nextTick(() => {
        console.log(this.$refs.table);
        this.tableExample = this.$refs.table.init(settings);
      });
    },
    //获取到了正确的信息
    getInfors(infos, row) {
      //其他的开始判断
      let val = this.tableExample.colToProp(row.col);
      this.row = row.row //要操作的列号
      this.messKey = val //要操作的列类型
      this.tenantID = infos.TenantID //要操作的数据id
      //点击操作跳转详情
      if (val === "caozuo") {

        window.open(`${process.env.BASE_URL}:8889/#/details?perjectId=${this.projectId}&secret=${this.secret}&FmId=${this.tenantID}&type=0&code=VOTn`,"_blank")
      }
      //点击关联的元空间
      if (val === "RoomCount") {
        if(infos && infos.RoomID) {
          this.roomId = infos.RoomID
        } else {
          this.roomId = ""
        }
        this.isTableRightShow = true;
      }
    },
    //表格点击事件
    handleTdClick(el, rowArr) {
      //点击的是表头
      if (rowArr.row < 0) {
        return;
      }
      //被筛选过后的数组
      let trimmedArr = this.trimmedRows();
      //是否启用了排序
      let isSort = this.tableExample.getPlugin("columnSorting").isSorted();
      if (trimmedArr.length && isSort) {
        let sortArr = this.myHotArr.getPlugin("columnSorting").rowsMapper
          .__arrayMap;
        let infos = this.tableData[trimmedArr[sortArr[rowArr.row]]];
        this.getInfors(infos, { row: sortArr[rowArr.row], col: rowArr.col });
      } else if (isSort) {
        //排序后的数组
        let sortArr = this.tableExample.getPlugin("columnSorting").rowsMapper.__arrayMap;
        let infos = this.tableData[sortArr[rowArr.row]];
        this.getInfors(infos, { row: sortArr[rowArr.row], col: rowArr.col });
      } else if (trimmedArr.length) {
        let infos = this.tableData[trimmedArr[rowArr.row]];
        this.getInfors(infos, { row: trimmedArr[rowArr.row], col: rowArr.col });
      } else {
        let infos = this.tableData[rowArr.row];
        this.getInfors(infos, rowArr);
      }
    },
    //获取被筛选掉的行号
    trimmedRows() {
      // var plugin = hot.getPlugin('trimRows').trimmedRows;//获取被筛选掉的行号
      var plugin = this.tableExample.getPlugin("trimRows").trimmedRows;
      let dataLength = this.tableData.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);
      }
      return dataArr || [];
      // var DataArray = new Array();

      // for (var i = 0; i < plugin.length; i++) {
      //     // 通过行号获取数据
      //     DataArray.push(this.tableExample.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;
    }
  }
};
</script>
<style lang="less" scoped>
#deviceList {
  overflow: hidden;
  height: 100%;
  background-color: #fff;
  padding: 10px;
  position: relative;
  .right {
    background: #fff;
  }
  .search-header {
    overflow: hidden;
    padding:0 10px 10px 10px;
    border-bottom: 1px solid #bcbcbc;
  }
  .tableBox {
    display: flex;
    height: calc(100% - 95px);
    margin-top: 10px;
    .tableLeft {
      flex: 2;
      margin-right: 20px;
    }
    .tableRight {
      flex: 1;
      // display: none;
      border-left: 1px solid #dadada;
      padding: 5px 15px;
      margin-right: 5px;
      box-shadow: 0px 1px 5px 0px rgba(59, 66, 84, 0.15);
      .table_right_box::after{
        display: block;
        content: "";
        clear: both;
      }
      .close_right {
        float: right;
        cursor: pointer;
      }
    }
  }
}
.el-pagination button, .el-pagination span:not([class*=suffix]) {
    vertical-align: middle;
}
</style>