<template>
  <div id="deviceList">
    <el-row class="right"> 
      <span style="width:20px;float:left;display:block;height:20px;cursor: pointer;" @click="changeAssetsFalg">
        <i class="el-icon-fa  el-icon-fa-compass"></i>
      </span>
      <span style="float:left;">当前选择的系统类型:{{category.CategoryName}}</span>
      <div style="width:200px;display:inline-block;text-align:left;color:gray;">
        <span>隐藏自动填充的信息</span>
        <el-checkbox v-model="showTypeFlag" @change="getTableHeader"></el-checkbox>
      </div>
      <span>增加</span>
      <el-input v-model="addNum" style="width:40px;" size="small"></el-input>
      <span>个{{category.CategoryName}}</span>
      <el-button @click="handleAddTableRow">增加</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>
    <el-row class="center">
      <el-button type="primary" size="medium" @click="handleCreateTableData" class="create_button">创建系统</el-button>
    </el-row>
  </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 session from "@/framework/utils/storage";

import handsonTable from "@/components/common/handsontable";
import {
  getDataDictionary,
  createGeneralSys,
  getSpaceFloor
} from "@/api/scan/request";
import { mapGetters, mapActions } from "vuex";

import qrcode from "@/components/ledger/lib/qrcode";
export default {
  components: {
    handsonTable
  },
  data() {
    return {
      addNum: 1,
      onlyRead: false,
      tableHeader: [],
      tableData: session.get("systemAddData")
        ? session.get("systemAddData").length
          ? session.get("systemAddData")
          : [{}]
        : [{}],
      copyTableData: [],
      category: "", //当前设备类
      myDialog: {
        qrcode: false, //二维码弹窗
        firm: false, //厂商弹窗
        supply: false, //选择供应合同
        supplier: false, //供应商选择
        guarantee: false, //选择保单
        maintainer: false, //选择维修商
        insurer: false, //选择保险公司
        uploadFiles: false, //上传文件
        uploadImgs: false, //上传单个图片
        pic: false, //多个图片
        addDevice: false,
        systemType: false,
        details: false, //详情页
        changeRea: false,
        lookPic: false //图片查看
      },
      qrcodeUrl: "", //二维码图片地址
      filesArr: [], //保存临时的文件key
      imgsArr: [], //临时保存的图片key数组
      picsArr: [], //临时设备图片keys数组
      systemId: null,
      graphyId: null,
      id: 0,
      showTypeFlag: true,
      EquipmentList: [],
    };
  },
  computed: {
    ...mapGetters("layout", ["projectId", "secret", "userId"])
  },
  created() {
    this.category = this.$route.query;
    this.getFloorData();
    this.getTableHeader();
  },
  methods: {
    //维护建筑
    changeAssetsFalg() {
      if (this.floorFlag) {
        this.floorFlag = false
      } else {
        this.$confirm('<p>维护设备所在建筑楼层后，对后续数据影响较大，如业务空间中的所在关系or其他?暂未梳理明白……</p><p>后续要修改设备所属建筑楼层，只能通过模型中的待建模清单操作</p>', '提示', {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '就要维护设备所属建筑楼层',
          cancelButtonText: '暂时不搞了',
          confirmButtonClass: 'confirmButtonClass',
          cancelButtonClass: 'cancelButtonClass'
        }).then(_ => {
          this.floorFlag = true
          this.getTableHeader()
        }).catch(_ => {
          this.$message("取消")
        })
      }
    },
    //获取楼层数据
    getFloorData() {
      let param = {
        ProjId: this.projectId,
        secret: this.secret
      }
      getSpaceFloor(param).then(res => {
        if (res.data.Result == 'success') {
          let data = this.changeArr(res.data.Content), floorData = []
          data.map(item => {
            floorData.push({
              Code: item.value,
              Name: item.label
            })
          })
          this.floorData = floorData
          this.floorData = floorData
        } else {
          this.$message.error(res.data.ResultMsg)
        }
      }).catch(() => {
        this.$message.error("请求出错")
      })
    },
    //将数组转换成optiosn格式
    changeArr(arr) {
      return arr.map(item => {
        if (item.floors && item.floors.length) {
          return {
            value: item.id,
            label: item.infos.BuildLocalName,
            children: item.floors.map(i => {
              return {
                value: i.id,
                label: i.infos.FloorLocalName || "未知",
              }
            })
          }
        } else {
          return {
            value: item.id,
            label: item.infos.BuildLocalName,
            children: null,
            isChilren: 1,
          }
        }
      })
    },
    // 获取表头数据(初始化表格)
    async getTableHeader() {
      let params = {
        data: {
          PageNumber: 1,
          PageSize: 500
        },
        type: this.category.Category
      };
      await getDataDictionary(params, res => {
        this.tableHeader = res.Content;
        this.initTable();
      });
    },
    // 创建设备数据
    async handleCreateTableData() {
      let newData = this.tableData.filter(item => {
        let keys = Object.keys(item);
        keys.map(key => {
          //将值为空字符串的属性删除
          if (item[key] == "") {
            delete item[key];
          }
        });
        let newK = Object.keys(item)
        if (newK.length) {
          return item;
        }
      });
      if (!newData.length) {
        this.$message("创建信息为空,请录入信息后再创建!");
        return;
      }
      let flag = false;
      newData.map(item => {
        if (!item.SysLocalName) {
          flag = true;
        }
        // 处理建筑
        if (item.flowBuild) {
          item.BuildingId = item.flowBuild
        }
        item.Category = this.category.Category
      })
      if (flag) {
        this.$message.info("存在系统的本地名称为空，请检查")
        return;
      }
      createGeneralSys(newData, res => {
        this.$message.success('创建成功')
        session.remove("systemAddData")
        this.$router.push({
          path: "/system/list",
          query: { deviceId: this.category.Category }
        });
      })
    },
    // 删除表格行
    handleDeleteTableRow() {
      this.$message.success("删除成功");
      this.formaTableData();
    },
    // 添加行
    handleAddTableRow() {
      let addRowLength = this.addNum;
      for (let i = 0; i < addRowLength; i++) {
        this.tableData.push({});
      }
      this.initTable();
      this.formaTableData();
    },
    //修改
    handleUpdataTable(changeData, source) {
      this.formaTableData();
    },
    //保存去掉空字段的新增数据
    formaTableData() {
      let newData = this.tableData.filter(item => {
        let keys = Object.keys(item);
        keys.map(key => {
          //将值为空字符串的属性删除
          if (item[key] == "") {
            delete item[key];
          }
        });
        if (keys.length && Object.keys(item).length) {
          return item;
        }
      });
      session.set("systemAddData", newData);
    },
    //格式化表头显示的数据
    formatHeaderData(list) {
      let arr = tools.copyArr(list);
      let showType = this.showTypeFlag ? 'partInfo' : 'all';
      let data = showTools.headerTextFilter(arr, 'system', this.onlyRead, showType);
      data.unshift("所属建筑");
      return data;
    },
    formatHeaderType(list) {
      //格式化表头头映射的数据
      let arr = tools.copyArr(list);
      let showType = this.showTypeFlag ? 'partInfo' : 'all';
      let data = showTools.headerTypeFilter(arr, 'system', this.onlyRead, showType);
      data.unshift({
        data: "flowBuild",
        renderer: tools.customDropdownRenderer,
        editor: "chosen",
        chosenOptions: {
          // multiple: true,//多选
          data: this.floorData
        }
      });
      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(() => {
        this.tableExample = this.$refs.table.init(settings);
      });
    },
    //去除数组中相同的元素
    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;
    },
    //表格点击事件
    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 = 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 || [];
    },
    getInfors(infos, row) {
      let val = this.tableExample.colToProp(row.col);
      console.log(val)
      switch (val) {
        //操作
        case 'caozuo':
          // window.open(`http://adm.sagacloud.cn:8058/spread?id=${infos.EquipID}&pid=${this.projectId}&secret=${this.secret}`,"_blank")
          this.$message("开发中...")
          break;
        //设备二维码图片
        case 'EquipQRCode':
          this.qrcodeUrl = this.tableData[row.row].EquipQRCode;
          if (!!this.qrcodeUrl) {
            this.myDialog.qrcode = true;
          } else {
            this.$message("此设备没有设备二维码");
          }
          break;
        //关联系统
        case 'linkSystem':
          if (!this.onlyRead) {
            this.systemList = this.tableData[row.row].LinkSystem || [];
            this.myDialog.systemType = true;
          }
          break;
        //关联资产
        case 'LinkEquipLocalName':
          if (this.linkNameFalg) {
            this.myDialog.changeRea = true;
          }
          break;
        //品牌型号弹窗
        case 'DPManufacturerID':
          if (!this.onlyRead) {
            this.myDialog.firm = true;
          }
          break;
        //供应商信息弹窗
        case 'DPSupplierID':
          if (!this.onlyRead) {
            this.myDialog.supplier = true;
          }
          break;
        //维修商信息弹窗
        case 'DPMaintainerID':
          if (!this.onlyRead) {
            this.myDialog.maintainer = true;
          }
          break;
        //保险公司信息
        case 'DPInsurerID':
          if (!this.onlyRead) {
            this.myDialog.insurer = true;
          }
          break;
        //供应合同编号
        case 'LedgerParam.SupplyPurchase.SupplierContractID':
          if (!this.onlyRead) {
            let ContractIDflag = null;
            let DPSdata = this.tableData[row.row].DPSupplierID;
            if (DPSdata) {
              ContractIDflag = DPSdata.split("-")[0];
            }
            if (!!ContractIDflag) {
              this.id = ContractIDflag;
              this.myDialog.supply = true;
            } else {
              this.$message("请先选择供应商");
            }
          }
          break;
        //保险单号
        case 'LedgerParam.InsuranceDoc.InsuranceNum':
          if (!this.onlyRead) {
            let DPInsurerIDflag = null;
            let DPIdata = this.tableData[row.row].DPInsurerID;
            if (DPIdata) {
              DPInsurerIDflag = DPIdata.split("-")[0];
            }
            if (!!DPInsurerIDflag) {
              this.id = DPInsurerIDflag;
              this.myDialog.guarantee = true;
            } else {
              this.$message("请先选择保险商");
            }
          }
          break;
        //保险文件--设备文档--安装质检报告
        case 'LedgerParam.InsuranceDoc.InsuranceFile':
        case 'LedgerParam.PhotoDoc.Archive':
        case 'LedgerParam.Siteinstall.CheckReport':
          let IPSdata = tools.dataForKey(this.tableData[row.row], val);
          this.filesArr = IPSdata ? IPSdata : [];
          this.myDialog.uploadFiles = true;
          break;
        //安装照片--安装图纸--设备铭牌照片--设备图纸
        case 'LedgerParam.Siteinstall.InstallPic':
        case 'LedgerParam.Siteinstall.InstallDrawing':
        case 'LedgerParam.PhotoDoc.Nameplate':
        case 'LedgerParam.PhotoDoc.Drawing':
          let SSPPdata = tools.dataForKey(this.tableData[row.row], val);
          this.imgsArr = SSPPdata ? SSPPdata : [];
          this.myDialog.uploadImgs = true;
          break;
        //设备照片
        case 'LedgerParam.PhotoDoc.Pic':
          let Pdata = tools.dataForKey(this.tableData[row.row], val);
          this.picsArr = Pdata ? Pdata : [];
          this.myDialog.pic = true;
          break;
        //包含的部件字段
        case 'Count':
          if (this.onlyRead) {
            this.$router.push({ path: '/ledger/parts', query: { deviceId: infos.EquipID } });
          } else {
            this.$router.push({ path: '/ledger/partsmanage', query: { deviceId: infos.EquipID, typeId: this.mess.deviceId } });
          }
          break;
        default:
          break;
      }
      this.row = row.row;
      this.messKey = val;
    },
  }
};
</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% - 100px);
    margin-top: 10px;
    .tableLeft {
      flex: 1;
    }
  }
  .create_button {
    margin-top: 10px;
  }
}
</style>