<template>
  <div id="deviceList">
    <div class="search-header">
      <cenote-type @change="changeFloor"></cenote-type>
    </div>
    <el-row class="left">
      <span style="float:right;">当前筛选条件下共{{ page.total || '--' }}竖井</span>
      <el-select v-model="onlyRead" @change="getTableHeader"
                 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="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>
      <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="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>
    <!-- 所属建筑 -->
    <building-dialog :shaftId="shaftId" :dialog="myDialog" :onlyRead="onlyRead"
                 @change="changeBuildingList"
                 :buildingList="buildingList"></building-dialog>
    <!-- 多选枚举类型维护 -->
   <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>
  </div>
</template>
<script>
import tools from "@/utils/scan/tools";
import text from "@/utils/handsontable/mainText";
import handsonUtils from "@/utils/hasontableUtils"
import showTools from "@/utils/handsontable/notShow"
import cenoteType from "@/components/ledger/lib/cenoteType";
import buildingDialog from "@/components/ledger/lib/buildingDialog";
import handsonTable from "@/components/common/handsontable";
import {getDataDictionary} from "@/api/dict";
import menum from "@/components/dialogs/list/menum";
import {
  BeatchQueryParam,
  deleteCenoteTableData,
  queryCenoteTableData,
  saveCenoteRelateSpace,
  updataCenoteTableData
} from "@/api/scan/request"
import {mapGetters} from "vuex";

export default {
  components: {
    cenoteType,
    handsonTable,
    buildingDialog,
    menum
  },
  data() {
    return {
      cenoteId: "",//竖井类型id
      shaftId: "",//要操作的竖井id
      spaceList: "",
      options: [{
        value: true,
        label: '只读模式'
      }, {
        value: false,
        label: '编辑模式'
      }],
      onlyRead: true,
      showType: "",
      // allMess: true,
      tableHeader: [],
      page: {
        pageSize: 50,
        pageSizes: [10, 20, 50, 100],
        pageNumber: 1,
        total: 0
      },
      tableData: [],
      copyTableData: [],
      buildData: [],
      tableExample: null,
      myDialog: {
        update: false,//临时维护信息点
        building: false,//所属建筑
        menum: false, //临时多选枚举类型信息点
      },
      inputMap: {}, //信息点和输入方式映射表
      buildingList: [], //当前选中竖井所属建筑
      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.getTableHeader()
  },
  mounted() {
    this.onlyRead = !this.$route.params.onlyRead;
  },
  watch: {
    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: 'shaft'
      }
      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: 'spaceList' }, { name: 'buildingList' }],
        orders: "createTime desc, localName desc, localId desc, id asc",
        pageNumber: this.page.pageNumber,
        pageSize: this.page.pageSize
      }
      if (this.cenoteId) {
        params.filters = `infos.shaftFuncType='${this.cenoteId}'`
      }
      await queryCenoteTableData(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 updataCenoteTableData(param, (res) => {

      })
    },
    // 删除表格数据
    async deleteTableData(params) {
      await deleteCenoteTableData(params, (res) => {
        this.$message.success("删除成功!")
        this.getTableHeader()
      })
    },
    //保存元空间关联
    async saveSpaceList() {
      let params = {
        ShaftId: this.shaftId,
        SpaceId: this.spaceList
      }
      await saveCenoteRelateSpace(params, (res) => {
        this.$message.success("关联成功!")
        this.getTableHeader()
      })
    },
    // 添加竖井
    handleCreateTableData() {
      this.$router.push({
        path: '/ledger/cenoteadd',
        query: {
          showType: this.showType
        }
      })
    },
    // 删除表格行
    handleDeleteTableRow() {
      let params = tools.differenceArr(this.tableData, this.copyTableData)
      if (params.length < 1 || this.tableData > this.copyTableData) {
        return
      }
      let param = []
      params.map(item => {
        param.push({ id: item.id })
      })
      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()
    },
    //切换每页显示多少条数据
    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, "shaft", this.onlyRead, this.showType)
      data.unshift("关联的业务空间", "其他关系");
      if (this.showType == 'all') {
        data.splice(4, 0, '所属建筑');
      }
      return data;
    },
    formatHeaderType(list) {//格式化表头头映射的数据
      let arr = tools.copyArr(list);
      let data = showTools.headerTypeFilter(arr, "shaft", this.onlyRead, this.showType)
      data.unshift({
        data: "spaceList",
        renderer: (instance, td, row, col, prop, value, cellProperties) => {
          td.style.color = "#409EFF";
          td.style.cursor = "pointer";
          td.innerHTML = `<span>${value ? value.length : 0}</span>`
          return td;
        },
        readOnly: true
      }, {
        data: "otheRelations",
        renderer: (instance, td, row, col, prop, value, cellProperties) => {
          td.style.color = "#409EFF";
          td.style.cursor = "pointer";
          td.innerHTML = "查看";
          return td;
        },
        readOnly: true
      })
      if (this.showType == 'all') {
        data.splice(4, 0, {
            data: 'buildingList',
            renderer: text.buildingList,
            readOnly: this.onlyRead
        })
      }
      return data;
    },
    initTable() {//实例化表格
      let settings = {
        data: this.tableData,
        fixedColumnsLeft: 4,
        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]
      let name = infos.localName ? infos.localName : infos.name
      this.row = row.row;
      this.shaftId = infos.id //要操作的数据id
      //点击关联的业务空间
      if (val === "spaceList") {
        this.$router.push({
          path: '/ledger/relatedSpace',
          query: { ShaftId: this.shaftId, name: name, onlyRead: this.onlyRead }
        })
        return false
      } else if (val === "otheRelations") {
        this.$router.push({
          path: "/ledger/cenoteDetail",
          query: {
            ShaftID: this.shaftId,
            name: name
          }
        })
        return false
      } else if (val === "buildingList") { //所属建筑
        this.buildingList = infos[val]? infos[val]: [];
        this.myDialog.building = true;
        return false
      }
      if (!this.onlyRead && !inputData.editable) {
        this.$confirm('该信息点的值为自动生成，不可人工维护！', '提示', {
            confirmButtonText: '我知道了',
            showCancelButton: false,
            type: 'warning',
            center: true
        }).then(() => {
            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 && showTools.inputModeArr.indexOf(inputData.dataType) == '-1') {
        this.updateInfoPoint = val;
        this.updateInput = tools.dataForKey(this.tableData[row.row], val);
        this.myDialog.update = true;
        return false;
      }
    },
    //多选枚举类型值修改
    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 = "";
    },
    //所属建筑
    changeBuildingList(data) {
        console.log(this.tableData[this.row]);
        console.log("buildingList");
        console.log(data);
      tools.setDataForKey(this.tableData[this.row], "buildingList", data);
    },
    //关闭临时维护弹窗回调
    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);
        });
      }
    }
  }
};
</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-bottom: 10px;
    border-bottom: 1px solid #bcbcbc;
  }

  .tableBox {
    display: flex;
    height: calc(100% - 140px);
    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>
