<template>
  <div id="deviceList">
    <el-row class="right">
      <span style="float: left">当前选择的设备类型:{{ category.name }}</span>
      <el-select
        v-model="showType"
        @change="initTable"
        style="width: 140px; 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>
      <span>增加</span>
      <el-input-number
        v-model="addNum"
        :controls="false"
        style="width: 50px"
        :min="1"
        :max="50"
      ></el-input-number>
      <span>个{{ category.name }}</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="icon-wushuju 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"
        :disabled="createDisable"
        >创建设备</el-button
      >
    </el-row>
    <!-- 多选枚举类型维护 -->
    <menum
      :dialog="myDialog"
      :updateInfoData="updateInfoData"
      :updateInput="updateInput"
      @change="handleChangeMenum"
    ></menum>
    <!-- 二维码弹窗 -->
    <qrcode
      :dialog="myDialog"
      :qrcodeUrl="qrcodeUrl"
      :addBody="true"
      ref="qrcode"
    ></qrcode>
    <upload-files-dialog
      :read="onlyRead ? true : false"
      ref="upload"
      @changeFile="fileChange"
      :keysArr="filesArr"
      :dialog="myDialog"
    >
    </upload-files-dialog>
    <upload-img-dialog
      :read="onlyRead ? true : false"
      @changeFile="imgChange"
      :keysArr="imgsArr"
      :dialog="myDialog"
    ></upload-img-dialog>
    <pic-dialog
      :read="onlyRead ? true : false"
      :dialog="myDialog"
      :keysArr="picsArr"
      @change="changePics"
    ></pic-dialog>
    <system-type
      :device="category"
      :dialog="myDialog"
      :type="onlyRead ? 'read' : 'edit'"
      @change="changeSystemType"
      :list="systemList"
    ></system-type>
    <details-dialog
      :iframeSrc="iframeSrc"
      v-if="myDialog.details"
      :dialog="myDialog"
    ></details-dialog>
  </div>
</template>
<script>
import tools from "@/utils/old-adm/scan/tools";
import showTools from "@/utils/old-adm/handsontable/notShow";
import text from "@/utils/old-adm/handsontable/mainText";
import storage from "@/utils/storageUtil";
import BuildController from "@/controller/old-adm/buildController";
import handsonTable from "@/components/old-adm/common/handsontable";
import ScanController from "@/controller/old-adm/ScanController";
import Dic from "@/controller/old-adm/dicController";

import { mapGetters } from "vuex";

import qrcode from "@/components/old-adm/ledger/components/lib/qrcode";
import uploadFilesDialog from "@/components/old-adm/dialogs/list/filesDialog";
import uploadImgDialog from "@/components/old-adm/dialogs/list/uploadImgDialog";
import picDialog from "@/components/old-adm/dialogs/list/picDialog";
import menum from "@/components/old-adm/dialogs/list/menum";
import systemType from "@/components/old-adm/dialogs/list/systemType";

export default {
  components: {
    qrcode, //二维码页面
    uploadFilesDialog,
    uploadImgDialog,
    picDialog,
    systemType,
    handsonTable,
    menum,
  },
  data() {
    return {
      addNum: 1,
      onlyRead: false,
      showTypes: [
        { value: "Visible", label: "只看需交付的" },
        { value: "all", label: "全部" },
      ],
      tableHeader: [],
      // tableData: session.get("deviceAddData")
      //     ? session.get("deviceAddData").length
      //         ? session.get("deviceAddData")
      //         : [{ checked: 1 }]
      //     : [{ checked: 1 }],
      tableData: storage.get("deviceAddData")
        ? storage.get("deviceAddData").length
          ? storage.get("deviceAddData")
          : []
        : [],
      copyTableData: [],
      category: "", //当前设备类
      myDialog: {
        qrcode: false, //二维码弹窗
        uploadFiles: false, //上传文件
        uploadImgs: false, //上传单个图片
        pic: false, //多个图片
        addDevice: false,
        systemType: false,
        details: false, //详情页
        changeRea: false,
        lookPic: false, //图片查看
        menum: false, //临时多选枚举类型信息点
      },
      inputMap: {
        flowBuild: {
          editable: true,
          code: "flowBuild",
          name: "建筑楼层",
          path: "flowBuild",
          category: "STATIC",
          dataType: "ENUM",
        },
      }, //信息点和输入方式映射表
      qrcodeUrl: "", //二维码图片地址
      filesArr: [], //保存临时的文件key
      imgsArr: [], //临时保存的图片key数组
      picsArr: [], //临时设备图片keys数组
      systemList: [], //关联的系统
      systemId: null,
      graphyId: null,
      id: 0,
      showType: this.$route.query.showType,
      EquipmentList: [],
      firmId: "", //品牌型号所需字段--族id三位编码(传设备类id或部件类id)
      buildFloorData: [],
      floorFlag: true,
      createDisable: false,
      updateInfoData: {}, //当前信息点信息
      updateInfoPoint: "", //临时维护信息点键
      updateInput: "", //临时维护信息点值
    };
  },
  computed: {
    ...mapGetters("layout", ["projectId", "secret", "userId"]),
  },
  created() {
    this.category = this.$route.query;
    BuildController.getData(this.buildFloorData);
    this.getBelongs();
    this.getTableHeader();
  },
  methods: {
    //查询设备类对应的 族
    getBelongs() {
      let params = {
        data: {
          filters: `equipCode='${this.category.deviceId}'`,
          pageNumber: 1,
          pageSize: 50,
        },
      };
      ScanController.getEquipBelongs(params).then((res) => {
        if (res.content.length) {
          this.firmId = res.content[0].family;
        }
      });
    },
    //将数组转换成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 = {
        orders: "sort asc, name desc",
        pageNumber: 1,
        pageSize: 1000,
        type: this.category.deviceId,
      };
      await Dic.getDataDictionary(params, (res) => {
        this.tableHeader = res.content;
        this.tableHeader.forEach((item) => {
          if (item.path) {
            this.inputMap[item.path] = item;
          }
        });
        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 (
          (item.checked && newK.length > 1) ||
          (!item.checked && newK.length)
        ) {
          return item;
        }
      });
      if (!newData.length) {
        this.$message("创建信息为空,请录入信息后再创建!");
        return;
      }
      let flag = false;
      newData.map((item) => {
        if (!item.localName) {
          flag = true;
        }
        // 处理建筑-楼层
        if (item.flowBuild) {
          let bid = item.flowBuild.split("-");
          item.buildingId = item.flowBuild.split("-")[0];
          if (bid[1]) {
            item.floorId = item.flowBuild.split("-")[1];
          }
        }
        //处理关联的系统
        if (item.linkSystem && item.linkSystem.length) {
          item.SystemList = [];
          item.linkSystem.map((t) => {
            item.SystemList.push(t.id);
          });
        }
        // 关联创建资产
        // item.propertyId = !!item.checked;
        item.classCode = this.category.deviceId;
      });
      if (flag) {
        this.$message.info("存在设备的本地名称为空，请检查");
        return;
      }

      // for (let i = 0; i < newData.length; i++) {
      //   let params = newData[i]
      //   params.Family = this.firmId;
      //   params.Category = this.category.deviceId;
      //   if (newData[i].PropertyId) {//同时创建资产
      //     await createPropertyData([params], async res => {
      //       params.PropertyId = res.EntityList[0].EquipID
      //       await createEquip([params], res => {
      //         if (i == newData.length - 1) {
      //           this.$router.push({
      //             path: "/ledger/facility",
      //             query: { deviceId: this.category.deviceId }
      //           });
      //           session.remove("deviceAddData")
      //         }
      //       })
      //     })
      //   } else {
      //     await createEquip([params], res => {
      //       if (i == newData.length - 1) {
      //         this.$router.push({
      //           path: "/ledger/facility",
      //           query: { deviceId: this.category.deviceId }
      //         });
      //         session.remove("deviceAddData")
      //       }
      //     });
      //   }
      // }
      this.createDisable = true;
      //待接口修改为关联创建即可修改
      let param = {
        cascade: [],
        content: newData,
      };
      ScanController.createEquipAndProperty(param).then((res) => {
        this.createDisable = false;
        this.$message.success("创建成功");
        storage.remove("deviceAddData");
        this.$router.push({
          name: "facilityLedger",
          params: {
            deviceId: this.category.deviceId,
            facility: this.category.name,
          },
        });
      });
    },
    // 删除表格行
    handleDeleteTableRow(a, b, c, d) {
      if (d && d === "ContextMenu.removeRow") {
        this.$message.success("删除成功");
        this.formaTableData();
      }
    },
    // 添加行
    handleAddTableRow() {
      let addRowLength = this.addNum;
      for (let i = 0; i < addRowLength; i++) {
        // this.tableData.push({ checked: 1 });
        this.tableData.push({});
      }
      this.initTable();
      this.formaTableData();
    },
    //修改
    handleUpdataTable(changeData, source) {
      if (!this.onlyRead && source != "ObserveChanges.change") {
        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;
        }
      });
      storage.set("deviceAddData", newData);
    },
    //格式化表头显示的数据
    formatHeaderData(list) {
      let arr = tools.copyArr(list);
      let data = showTools.headerTextFilter(
        arr,
        "equipment",
        this.onlyRead,
        this.showType,
        true
      );
      // data.unshift("同时创建资产", "所属系统实例");
      data.unshift("所属系统实例");
      if (this.floorFlag) {
        data.splice(1, 0, "所属建筑楼层");
      }
      return data;
    },
    formatHeaderType(list) {
      //格式化表头头映射的数据
      let arr = tools.copyArr(list);
      let data = showTools.headerTypeFilter(
        arr,
        "equipment",
        this.onlyRead,
        this.showType,
        true
      );
      data.unshift(
        // {
        //     type: "checkbox",
        //     checkedTemplate: 1,
        //     uncheckedTemplate: 0,
        //     data: "checked",
        //     label: {
        //         position: "after",
        //     },
        // },
        {
          data: "linkSystem",
          renderer: text.systemList,
          readOnly: true,
        }
      );
      if (this.floorFlag) {
        data.splice(1, 0, {
          data: "flowBuild",
          renderer: tools.customDropdownRenderer,
          editor: "chosen",
          chosenOptions: {
            // multiple: true,//多选
            data: this.buildFloorData,
          },
        });
      }
      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(() => {
        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;
    },
    //上传文件弹窗触发事件
    fileChange(keys) {
      this.setDataToMain(keys, this.messKey, this.row);
    },
    //上传图片弹窗触发事件
    imgChange(keys) {
      this.setDataToMain(keys, this.messKey, this.row);
    },
    //设备图片弹窗改变事件
    changePics(keys) {
      this.setDataToMain(keys, this.messKey, this.row);
    },
    //关联系统变更
    changeSystemType(data) {
      tools.setDataForKey(this.tableData[this.row], "linkSystem", data);
    },
    //表格点击事件
    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);
      let inputData = this.inputMap[val];
      this.row = row.row;
      this.messKey = 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("开发中...");
          return false;
        case "defaultQRCode":
          this.qrcodeUrl = this.tableData[row.row][val];
          if (this.qrcodeUrl) {
            this.myDialog.qrcode = true;
          } else {
            this.$message("此设备没有设备二维码");
          }
          return false;
        // 同时创建资产
        case "checked":
          return false;
        //关联系统
        case "linkSystem":
          if (!this.onlyRead) {
            this.systemList = this.tableData[row.row].linkSystem || [];
            this.myDialog.systemType = true;
          }
          return false;
        //关联资产
        case "linkEquipLocalName":
          if (this.linkNameFalg) {
            this.myDialog.changeRea = true;
          }
          return false;
        /**
         * 关联资产后才可维护的信息点
         */
        // case 'flowBuild': //所属建筑楼层
        // case 'infos.productDate': //生产日期
        // case 'infos.serialNum': //出厂编号
        // case 'infos.assetID': //资产编号
        // case 'infos.purchasePrice': //采购价格
        // case 'infos.insuranceNum': //保险单号
        // case 'infos.insuranceFile': //保险文件
        //     if (!this.onlyRead) {
        //         const linkId = this.tableData[row.row].linkId;
        //         if (!linkId) { //未关联资产
        //             this.$confirm('您暂未关联设备对应的资产，该信息点不可编辑', '提示', {
        //                 confirmButtonText: '我知道了',
        //                 showCancelButton: false,
        //                 type: 'warning',
        //                 center: true
        //             }).then(() => {
        //                 return false;
        //             });
        //         }
        //     }
        //     break
        //保险文件--设备文档--安装质检报告
        case "infos.insuranceFile": //保险文件
        case "infos.archive": //设备文档
        case "infos.checkReport": //安装质检报告
        case "infos.maintainManual": //维修保养手册
        case "infos.approachingAcceptance": //进场验收单
        case "infos.acceptanceReport": //验收报告
        case "infos.operationManual": //操作说明书
        case "infos.originalCertificate": //原厂证明
        case "infos.testReport": //检测报告
        case "infos.productCertification": //产品合格证
        case "infos.installInstruction": //安装说明书
        case "infos.supplierContract": //供应合同
        case "infos.drawing": //设备图纸
        case "infos.installDrawing": //安装图纸
        case "infos.designIDGraph": //设计工况空调机组处理过程焓湿图(F2)
        case "infos.fanCharacterCurve": //风机性能曲线(F1)
          let IPSdata = tools.dataForKey(this.tableData[row.row], val);
          this.filesArr = IPSdata ? IPSdata : [];
          this.myDialog.uploadFiles = true;
          return false;
        //安装照片--设备铭牌照片
        case "infos.installPic":
        case "infos.nameplate":
          let SSPPdata = tools.dataForKey(this.tableData[row.row], val);
          this.imgsArr = SSPPdata ? SSPPdata : [];
          this.myDialog.uploadImgs = true;
          return false;
        //设备照片
        case "infos.pic":
          let Pdata = tools.dataForKey(this.tableData[row.row], val);
          this.picsArr = Pdata ? Pdata : [];
          this.myDialog.pic = true;
          return false;
        //包含的部件字段
        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 },
            });
          }
          return false;
        default:
          break;
      }
      // 维护多选枚举值
      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.region || inputData.multiple)) {
        this.$confirm("该信息点为区间值/复数值，暂无组件支持输入！", "提示", {
          confirmButtonText: "我知道了",
          showCancelButton: false,
          type: "warning",
          center: true,
        }).then(() => {
          return false;
        });
      }
      if (!this.onlyRead && !inputData.editable) {
        this.$confirm("该信息点的值为自动生成，不可人工维护！", "提示", {
          confirmButtonText: "我知道了",
          showCancelButton: false,
          type: "warning",
          center: true,
        }).then(() => {
          return false;
        });
      }
    },
    utilToKey(key, name, data, messName) {
      if (key == name) {
        this.setDataToMain(data[key], messName, this.row);
      }
    },
    //多选枚举类型值修改
    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 = "";
    },
    //判断是否有值，有值赋值
    setDataToMain(data, key, row) {
      if (!!data && data != "--") {
        if (!!this.tableData[row]) {
          //铭牌照片特殊处理
          tools.setDataForKey(this.tableData[row], key, data);
          // this.tableData[row][key] = data;
        } else {
          this.tableData[row] = {};
          tools.setDataForKey(this.tableData[row], key, data);
        }
      } else {
        tools.setDataForKey(this.tableData[row], key, "");
      }
    },
  },
};
</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>
