<!--
    上传文件的弹窗
-->

<template>
  <div v-if="dialog.addDevice">
    <el-dialog
      :title="title"
      :center="isCenter"
      :visible.sync="dialog.addDevice"
      :width="width"
      :fullscreen="isFull"
    >
      <div id="addDevice">
        <div v-show="!isCenter">
          <my-cascader ref="cascader" @change="changeCader"></my-cascader>
        </div>
        <div v-if="isCenter">
          <div>
            <div class="hanson-bar">
              <span>当前选择的设备族：{{deviceType.facility}}</span>
              <div style="width:350px;float:right;overflow:hidden;">
                <span>增加</span>
                <el-input v-model="addNum" style="width:40px;" placeholder="增加个数" size="small"></el-input>
                <span>个{{deviceType.facility}}</span>
                <el-button size="small" @click="addMain">增加</el-button>
              </div>
              <div
                style="width:200px;color:gray;float:right;padding-top:7px;font-size:10px;"
              >是否隐藏自动填充信息点:
                <el-tooltip :content="'' + (isWatch ? '隐藏' : '不隐藏')" placement="top">
                  <el-switch
                    @change="changeWatch"
                    v-model="isWatch"
                    active-color="#13ce66"
                    inactive-color="gray"
                  ></el-switch>
                </el-tooltip>
              </div>
            </div>
            <div v-show="main && main.length" id="myHandson" ref="myHandson"></div>
          </div>
        </div>
      </div>
      <div v-show="!isCenter" slot="footer" class="dialog-footer">
        <el-button>取 消</el-button>
        <el-button type="primary" @click="step(1)">下 一 步</el-button>
      </div>
      <span v-show="isCenter" slot="footer" class="dialog-footer">
        <el-button type="primary" @click="createAssets">创建资产</el-button>
      </span>
    </el-dialog>
    <qrcode :dialog="myDialog" :addBody="true" ref="qrcode"></qrcode>
    <firm
      :mess="{deviceId : deviceType.code}"
      ref="firm"
      @changeFirm="firmChange"
      :dialog="myDialog"
    ></firm>
    <supply-dialog @change="supplyChange" :id="id" ref="supply" :dialog="myDialog"></supply-dialog>
    <supplier-dialog ref="supplier" @changeSupplier="supplierChange" :dialog="myDialog"></supplier-dialog>
    <guarantee-dialog ref="guarantee" :id="id" @change="guaranteeChange" :dialog="myDialog"></guarantee-dialog>
    <upload-files-dialog
      ref="upload"
      @changeFile="fileChange"
      :keysArr="filesArr"
      :dialog="myDialog"
    ></upload-files-dialog>
    <upload-img-dialog @changeFile="imgChange" :keysArr="imgsArr" :dialog="myDialog"></upload-img-dialog>
    <maintainer-dialog @changeMaintainer="changeMaintainer" ref="maintainer" :dialog="myDialog"></maintainer-dialog>
    <insurer-dialog @changeInsurer="changeInsurer" ref="insurer" :dialog="myDialog"></insurer-dialog>
    <pic-dialog :dialog="myDialog" :keysArr="picsArr" @change="changePics"></pic-dialog>
  </div>
</template>
<script>

import myCascader from "@/components/lib/cascaders/assets";
import hansonTable from "@/components/dialogHanson/addDevice";
import tools from "@/assets/js/tools";
import qrcode from "@/components/lib/qrcode";
import firm from "@/components/dialogs/list/firm";
import supplyDialog from "@/components/dialogs/list/supplyDialog";
import supplierDialog from "@/components/dialogs/list/supplierDialog";
import maintainerDialog from "@/components/dialogs/list/maintainerDialog";
import insurerDialog from "@/components/dialogs/list/insurerDialog";
import guaranteeDialog from "@/components/dialogs/list/guaranteeDialog";
import uploadFilesDialog from "@/components/dialogs/list/filesDialog";
import uploadImgDialog from "@/components/dialogs/list/uploadImgDialog";
import picDialog from "@/components/dialogs/list/picDialog"

//下拉插件
import "@/assets/js/chosen.jquery.min";
import "@/assets/js/handsontable-chosen-editor";

import text from "@/utils/hansontable/mainText"

import showTools from "@/utils/hansontable/notShow"

import uuid from "@/utils/uuid";

import { getTableHeader, createProperty, getSpaceFloor, createAssetsList } from "@/api/request";
let table = function (num) {
  let main = []
  for (let i = 0; i < num; i++) {
    main.push({})
  }
  return main
}
export default {
  components: {
    myCascader,
    hansonTable,
    qrcode, //二维码页面
    firm, //
    supplyDialog,
    supplierDialog,
    guaranteeDialog,
    uploadFilesDialog,
    maintainerDialog,
    insurerDialog,
    uploadImgDialog,
    picDialog
  },
  props: {
    dialog: {
      type: Object,
      default: function () {
        return {
          addDevice: false
        };
      }
    },
    assetType: {
      type: Array,
      default: function () {
        return []
      }
    }
  },
  data() {
    return {
      width: "30%",
      isFull: false,//dialog是否为全屏
      title: "确定新增资产的类型",
      isCenter: false,
      deviceType: {},
      main: table(1),
      mess: {},
      headers: null,
      page: {
        size: 10,
        sizes: [10, 30, 50, 100, 150, 200],
        total: 400,
        currentPage: 1
      },
      id: 0,
      myDialog: {
        qrcode: false, //二维码弹窗
        firm: false, //厂商弹窗
        supply: false, //选择供应合同
        supplier: false, //供应商选择
        guarantee: false, //选择保单
        maintainer: false, //选择维修商
        insurer: false, //选择保险公司
        uploadFiles: false,//上传文件
        uploadImgs: false,//上传单个图片
        pic: false, //多个图片
      },
      addNum: 1,//增加个数
      row: null,//被修改的row
      filesArr: [],//保存临时的文件key
      messKey: null,
      imgsArr: [],//临时保存的图片key数组
      picsArr: [],//临时设备图片keys数组
      param: {
        ProjId: this.$route.query.projId,
        secret: this.$route.query.secret
      },
      floorData: [],
      isWatch: true,
      ajaxResult: true
    };
  },
  created() {
    this.getFloorData()
  },
  mounted() { },
  methods: {
    //设置默认选中数据
    setValue() {
      this.$nextTick(_ => {
        this.$refs.cascader.setValue(this.assetType)
      })
    },
    //获取楼层数据
    getFloorData() {
      getSpaceFloor(this.param).then(res => {
        if (res.data.Result == 'success') {
          let data = this.changeArr(res.data.Content), floorData = []
          data.map(item => {
            if (!!item.children) {
              item.children.unshift({
                value: '',
                label: "未明确楼层的设备"
              })
            }
            return item
          })
          data.map(item => {
            if (!!item.children && item.children.length) {
              item.children.map(child => {
                floorData.push({
                  Code: item.value + "-" + child.value,
                  Name: item.label + "-" + child.label
                })
              })
            }
          })
          this.floorData = floorData
          //   this.options = data
        } 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,
          }
        }
      })
    },

    //增加个数
    addMain() {
      for (let i = 0; i < this.addNum; i++) {
        this.main.push({})
      }
      if (!!this.hot) {
        this.hot.destroy()
      }
      this.initHot()
    },

    //下一步
    step(val) {
      if (!!val) {
        this.isFull = true
        this.isCenter = true
        this.title = "添加资产"
        this.getData()
      } else {
        this.isFull = false
        this.isCenter = false
      }
    },
    //修改设备类型
    changeCader(val) {
      this.deviceType = val
    },
    //获取header的mess
    getHeader(mess) {
      this.mess = mess;
    },

    //获取主体内容
    getMain(floorMess) {
    },

    //获取表头
    getData() {
      this.main = table(1)
      getTableHeader({
        code: this.deviceType.code,
        ProjId: this.$route.query.projId
      }).then(res => {
        this.headers = res.data.Content;
        if (!!this.hot) {
          this.hot.destroy();
          this.hot = null;
        }
        let data = tools.getItem(this.deviceType.code)
        if (!!data) {
          this.main = data
        }
        this.initHot();
      });
    },

    changeWatch() {
      this.getData()
    },

    //撤回
    undo() {
      this.hot.undo();
    },

    //刷新
    reset() {
      this.getData();
    },

    //添加设备
    addDevice() {
    },

    //创建资产
    createAssets() {
      let data = []
      let copyData = tools.copyArr(this.main)
      let falg = false
      copyData.map(item => {
        if (!!item.infos) {
          if (item.infos.EquipLocalName) {
            item.family = this.deviceType.code
            data.push(item)
          } else {
            falg = true
          }
        }
      })
      if (falg) {
        this.$message.error("存在资产的本地名称为空，请检查")
        return
      }
      let params = []
      data.map(item => {
        if (!!item.infos) {
          let one = {}
          if (!!item.flowBuild) {
            one.BuildId = item.flowBuild.split("-")[0]
            one.FloorId = item.flowBuild.split("-")[1] || null
          }
          one.Family = this.deviceType.code
          one.FamilyName = this.deviceType.facility
          one.Infos = item.infos
          one.FmId = "Pe" + uuid(32, 16)
          one.ProjId = this.$route.query.projId
          one.FmName = item.infos.EquipLocalName || ""
          one.X = 0
          one.Y = 0
          params.push(one)
        }
      })
      params.map(item => {
        for (let k in item.Infos) {
          if (item.Infos[k] == "") {
            item.Infos[k] = null
          }
        }
      })
      if (params.length) {
        this.createJson(params)
      } else {
        this.$message.error("信息点不能为空")
      }
    },

    //新建资产请求
    async createJson(data) {
      data.map(item => {
        if (!!item.Infos.DPSupplierID) {
          item.Infos.DPSupplierID = item.Infos.DPSupplierID.split("-")[0]
        }
        if (!!item.Infos.DPManufacturerID) {
          item.Infos.DPManufacturerID = item.Infos.DPManufacturerID.split("-")[0]
        }
        if (!!item.Infos.DPInsurerID) {
          item.Infos.DPInsurerID = item.Infos.DPInsurerID.split("-")[0]
        }
        if (!!item.Infos.DPMaintainerID) {
          item.Infos.DPMaintainerID = item.Infos.DPMaintainerID.split("-")[0]
        }
        if (!!item.Infos.DPSpecificationID) {
          item.Infos.DPSpecificationID = item.Infos.DPSpecificationID.split("-")[0]
        }
        for (let k in item.Infos) {
          if (item.Infos[k] == "") {
            item.Infos[k] = null
          }
        }
        return item
      })
      this.ajaxResult = true
      let param = {
        FmList: data,
        ProjId: this.$route.query.projId,
        UserId: this.$route.query.userId
      }
      await this.createAssetId(param)
    },

    async createAssetId(param) {
      await createAssetsList(param, res => {
        console.log(res)
        if (res.Result != "success") {
          this.$message.error("请求错误")
        } else {
          tools.removeItem(this.deviceType.code)
          this.$emit("close", this.deviceType)
          this.dialog.addDevice = false
        }
      })
    },

    /**
     * 表头文案处理函数
     * @param list header数组数据
     *
     * @return 处理好的文案
     */
    delHeader(list) {
      let arr = tools.copyArr(list)
      // 如果不是只读状态，添加四大厂商选择
      arr = showTools.arrToArr(arr)
      let readArr = ["A1", "A2", "B1", "C5", "D1", "D2", "X", "L", "L1", "L2", "F1", "F2","M"]
      readArr.push("Own")
      let data = showTools.changeHeader(arr, readArr, false, this.isWatch, false, true)
      data.unshift("所属建筑楼层");
      console.log(data, "data")
      return data;
    },

    /**
     * 表头数据处理函数
     * @param list header数组数据
     *
     * @return 处理好的数据格式
     */
    getType(list) {
      let arr = tools.copyArr(list)
      // 如果不是只读状态，添加四大厂商选择
      if (!this.onlyRead) {
        arr = showTools.arrToArr(arr)
      }
      let data = showTools.showTypes(arr, false, this.isWatch, false, true)
      data.unshift(
        {
          data: "flowBuild",
          renderer: tools.customDropdownRenderer,
          editor: "chosen",
          chosenOptions: {
            // multiple: true,//多选
            data: this.floorData
          }
        }
      );
      console.log("type", data)
      return data;
    },


    //初始化插件
    initHot() {
      var container = document.getElementById("myHandson");
      let winHeight = document.documentElement.clientHeight;
      this.hot = new Handsontable(container, {
        data: this.main,
        colHeaders: this.delHeader(this.headers), //表头文案
        columns: this.getType(this.headers), //数据显示格式
        filters: true,
        rowHeaders: true,
        height: winHeight - 100 - 50 - 60,
        columnSorting: true, //添加排序
        sortIndicator: true, //添加排序
        renderAllRows: true,
        autoColumnSize: true,
        language: "zh-CN",
        maxRows: this.main.length,
        manualColumnResize: true,
        manualColumnMove: true,
        dropdownMenu: [
          "filter_by_condition",
          "filter_by_value",
          "filter_action_bar"
        ],
        contextMenu: {
          items: {
            remove_row: {
              name: "删除该资产"
            }
          }
        },
        afterChange: this.tdChange, //修改后
        afterFilter: this.trimmedRows, //排序前
        afterRemoveRow: this.romoveFm, //右键删除
        afterOnCellMouseDown: this.eventClick //鼠标点击
      });
      let pro = document.getElementById("hot-display-license-info");
      if (!!pro) {
        pro.parentNode.removeChild(pro);
      }
      this.isLoading = false;
    },

    tdChange() {
      tools.setItem(this.deviceType.code, this.main)
    },

    //表格中的点击
    eventClick(el, rowArr) {
      //点击的是表头
      if (rowArr.row < 0) {
        return;
      }
      let filter = this.filtersArr;
      //被筛选过后的数组
      let trimmedArr = this.trimmedRows();
      //是否启用了排序
      let isSort = this.hot.getPlugin("columnSorting").isSorted();
      if (trimmedArr.length && isSort) {
        let sortArr = this.myHotArr.getPlugin("columnSorting").rowsMapper
          .__arrayMap;
        let infos = this.main[trimmedArr[sortArr[rowArr.row]]];
        this.getInfors(infos, sortArr[rowArr.row]);
      } else if (isSort) {
        //排序后的数组
        let sortArr = this.hot.getPlugin("columnSorting").rowsMapper.__arrayMap;
        let infos = this.main[sortArr[rowArr.row]];
        this.getInfors(infos, sortArr[rowArr.row]);
      } else if (trimmedArr.length) {
        let infos = this.main[trimmedArr[rowArr.row]];
        this.getInfors(infos, trimmedArr[rowArr.row]);
      } else {
        let infos = this.main[rowArr.row];
        this.getInfors(infos, rowArr);
      }
    },

    getInfors(infos, row) {
      //其他的开始判断
      let val = this.hot.colToProp(row.col);
      if (val == "infos.EquipQRCode") {
        this.myDialog.qrcode = true;
        this.$refs.qrcode.getCanvas(1111);
      }

      if (val == "linkSystem") {
        this.systemList = this.main[row.row].linkSystem || []
        this.dialog.systemType = true
      }

      if (val == "infos.DPManufacturerID") {
        this.myDialog.firm = true;
      }

      if (val == "infos.SupplierContractID") {
        let falg = null
        if (!!this.main[row.row].infos) {
          if (!!this.main[row.row].infos) {
            falg = this.main[row.row].infos.DPSupplierID.split("-")[0]
          }
        }
        if (!!falg) {
          this.id = falg
          this.myDialog.supply = true;
        } else {
          this.$message("请先选择供应商")
        }
      }

      if (val == "infos.InsuranceNum") {
        //选择保单
        let falg = null
        if (!!this.main[row.row].infos) {
          if (!!this.main[row.row].infos) {
            falg = this.main[row.row].infos.DPInsurerID.split("-")[0]
          }
        }
        if (!!falg) {
          this.id = falg
          this.myDialog.guarantee = true;
        } else {
          this.$message("请先选择保险商")
        }
      }

      if (val == "infos.InsuranceFile" || val == "infos.Archive") {
        this.filesArr = this.main[row.row].infos ? (this.main[row.row].infos[val.split(".")[1]] ? [this.main[row.row].infos[val.split(".")[1]]] : []) : []
        this.myDialog.uploadFiles = true
      }

      if (
        val == "infos.InstallPic" ||
        val == "infos.InstallDrawing" ||
        val == "infos.Nameplate" ||
        val == "infos.Drawing"
      ) {
        if (val == "infos.Nameplate") {
          this.imgsArr = this.main[row.row].infos ? (this.main[row.row].infos[val.split(".")[1]] ? [this.main[row.row].infos[val.split(".")[1]].key] : []) : []
        } else {
          this.imgsArr = this.main[row.row].infos ? (this.main[row.row].infos[val.split(".")[1]] ? [this.main[row.row].infos[val.split(".")[1]]] : []) : []
        }
        this.myDialog.uploadImgs = true
      }

      if (val == "infos.Pic") {
        this.picsArr = this.main[row.row].infos ? (this.main[row.row].infos[val.split(".")[1]] ? this.main[row.row].infos[val.split(".")[1]] : []) : []
        this.myDialog.pic = true
      }

      if (
        val == "infos.Supplier"
      ) {
        this.myDialog.supplier = true;
      }

      if (
        val == "infos.DPSupplierID"
      ) {
        this.myDialog.supplier = true;
      }

      if (val == "infos.DPMaintainerID"
      ) {
        this.myDialog.maintainer = true;
      }

      if (
        val == "infos.DPInsurerID"
      ) {
        this.myDialog.insurer = true;
      }

      if (val == "infos.Maintainer") {
        this.myDialog.maintainer = true;
      }

      if (
        val == "infos.Insurer" ||
        val == "infos.InsurerContactor") {
        this.myDialog.insurer = true;
      }
      this.row = row.row
      this.messKey = val
      console.log(val, row);
    },

    //获取被筛选掉的行号
    trimmedRows() {
      // var plugin = hot.getPlugin('trimRows').trimmedRows;//获取被筛选掉的行号
      var plugin = this.hot.getPlugin("trimRows").trimmedRows;
      let dataLength = this.main.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.hot.getSourceDataAtRow(plugin[i]));
      // }
    },

    //判断是否为空行
    isEmptyRow(instance, row) {
      var rowData = instance.countRows();
      for (var i = 0, ilen = rowData.length; i < ilen; i++) {
        if (rowData[i] !== null) {
          return false;
        }
      }
      return true;
    },

    //选择型号修改
    firmChange(data) {
      for (let key in data) {
        // this.utilToKey(key, "brand", data, "Brand")
        // this.utilToKey(key, "name", data, "Specification")
        // this.utilToKey(key, "venderName", data, "Manufacturer")
        if (key == "venderId") {
          data[key] = data[key] + "-" + data.name + "/" + data.brand
          this.utilToKey(key, "venderId", data, "DPManufacturerID")
        }
        this.utilToKey(key, "specificationId", data, "DPSpecificationID")
      }
      tools.setItem(this.deviceType.code, this.main)
    },

    //如果选择供应商之后
    supplierChange(data) {
      for (let key in data) {
        // this.utilToKey(key, "name", data, "Supplier")
        // this.utilToKey(key, "email", data, "SupplierEmail")
        // this.utilToKey(key, "website", data, "SupplierWeb")
        // this.utilToKey(key, "phone", data, "SupplierPhone")
        // this.utilToKey(key, "fox", data, "SupplierFax")
        // this.utilToKey(key, "man", data, "SupplierContactor")
        if (key == "venderId") {
          data[key] = data[key] + "-" + data.name
          console.log(data)
          this.utilToKey(key, "venderId", data, "DPSupplierID")
        }
        // this.utilToKey(key, "specificationId", data, "DPSpecificationID")
      }
      tools.setItem(this.deviceType.code, this.main)
    },

    //供应商合同
    supplyChange(data) {
      let changeData = { id: data }
      this.utilToKey("id", "id", changeData, "SupplierContractID")
      tools.setItem(this.deviceType.code, this.main)
    },

    //保险合同
    guaranteeChange(data) {
      for (let key in data) {
        this.utilToKey(key, "insuranceNo", data, "InsuranceNum")
        if (key == "contractFile") {
          if (!!data[key]) {
            data[key] = [data[key]]
          }
        }
        this.utilToKey(key, "contractFile", data, "InsuranceFile")
      }
      tools.setItem(this.deviceType.code, this.main)
    },

    //保险商变更
    changeInsurer(data) {
      for (let key in data) {
        // this.utilToKey(key, "name", data, "Insurer")
        // this.utilToKey(key, "email", data, "InsurerEmail")
        // this.utilToKey(key, "website", data, "InsurerWeb")
        // this.utilToKey(key, "phone", data, "InsurerFax")
        // this.utilToKey(key, "man", data, "InsurerContactor")
        if (key == "venderId") {
          data[key] = data[key] + "-" + data.name
          this.utilToKey(key, "venderId", data, "DPInsurerID")
        }
      }
      tools.setItem(this.deviceType.code, this.main)
    },

    //维修商变更
    changeMaintainer(data) {
      for (let key in data) {
        // this.utilToKey(key, "name", data, "Maintainer")
        // this.utilToKey(key, "email", data, "MaintainerEmail")
        // this.utilToKey(key, "website", data, "MaintainerWeb")
        // this.utilToKey(key, "phone", data, "MaintainerPhone")
        // this.utilToKey(key, "fox", data, "MaintainerFax")
        // this.utilToKey(key, "man", data, "MaintainerContactor")
        if (key == "venderId") {
          data[key] = data[key] + "-" + data.name
          this.utilToKey(key, "venderId", data, "DPMaintainerID")
        }
      }
      tools.setItem(this.deviceType.code, this.main)
    },

    utilToKey(key, name, data, messName) {
      if (key == name) {
        this.setDataToMain(data[key], messName, this.row)
      }
    },

    //上传文件弹窗触发事件
    fileChange(keys) {
      this.setDataToMain(keys[0], this.messKey.split("."), this.row)
      tools.setItem(this.deviceType.code, this.main)
    },

    //上传图片弹窗触发事件
    imgChange(keys) {
      this.setDataToMain(keys[0], this.messKey.split("."), this.row)
      tools.setItem(this.deviceType.code, this.main)
    },

    //设备图片弹窗改变事件
    changePics(keys) {
      this.setDataToMain(keys, this.messKey.split("."), this.row)
      tools.setItem(this.deviceType.code, this.main)
    },

    //判断是否有值，有值赋值
    setDataToMain(data, key, row) {
      if (!!data && data != '--') {
        if (!!this.main[row].infos) {
          //铭牌照片特殊处理
          this.main[row].infos[key] = data
        } else {
          this.main[row].infos = {}
          this.main[row].infos[key] = data
        }
      } else {
        this.main[row].infos[key] = ''
      }
    }
  },
  watch: {
    dialog: {
      deep: true,
      handler: function () {
        if (this.dialog.addDevice) {
          this.setValue()
        }
      }
    }
  }
};
</script>
<style lang="less" scoped>
#addDevice {
  overflow: hidden;
}
</style>
