<template>
  <div id="deviceList">
    <!-- <div class="search-header">
      <floor-cascader @change="changeFloor"></floor-cascader>
    </div> -->
    <el-row class="left">
      <span style="float:right;">当前筛选条件下共{{ 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>
      <el-select v-model="showType" @change="initTable" 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>
      <!-- <div v-show="onlyRead" style="width:200px;display:inline-block;text-align:left;color:gray;font-size:12px;">
        <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 @click="mangeTenantZone">管理租赁空间</el-button>
      <el-button v-show="!onlyRead" @click="undo">撤销</el-button>
    </el-row>
    <div class="tableBox">
      <div class="center middle_sty" style="flex:1;" v-show="tableData && !tableData.length">
        <p>
          <i class="icon-wushuju iconfont"></i>
          暂无数据
        </p>
      </div>
      <div class="tableLeft" v-show="tableData && tableData.length">
        <handson-table ref="table"></handson-table>
      </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>
    <!-- 多选枚举类型维护 -->
   <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>
    <!-- 右侧关联的业务空间抽屉 -->
    <roomCountDrawer ref="roomCountDrawer" :readonly="onlyRead" @refresh="getTableData"></roomCountDrawer>
  </div>
</template>
<script>
import tools from "@/utils/scan/tools"
import handsonUtils from "@/utils/hasontableUtils"
import showTools from "@/utils/handsontable/notShow"
import roomCountDrawer from "@/components/ledger/rentList/roomCountDrawer"
import floorCascader from "@/components/ledger/lib/floorCascader"
import handsonTable from "@/components/common/handsontable"
import {getDataDictionary} from "@/api/dict";
import menum from "@/components/dialogs/list/menum";
import {
  BeatchQueryParam,
  deleteRentTableData,
  queryRentTableData,
  saveRentRelateSpace,
  updataRentTableData
} from "@/api/scan/request"
import {mapGetters} from "vuex";

export default {
  components: {
    floorCascader,
    handsonTable,
    roomCountDrawer,
    menum
  },
  data() {
    return {
      buildId: null,//建筑id
      floorId: null,//楼层id
      tenantID: "",//要操作的租户id
      isTableRightShow: false,
      roomId: "",//关联的空间id
      options: [{
        value: true,
        label: '只读模式'
      }, {
        value: false,
        label: '编辑模式'
      }],
      onlyRead: true,
      showType: "Visible",
      // allMess: true,
      tableHeader: [],
      page: {
        pageSize: 50,
        pageSizes: [10, 20, 50, 100],
        pageNumber: 1,
        total: 0
      },
      tableData: [],
      copyTableData: [],
      myDialog: {
        update: false,//临时维护信息点
        menum: false, //临时多选枚举类型信息点
      },
      inputMap: {
        FloorId: {
          editable: true,
          code: "FloorId",
          name: "所属楼层",
          path: "FloorId",
          category: 'STATIC',
          dataType: "STRING"
        }
      }, //信息点和输入方式映射表
      updateInputShow: false, //是否显示临时维护输入框
      updateInfoData: {}, //当前信息点信息
      updateInfoPoint: '',//临时维护信息点
      updateInput: '', //临时维护信息点值
    };
  },
  computed: {
    ...mapGetters("layout", ["projectId", "secret", "userId", "group_code"]),
    showTypes() {
      return this.onlyRead ?
        [{value: "Visible", label: '只看采集信息'}, {value: "all", label: '全部'}] :
        [{value: "Visible", label: '只看采集信息'}, {value: "all", label: '全部'}]
    }
  },
  created() {
    this.onlyRead = this.$route.query.onlyRead === 'true' || this.$route.query.onlyRead === true || !this.$route.query.onlyRead;
    this.getTableHeader()
  },
  watch: {
    projectId() {
      this.getTableHeader()
    },
    showTypes: {
      handler(newName, oldName) {
        if (newName && newName[0] && newName[0].value) {
          this.showType = newName[0].value
        } else {
          this.showType = "Visible"
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 获取表头数据(初始化表格)
    async getTableHeader() {
      let param = {
        orders: "sort asc, name desc",
        pageNumber: 1,
        pageSize: 1000,
        type: 'tenant'
      }
      await getDataDictionary(param, res => {
        this.tableHeader = res.content;
        this.codeToDataSource = {}
        this.tableHeader.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.getTableData()
      })
    },
    async getTableData() {//获取表格数据
      let params = {
        cascade: [
          { name: 'zoneTenantList', cascade: [{ name: 'building' }, { name: 'floor' }] },
          { name: 'zoneGeneraltList', cascade: [{ name: 'building' }, { name: 'floor' }] }
        ],
        orders: "createTime desc, localName desc, localId desc, id asc",
        pageNumber: this.page.pageNumber,
        pageSize: this.page.pageSize
      }
      await queryRentTableData(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) {
          if (this.onlyRead) {
            this.getBatch(res.content)
          }
          this.initTable()
        }
      })
    },
    // 修改表格内容
    async updateTableData(data, change) {
      let param = {
        content: []
      }, keyList = [];
      //生成要修改字段列表
      change.map(item => {
        if (item[1] && keyList.indexOf(item[1]) == -1) {
          keyList.push(item[1]);
        }
      });
      //生成对应修改数据
      data.map((item, index) => {
        let nullList = [];
        keyList.map(value => {
          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.content.push(updateItem);
        } else {// 无置空内容
            param.content.push(item);
        }
      });
      await updataRentTableData(param, (res) => {

      })
    },
    //保存元空间关联
    async saveSpaceList() {
      let params = {
        Tenant: this.tenantID,
        RoomID: this.roomId
      }
      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({
        path: '/ledger/rentadd',
        query: {
          showType: this.showType
        }
      })
    },
    // 删除表格行
    handleDeleteTableRow() {
      let params = tools.differenceArr(this.tableData, this.copyTableData)
      if (params.length < 1) {
        return
      }
      let param = []
      params.map(item => {
        param.push({ TenantID: 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)
      let data = showTools.headerTextFilter(arr, "tenant", this.onlyRead, this.showType)
      data.unshift("操作", "所属楼层", "租赁空间");
      return data;
    },
    formatHeaderType(list) {//格式化表头头映射的数据
      let arr = tools.copyArr(list);
      let data = showTools.headerTypeFilter(arr, "tenant", this.onlyRead, this.showType)
      data.unshift({
        data: "caozuo",
        renderer: tools.lookDetails,
        readOnly: true
      }, {
        data: "FloorId",
        readOnly: true
      }, {
        data: "RoomCount",
        renderer: (instance, td, row, col, prop, value, cellProperties) => {
          td.style.color = "#409EFF";
          td.style.cursor = "pointer";
          let num = 0;
          let a = instance.getDataAtRowProp(row, 'ZoneGeneraltList')
          let b = instance.getDataAtRowProp(row, 'ZoneTenantList')
          if (a && a.length) {
            num += a.length
          }
          if (b && b.length) {
            num += b.length
          }
          td.innerHTML = num;
          return td;
        },
        readOnly: true
      })
      return data;
    },
    initTable() {//实例化表格
      let settings = {
        data: this.tableData,
        colHeaders: this.formatHeaderData(this.tableHeader),
        columns: this.formatHeaderType(this.tableHeader),
        rowHeights: 30,
        fillHandle: 'vertical', //允许纵向填充
        maxRows: this.tableData.length,
        contextMenu: this.onlyRead ? false : {
          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)
      let inputData = this.inputMap[val]
      this.row = row.row //要操作的列号
      this.messKey = val //要操作的列类型
      this.tenantID = infos.TenantID //要操作的数据id
      //点击操作跳转详情
      if (val === "caozuo") {
        this.$message("开发中！")
        // window.open(`${process.env.BASE_URL}:8889/#/details?perjectId=${this.projectId}&secret=${this.secret}&FmId=${this.tenantID}&type=0&code=VOTn`,"_blank")
        return false
      }
      //点击关联的元空间
      if (val === "RoomCount") {
        // if (infos && infos.RoomID) {
        //   this.roomId = infos.RoomID
        // } else {
        //   this.roomId = ""
        // }
        // this.isTableRightShow = true;
        this.$refs.roomCountDrawer.showDrawer(infos)
        return false
      }
      // 维护多选枚举值
      if (!this.onlyRead && inputData.dataType == "MENUM") {
        this.updateInfoData = inputData;
        this.updateInfoPoint = val;
        this.updateInput = tools.dataForKey(this.tableData[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.tableData[row.row], val)
        this.myDialog.update = true
      }
    },
    //多选枚举类型值修改
    handleChangeMenum(newValue) {
        tools.setDataForKey(
        this.tableData[this.row],
        this.updateInfoPoint,
        newValue
      );
      this.handleUpdataTable(
        [[this.row, this.updateInfoPoint, null, newValue]],
        "edit"
      );
      this.myDialog.menum = false;
      this.updateInput = "";
    },
    //关闭临时维护弹窗回调
    handleCloseUpdate() {
      this.updateInputShow = false
      this.updateInfoPoint = ''
      this.updateInput = ''
    },
    //更新临时维护信息点
    handleClickUpdate() {
      tools.setDataForKey(this.tableData[this.row], this.updateInfoPoint, this.updateInput)
      this.handleUpdataTable([[this.row, this.updateInfoPoint, null, this.updateInput]], "edit")
      this.updateInputShow = false
      this.myDialog.update = false
      this.updateInput = ''
    },
    //表格点击事件
    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;
    },
    //获取动态参数
    getBatch(data) {
      let param = { //获取动态参数
        groupCode: this.group_code,
        appId: "datacenter",
        projectId: this.projectId,
        data: []
      }
      this.tableHeader.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) {
        BeatchQueryParam(param, res => {
          this.tableData = data.map(item => {
            res.data.map(child => {
              if (item.id == child.objectId) {
                if (child.data || child.data == 0) {
                  this.tableHeader.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.tableHeader.map(head => {
                    if (head.code == child.infoCode) {
                      tools.setDataForKey(
                        item,
                        head.path,
                        child.error ? child.value ? "表号功能号格式错误" : "表号功能号不存在" : "暂未采集到实时数据"
                      );
                    }
                  });
                }
              }
            });
            return item;
          });
          this.tableExample.loadData(this.tableData);
        });
      }
    },
    // 跳转至管理租赁空间
    mangeTenantZone() {
      this.$router.push({ name: 'manageTenantZone', query: { onlyRead: this.onlyRead } })
    }
  }
};
</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>
