<template>
  <div id="deviceList">
    <el-row>
      <el-tabs @tab-click="handleClick" v-model="tabVal">
        <el-tab-pane label="用户管理" name="first"></el-tab-pane>
        <el-tab-pane label="配置管理" name="second"></el-tab-pane>
        <el-tab-pane label="角色管理" name="third"></el-tab-pane>
        <el-tab-pane label="定时任务补偿" name="fourth"></el-tab-pane>
      </el-tabs>
    </el-row>
    <el-row class="right">
      <div 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" 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>
    <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 cenoteType from "@/components/ledger/lib/cenoteType";
import handsonTable from "@/components/common/handsontable";
import { getCenoteTableHeader, getCenoteTableData, updataCenoteTableData, deleteCenoteTableData, saveCenoteRelateSpace } from "@/api/scan/request"
import { mapGetters, mapActions } from "vuex";
export default {
  components: {
    cenoteType,
    handsonTable
  },
  data() {
    return {
      cenoteId: "",//部件类型id
      shaftId: "",//要操作的部件id
      isTableRightShow: false,
      spaceList: "",
      onlyRead: false,
      allMess: true,
      tableHeader: [],
      page: {
        pageSize: 50,
        pageSizes: [10, 20, 50, 100],
        pageNumber: 1,
        total: 0
      },
      tableData: [],
      copyTableData: [],
      tableExample:null,
      tabVal:'first'
    };
  },
  computed: {
    ...mapGetters("layout", [
        "projectId",
        "secret",
        "userId"
    ])
  },
  created() {
    this.getTableHeader()
  },
  methods: {
    //tab页点击事件
    handleClick(){
      console.log(this.tabVal)
    },
    // 获取表头数据(初始化表格)
    async getTableHeader() {
      let param = {
        ProjId: this.projectId,
        secret: this.secret,
        data: {
          "CollectFlag": this.allMess
        }
      }
      await getCenoteTableHeader(param, res => {
        this.tableHeader = res.Content;
        this.getTableData()
      })
    },
    async getTableData() {//获取表格数据
      let data = {
        Filters: this.cenoteId? `ProjectId='${this.projectId}';structureInfo.ShaftFuncType='${this.cenoteId}'`: `ProjectId='${this.projectId}'`,
        PageNumber: this.page.pageNumber,
        PageSize: this.page.pageSize
      }
      const params = {
        ProjId: this.projectId,
        secret: this.secret,
        data: data
      }
      await getCenoteTableData(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 updataCenoteTableData(param, (res) => {
        
      })
    },
    // 删除表格数据
    async deleteTableData(params) {
      await deleteCenoteTableData(params, (res) => {
        this.$message.success("删除成功!")
        this.getTableHeader()
      })
    },
    //保存元空间关联
    async saveSpaceList() {
      let data = {
        ShaftId: this.shaftId,
        SpaceId: this.spaceList
      }
      const params = {
        ProjId: this.projectId,
        secret: this.secret,
        data: data
      }
      await saveCenoteRelateSpace(params, (res) => {
        this.$message.success("关联成功!")
        this.getTableHeader()
      })
    },
    // 添加部件
    handleCreateTableData() {
      this.$router.push({ name: 'addparts'})
    },
    // 删除表格行
    handleDeleteTableRow() {
      let params = tools.differenceArr(this.tableData, this.copyTableData)
      if (params.length < 1 || this.tableData > this.copyTableData) {
        return
      }
      let param = {
        ProjId: this.projectId,
        secret: this.secret,
        data: []
      }
      params.map(item => {
        param.data.push(item.ShaftID)
      })
      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) {
      this.cenoteId = value.Id
      this.getTableHeader()
    },
    //关闭右侧关联元空间输入按钮
    handleCloseRight() {
      this.isTableRightShow = false
      this.spaceList = ""
    },
    //切换每页显示多少条数据
    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: "SpaceCount",
        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, //修改后
        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.shaftId = infos.ShaftID //要操作的数据id
      //点击关联的元空间
      if (val === "SpaceCount") {
        this.spaceList = infos.SpaceList
        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 || [];
    },
    //去除数组中相同的元素
    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% - 150px);
    margin-top: 10px;
    .tableLeft {
      flex: 1;
    }
  }
}
.el-pagination button, .el-pagination span:not([class*=suffix]) {
    vertical-align: middle;
}
</style>