import {
  httpGet,
  httpPost
} from "../api";
import moment from 'moment'
import {
  api
} from "../api/all";
import ICINLocker from "../utils/equipment.js"
import {
  message
} from './resetMessage';
import pako from 'pako'
import md5 from 'js-md5'
import CryptoJS from "crypto-js";

let Base64 = require('js-base64')
import {dec2hex} from "./index.js"

/**
 * @param {Function} fn 防抖函数
 * @param {Number} delay 延迟时间
 */

export default class utils {
  // 扁平化树形数据
  static treeToArray(tree) {
    let res = []
    for (const item of tree) {
      const { subs, ...i } = item
      if (subs && subs.length) {
        res = res.concat(this.treeToArray(subs))
      }
      res.push(i)
    }
    return res
  }
  // 检测入住人员数组对象中是否有重复值
  static isRepeat(arr) {
    let hash = {};
    for (let i in arr) {
      if (
        hash[arr[i].phone] ||
        hash[arr[i].number]
      ) {
        return true;
      } else {
        hash[arr[i].phone] = true
        hash[arr[i].number] = true
      }
    }
    return false;

  }
  // 校验手机号
  static verificationPhone(str) {
    return /^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(str);
  }

static
FromBase64(base64)
{
  return new Buffer.from(base64, "base64").toString();
}
static
decrypt(word, keyStr)
{
  let key = CryptoJS.enc.Utf8.parse(keyStr);
  let decrypt = CryptoJS.AES.decrypt(word, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return CryptoJS.enc.Utf8.stringify(decrypt).toString()
}
static
zlib_unzip(info)
{
  var key = md5(String(info.currentTime) + "mdmdmdmdmdvsololololol")
  let b = info.list.split(',').map(function (x) {
    return parseInt(x);
  });
  let c = pako.inflate(b, {
    to: "string"
  });
  let e = this.decrypt(c, key)
  return JSON.parse(e)
}
  static
  validObject(obj)
  {
    let objectData = new Object()
    for (let i in obj) {
      if (obj[i] != '' && obj[i]) {
        objectData[i] = obj[i]
      }
    }
    return objectData;
  }
/**
 * 树级列表排序
 * @param origList 列表
 * @param idName id字段名
 * @param pidName 上级id字段名
 * @returns {any[]}
 */

static
getOrderList(origList, idName, pidName)
{
  //遍历获取MAP(pid->Object)
  var pidMap = new Map();
  for (var i = 0; i < origList.length; i++) {
    var item = origList[i];
    if (item[pidName] != null && item[pidName] != "") {
      if (pidMap.get(item[pidName]) != null) {
        pidMap.get(item[pidName]).push(item);
      } else {
        pidMap.set(item[pidName], [item]);
      }
    }
  }
  console.log(pidMap)
  //排序
  var rstList = new Array();
  for (var i = 0; i < origList.length; i++) {
    var item = origList[i];
    if (!item[pidName]) {
      rstList.push(item);
      this.pushChildList(rstList, item, pidMap, idName, pidName);
    }
  }
  return rstList;
}

//递归调用获取子节点的子节点
static
pushChildList(rstList, item, pidMap, idName, pidName)
{
  if (pidMap.get(item[idName]) != null && pidMap.get(item[idName]).length > 0) {
    for (var i = 0; i < pidMap.get(item[idName]).length; i++) {
      rstList.push(pidMap.get(item[idName])[i]);
      this.pushChildList(rstList, pidMap.get(item[idName])[i], pidMap, idName, pidName);
    }
  }
}

// 递归根据子节点id拿到完整路径
static
findIndexArray(data, id, indexArray)
{
  let arr = Array.from(indexArray);
  for (let i = 0, len = data.length; i < len; i++) {
    arr.push(data[i].name);
    if (data[i].id === id) {
      return arr
    }
    let children = data[i].children;
    if (children && children.length) {
      let result = this.findIndexArray(children, id, arr);
      if (result) return result
    }
    arr.pop()
  }
  return false
}
// 递归根据子节点id拿到完整路径
static
findIndexArrayOne(data, id, indexArray)
{
  let arr = Array.from(indexArray);
  for (let i = 0, len = data.length; i < len; i++) {
    arr.push(data[i].id);
    if (data[i].id === id) {
      return arr
    }
    let children = data[i].children;
    if (children && children.length) {
      let result = this.findIndexArrayOne(children, id, arr);
      if (result) return result
    }
    arr.pop()
  }
  return false
}
// 卡片转换
static
cardFormatConversion(data)
{
  var arr = data.split("")
  return arr[6] + arr[7] + arr[4] + arr[5] + arr[2] + arr[3] + arr[0] + arr[1]
}
// 锁用户凭证
static
sendLockUser(data, callback)
{
  var data = {
    deviceNum: data.deviceNum,
    imei: data.imei,
    cardId: data.cardId,
    content: data.content, //operateMode:NFC-10、把人员添加到凭证-1
    type: data.type,
    serial: data.serial,
    startTime: data.startTime,
    endTime: data.endTime,
  };
  httpPost(data, api.addCertificates).then((res) => {
    callback(res)
  });
}
// 设备反馈日志重新下发
static
CommandReissue(voucer, code)
{
  var data = {
    q: JSON.stringify({
      deviceNum: code.deviceNum
    }),
    pageNum: 1,
    pageSize: 1,
  };
  httpPost(data, api.getDeviceItems).then((res) => {
    if (res.success) {
      if (res.data.total > 0) {
        var deviceInfo = res.data.list[0]
        if (deviceInfo.manufactureId == 101) {
          ICINLocker.LDAddCertificate(voucer, (callback) => {
            if (callback.success) {
              var updatedata = {
                id: voucer.id,
                serial: callback.data.serialNumber
              };
              httpPost(updatedata, that.$api.updateCertificates).then(res2 => {
                if (res2.success) {
                  message({
                    type: "success",
                    message: "更新凭证成功"
                  })
                } else {
                  message({
                    type: "error",
                    message: "更新凭证失败"
                  })
                }
              })
              var data4 = {
                result: 1,
                serial: code.serial
              }
              httpPost(data4, api.updatePush).then(res3 => {
                if (res3.success) {
                  message({
                    type: "success",
                    message: "更新日志成功"
                  })
                } else {
                  message({
                    type: "error",
                    message: "更新日志失败"
                  })
                }
              })
            } else {
              message({
                type: "error",
                message: "发送失败"
              })
            }
          })
        } else if (deviceInfo.manufactureId == 201 || deviceInfo.manufactureId == 221) {
          ICINLocker.ZGAddCertificate(voucer, (callback) => {
            if (callback.success) {
              var updatedata = {
                id: voucer.id,
                serial: callback.data.serialNumber
              };
              httpPost(updatedata, that.$api.updateCertificates).then(res2 => {
                if (res2.success) {
                  message({
                    type: "success",
                    message: "更新凭证成功"
                  })
                } else {
                  message({
                    type: "error",
                    message: "更新凭证失败"
                  })
                }
              })
              var data4 = {
                result: 1,
                serial: code.serial
              }
              httpPost(data4, api.updatePush).then(res3 => {
                if (res3.success) {
                  message({
                    type: "success",
                    message: "更新日志成功"
                  })
                } else {
                  message({
                    type: "error",
                    message: "更新日志失败"
                  })
                }
              })
            } else {
              message({
                type: "error",
                message: "发送失败"
              })
            }
          })
        }
      } else {
        message({
          type: "error",
          message: "未获取到命令对应设备信息"
        })
      }
    } else {
      message({
        type: "error",
        message: "获取设备内容失败"
      })
    }
  })
}
// 下发凭证
static
putCarfidzgAdd(resultArr, row)
{
  var data = {};
  var userTelephone = JSON.parse(row.content).userTelephone;
  var userPassword = JSON.parse(row.content).userPassword;
  var startTime = row.startTime
  var endTime = row.endTime
  var passwordStartTime = row.startTime
  var passwordEndTime = row.endTime

  if (row.type == 1) {
    var fpId = new Date();
    var fingerprint1 = JSON.parse(row.content).fingerprint;
    var str = {
      imei: resultArr.imei,
      deviceNum: resultArr.deviceNum,
      userTelephone: userTelephone,
      userPassword: userPassword,
      password: JSON.parse(row.content).password,
      length: fingerprint1.length / 2,
      fpTimeId: fpId.getTime(),
      operateMode: 16,
      order: 6216,
      fingerprint: fingerprint1,
      passwordStartTime: passwordStartTime,
      passwordEndTime: passwordEndTime,
      pzname: JSON.parse(row.content).pzname
    };
    var data3 = {
      lockerId: resultArr.deviceNum,
      imei: resultArr.imei,
      order: 6216,
      lockerUserId: userPassword,
      keyId: userPassword,
      fingerType: 0,
      file: fingerprint1,
      cardName: row.name + '-' + JSON.parse(row.content).pzname,
      roomName: resultArr.roomName,
      startTime: passwordStartTime,
      endTime: passwordEndTime
    };
    ICINLocker.addFingerPrints(data3.lockerId, data3.imei, data3.lockerUserId, data3.fingerType, data3
      .file, data3.startTime, data3.endTime, data3.cardName, data3.roomName, (callback) => {
      console.log(callback, 'callbackcallbackcallback')
      if (callback.success) {
        var data = {
          id: row.id,
          serial: callback.data.serialNumber,
        };
        httpPost(data, api.updateCertificates).then((res) => {
          message({
            type: "success",
            message: "下发成功"
          })
        });
      } else {
        message({
          type: "error",
          message: callback.msg
        })
      }
    })
  } else if (row.type == 2) {
    if (JSON.parse(row.content).password.length != 16) {
      message({
        type: "error",
        message: "卡格式错误，请重新录入"
      })
      return
    }
    var str = {
      imei: resultArr.imei,
      userTelephone: userTelephone,
      cardId: row.cardId,
      userPassword: userPassword,
      password: JSON.parse(row.content).password,
      operateMode: 13,
      order: 6213,
      passwordStartTime: passwordStartTime,
      passwordEndTime: passwordEndTime,
      pzname: JSON.parse(row.content).pzname,
      is: false,
    };
    var data3 = {
      lockerId: resultArr.deviceNum,
      imei: resultArr.imei,
      lockerUserId: userPassword,
      keyId: userPassword,
      action: 1,
      taskStatus: 1,
      order: 6210,
      startTime: passwordStartTime,
      endTime: passwordEndTime,
      cardType: 36,
      cardName: row.name + '-' + JSON.parse(row.content).pzname,
      roomName: row.roomName,
      cardNo: JSON.parse(row.content).password
    };
    ICINLocker.RfCardRegister(data3.lockerId, data3.imei, data3.keyId, data3.action, data3.taskStatus,
      data3.cardNo, data3.cardType, data3.startTime,
      data3.endTime, data3.order, data3.cardName, data3.roomName, (callback) => {
        if (callback.success) {
          var data = {
            id: row.id,
            serial: callback.data.serialNumber,
          };
          httpPost(data, api.updateCertificates).then((res) => {
            message({
              type: "success",
              message: "下发成功"
            })
          });
        } else {
          message({
            type: "error",
            message: callback.msg
          })
        }
      })
  } else if (row.type == 3) {
    if (JSON.parse(row.content).password.length != 8) {
      message({
        type: "error",
        message: "卡格式错误，请重新录入"
      })
      return
    }
    var str = {
      imei: resultArr.imei,
      userTelephone: userTelephone,
      cardId: row.cardId,
      userPassword: userPassword,
      password: JSON.parse(row.content).password,
      operateMode: 10,
      order: 6210,
      passwordStartTime: passwordStartTime,
      passwordEndTime: passwordEndTime,
      pzname: JSON.parse(row.content).pzname,
      is: false,
    };
    var data3 = {
      lockerId: resultArr.deviceNum,
      lockerUserId: userPassword,
      keyId: userPassword,
      imei: resultArr.imei,
      action: 1,
      taskStatus: 1,
      order: 6210,
      startTime: passwordStartTime,
      endTime: passwordEndTime,
      cardType: 50,
      cardName: row.name + '-' + JSON.parse(row.content).pzname,
      roomName: row.roomName,
      cardNo: JSON.parse(row.content).password
    };
    ICINLocker.RfCardRegister(data3.lockerId, data3.imei, data3.keyId, data3.action, data3.taskStatus,
      data3.cardNo, data3.cardType, data3.startTime,
      data3.endTime, data3.order, data3.cardName, data3.roomName, (callback) => {
        if (callback.success) {
          var data = {
            id: row.id,
            serial: callback.data.serialNumber,
          };
          httpPost(data, api.updateCertificates).then((res) => {
            message({
              type: "success",
              message: "下发成功"
            })
          });
        } else {
          message({
            type: "error",
            message: callback.msg
          })
        }
      })
  } else if (row.type == 4) {
    str = {
      imei: resultArr.imei,
      userTelephone: userTelephone,
      cardId: row.cardId,
      userPassword: userPassword,
      password: JSON.parse(row.content).password,
      operateMode: 7,
      order: 6207,
      passwordStartTime: passwordStartTime,
      passwordEndTime: passwordEndTime,
      pzname: JSON.parse(row.content).pzname,
      is: false,
      cardName: row.name + '-' + JSON.parse(row.content).pzname,
      roomName: row.roomName
    };
    var data3 = {
      lockerId: resultArr.deviceNum,
      imei: resultArr.imei,
      order: 6207,
      passwordCount: 255,
      lockerUserId: userPassword,
      keyId: userPassword,
      startTime: passwordStartTime,
      endTime: passwordEndTime,
      action: 1,
      password: JSON.parse(row.content).password,
      cardName: row.name + '-' + JSON.parse(row.content).pzname,
      roomName: row.roomName
    };
    ICINLocker.addForeverPassword(data3.lockerId, data3.imei, data3.keyId, data3.action, data3.password,
      data3.passwordCount, data3.startTime, data3.endTime, data3.order, data3.cardName, data3
        .roomName, (callback) => {
        if (callback.success) {
          var data = {
            id: row.id,
            serial: callback.data.serialNumber,
          };
          httpPost(data, api.updateCertificates).then((res) => {
            message({
              type: "success",
              message: "下发成功"
            })
          });

        } else {
          message({
            type: "error",
            message: callback.msg
          })
        }
      })

  }
}
// 下发凭证
static
putCarfidAdd(resultArr, row)
{
  var data = {};
  var userTelephone = JSON.parse(row.content).userTelephone;
  var userPassword = JSON.parse(row.content).userPassword;
  var startTime = row.startTime
  var endTime = row.endTime
  var passwordEndTime = moment(endTime * 1000).format("YYYYMMDDHHmmss");
  var passwordStartTime = moment(startTime * 1000).format("YYYYMMDDHHmmss");
  if (row.type == 1) {
    var fpId = new Date();
    var fingerprint = JSON.parse(row.content).fingerprint;
    var str = {
      imei: resultArr.imei,
      deviceNum: resultArr.deviceNum,
      userTelephone: userTelephone,
      userPassword: userPassword,
      password: JSON.parse(row.content).password,
      length: fingerprint.length / 2,
      fpTimeId: fpId.getTime(),
      operateMode: 16,
      order: 6216,
      fingerprint: fingerprint,
      passwordStartTime: passwordStartTime,
      passwordEndTime: passwordEndTime,
      cardName: row.name + '-' + JSON.parse(row.content).pzname,
      roomName: resultArr.roomName,
    };
    ICINLocker.LDAddFingerPrints(str.deviceNum, str.imei, str.userTelephone, str.userPassword, str
        .password, str.passwordStartTime, str.passwordEndTime, str.operateMode, str.order, str.length,
      str.fpTimeId, str.fingerprint, str.cardName, str.roomName, (callback) => {
        if (callback.success) {
          var datafid = {
            id: row.id,
            serial: callback.data.serialNumber,
          };
          httpPost(datafid, api.updateCertificates).then((res) => {
            if (res.success) {
              message({
                type: "success",
                message: "下发成功"
              })
            } else {
              message({
                type: "error",
                message: "下发失败"
              })
            }
          });
        } else {
          message({
            type: "error",
            message: callback.msg
          })
        }
      })
    return false
  } else if (row.type == 2) {
    data = {
      imei: resultArr.imei,
      deviceNum: resultArr.deviceNum,
      userTelephone: userTelephone,
      cardId: row.cardId,
      userPassword: userPassword,
      password: JSON.parse(row.content).password,
      operateMode: 13,
      order: 6213,
      passwordStartTime: passwordStartTime,
      passwordEndTime: passwordEndTime,
      is: false,
      cardName: row.name + '-' + JSON.parse(row.content).pzname,
      roomName: resultArr.roomName,
    };
  } else if (row.type == 3) {
    data = {
      imei: resultArr.imei,
      deviceNum: resultArr.deviceNum,
      userTelephone: userTelephone,
      cardId: row.cardId,
      userPassword: userPassword,
      password: JSON.parse(row.content).password,
      operateMode: 10,
      order: 6210,
      passwordStartTime: passwordStartTime,
      passwordEndTime: passwordEndTime,
      is: false,
      cardName: row.name + '-' + JSON.parse(row.content).pzname,
      roomName: resultArr.roomName,
    };
  } else if (row.type == 4) {
    data = {
      imei: resultArr.imei,
      deviceNum: resultArr.deviceNum,
      userTelephone: userTelephone,
      cardId: row.cardId,
      userPassword: userPassword,
      password: JSON.parse(row.content).password,
      operateMode: 7,
      order: 6207,
      passwordStartTime: passwordStartTime,
      passwordEndTime: passwordEndTime,
      is: false,
      cardName: row.name + '-' + JSON.parse(row.content).pzname,
      roomName: resultArr.roomName,
    };
  }
  ICINLocker.LDRfCardRegister(data.deviceNum, data.imei, data.userTelephone, data.userPassword, data
    .password, data
    .passwordStartTime, data.passwordEndTime, data.operateMode, data.order, data.cardName, data
    .roomName, false, (callback) => {
    if (callback.success) {
      var datafid = {
        id: row.id,
        serial: callback.data.serialNumber,
      };
      httpPost(datafid, api.updateCertificates).then((res) => {
        if (res.success) {
          message({
            type: "success",
            message: "下发成功"
          })
        } else {
          message({
            type: "error",
            message: "下发失败"
          })
        }
      });
    } else {
      message({
        type: "error",
        message: callback.msg
      })
    }
  })
}
static
getfiId1(row, callback)
{
  var data = {
    q: JSON.stringify({
      serial: row.serial,
    }),
    pageNum: 1,
    pageSize: 10,
  };
  httpPost(data, api.getDeviceResult).then((res) => {
    let datalist = this.zlib_unzip(res.data)
    callback(datalist);
  });
}
static
putCarfid(resultArr, row, endTime, startTime)
{
  var data = {};
  var userTelephone = JSON.parse(row.content).userTelephone;
  var userPassword = JSON.parse(row.content).userPassword;
  var content = JSON.parse(row.content);
  var passwordEndTime = moment(endTime).format("YYYYMMDDHHmmss");
  var passwordStartTime = moment(startTime).format("YYYYMMDDHHmmss");
  if (row.type == 1) {
    this.getfiId1(row, function (data) {
      if (data.length > 0) {
        if (data.length > 0) {
          var fpid = "";
          fpid =
            data[0].face.toString(16).length != 2 ?
              "0" + data[0].face.toString(16) :
              data[0].face.toString(16);
          var str = {
            imei: resultArr.imei,
            deviceNum: resultArr.deviceNum,
            password: fpid,
            operateMode: 17,
            order: 6217,
            userPassword: userPassword,
            userTelephone: userTelephone,
            passwordStartTime: passwordEndTime,
            passwordEndTime: passwordStartTime,
            is: false,
            cardName: row.name + '-' + content.pzname,
            roomName: resultArr.roomName,
          };
          content['passwordStartTime'] = passwordStartTime
          content['passwordEndTime'] = passwordEndTime
          content['password'] = fpid
          content['cardName'] = str.cardName
          content['roomName'] = str.roomName
          httpPost(str, api.getDeviceOperateUserInfo).then((res1) => {
            if (res1.success) {
              content.passwordStartTime = str.passwordStartTime;
              content.passwordEndTime = str.passwordEndTime;
              var updatedata = {
                id: row.id,
                content: JSON.stringify(content),
                serial: res1.data.serialNumber,
                status: 0,
                startTime: startTime / 1000,
                endTime: endTime / 1000
              };
              httpPost(updatedata, api.updateCertificates)
                .then(
                  (res2) => {
                    that.$message.success("修改成功");
                  }
                );
            } else {
              that.$message.success("修改失败");
            }
          });
        }
      }
    })
    return false
  } else if (row.type == 2) {
    data = {
      imei: resultArr.imei,
      deviceNum: resultArr.deviceNum,
      userTelephone: userTelephone,
      cardId: row.cardId,
      userPassword: userPassword,
      password: JSON.parse(row.content).password,
      operateMode: 14,
      order: 6214,
      passwordStartTime: passwordStartTime,
      passwordEndTime: passwordEndTime,
      is: false,
      cardName: row.name + '-' + content.pzname,
      roomName: row.roomName
    };
  } else if (row.type == 3) {
    data = {
      imei: resultArr.imei,
      deviceNum: resultArr.deviceNum,
      userTelephone: userTelephone,
      cardId: row.cardId,
      userPassword: userPassword,
      password: JSON.parse(row.content).password,
      operateMode: 11,
      order: 6211,
      passwordStartTime: passwordStartTime,
      passwordEndTime: passwordEndTime,
      is: false,
      cardName: row.name + '-' + content.pzname,
      roomName: row.roomName
    };
  } else if (row.type == 4) {
    data = {
      imei: resultArr.imei,
      deviceNum: resultArr.deviceNum,
      userTelephone: userTelephone,
      cardId: row.cardId,
      userPassword: userPassword,
      password: JSON.parse(row.content).password,
      operateMode: 8,
      order: 6208,
      passwordStartTime: passwordStartTime,
      passwordEndTime: passwordEndTime,
      is: false,
      cardName: row.name + '-' + content.pzname,
      pzname: content.pzname,
      roomName: row.roomName
    };
  }
  ICINLocker.LDRfCardRegister(data.deviceNum, data.imei, data.userTelephone, data.userPassword, data
    .password, data
    .passwordStartTime, data.passwordEndTime, data.operateMode, data.order, data.cardName, data
    .roomName, false, (
    callback) => {
    if (callback.success) {
      content['passwordStartTime'] = data.passwordStartTime
      content['passwordEndTime'] = data.passwordEndTime
      content['cardName'] = data.cardName
      content['roomName'] = data.roomName
      var datafid = {
        id: row.id,
        content: JSON.stringify(content), //operateMode:NFC-10、把人员添加到凭证-1
        status: 0,
        serial: callback.data.serialNumber,
        startTime: moment(startTime).valueOf() / 1000,
        endTime: moment(endTime).valueOf() / 1000,
      };
      httpPost(datafid, api.updateCertificates).then((res) => {
        if (res.success) {
          message({
            type: "success",
            message: "下发成功"
          })
        } else {
          message({
            type: "error",
            message: "下发失败"
          })
        }
      });
    } else {
      message({
        type: "error",
        message: callback.msg
      })
    }
  })
}
// 下发凭证
static
putCarfidzg(resultArr, row, startTime, endTime)
{
  var data = {};
  var userTelephone = JSON.parse(row.content).userTelephone;
  var userPassword = JSON.parse(row.content).userPassword;
  var content = JSON.parse(row.content);
  var passwordEndTime = moment(endTime).valueOf() / 1000;
  var passwordStartTime = moment(startTime).valueOf() / 1000;
  if (row.type == 1) {
    this.getfiId1(row, function (data) {
      if (data.length > 0) {
        var fpid = "";
        fpid = data[0].face.toString(16).length != 2 ? "0" + data[0].face.toString(16) : data[0].face;
        var pwd = JSON.parse(row.content).userPassword
        var cardName = row.name + '-' + content.pzname
        ICINLocker.modifyFingerPrints(resultArr.deviceNum, resultArr.imei, pwd, 3,
          fpid, 0, passwordStartTime, passwordEndTime, cardName, resultArr.roomName, (callback) => {
            if (callback.success) {
              var str1 = JSON.parse(row.content);
              str1.fpTimeId = callback.data.serialNumber;
              str1.passwordStartTime = passwordStartTime;
              str1.passwordEndTime = passwordEndTime;
              var updatedata = {
                id: row.id,
                content: JSON.stringify(str1),
                serial: callback.data.serialNumber,
                status: 0,
                startTime: passwordStartTime,
                endTime: passwordEndTime
              };
              httpPost(updatedata, api.updateCertificates)
                .then(
                  (res2) => {
                    message({
                      type: "success",
                      message: "下发成功"
                    })
                  });
              that.$message.success(callback.msg)
            } else {
              that.$message.error(callback.msg)
            }
          })
      } else {
        that.$message.error("修改失败")
      }
    })
  } else if (row.type == 2) {
    var idcard = ''
    if (content.password.length == 16) {
      idcard = content.password
    } else {
      idcard = dec2hex(content.password);
    }
    var userid = JSON.parse(row.content).userPassword
    if (idcard.length != 16) {
      message({
        type: "error",
        message: "卡格式错误，请重新录入"
      })
      return
    }
    var cardName = row.name + '-' + content.pzname
    ICINLocker.RfCardRegister(resultArr.deviceNum, resultArr.imei, userid, 3, 1, idcard
      .toUpperCase(), 36, passwordStartTime, passwordEndTime, 6211, cardName, resultArr
      .roomName, (callback) => {
      if (callback.success) {
        var str = JSON.parse(row.content)
        str['password'] = idcard.toUpperCase()
        var updatedata = {
          id: row.id,
          content: JSON.stringify(str),
          serial: callback.data.serialNumber,
          startTime: passwordStartTime,
          endTime: passwordEndTime
        };
        httpPost(updatedata, this.$api.updateCertificates).then((res) => {
          message({
            type: "success",
            message: "下发成功"
          })

        });
        message({
          type: "success",
          message: callback.msg
        })
      } else {
        message({
          type: "error",
          message: callback.msg
        })
      }
    })
  } else if (row.type == 3) {
    var nfc = "";
    if (content.password.length == 8) {
      nfc = content.password
    } else {
      nfc = dec2hex(content.password);
    }
    var userid = JSON.parse(row.content).userPassword
    if (nfc.length != 8) {
      message({
        type: "error",
        message: "卡格式错误，请重新录入"
      })
      return
    }
    var cardName = row.name + '-' + content.pzname
    ICINLocker.RfCardRegister(resultArr.deviceNum, resultArr.imei, userid, 3, 1, nfc.toUpperCase(),
      50, passwordStartTime, passwordEndTime, 6211, cardName, resultArr.roomName, (
        callback) => {
        if (callback.success) {
          var str = JSON.parse(row.content)
          str['password'] = nfc.toUpperCase()
          str['pzname'] = JSON.parse(row.content).pzname
          var updatedata = {
            id: row.id,
            content: JSON.stringify(str),
            serial: callback.data.serialNumber,
            startTime: passwordStartTime,
            endTime: passwordEndTime
          };
          httpPost(updatedata, api.updateCertificates).then((res) => {
            message({
              type: "success",
              message: "下发成功"
            })

          });
          message({
            type: "success",
            message: callback.msg
          })
        } else {
          message({
            type: "error",
            message: callback.msg
          })
        }
      })
  } else if (row.type == 4) {
    var pwd = content.password
    var userid = JSON.parse(row.content).userPassword
    var cardName = row.name + '-' + content.pzname
    ICINLocker.addForeverPassword(resultArr.deviceNum, resultArr.imei, userid, 3, pwd, 255,
      passwordStartTime, passwordEndTime, 6208, cardName, resultArr.roomName, (
        callback) => {
        if (callback.success) {
          var data1 = JSON.parse(row.content)
          data1['password'] = content.password
          var updatedata = {
            id: row.id,
            content: JSON.stringify(data1),
            serial: callback.data.serialNumber,
            startTime: passwordStartTime,
            endTime: passwordEndTime
          };
          httpPost(updatedata, api.updateCertificates).then((res) => {
            message({
              type: "success",
              message: "下发成功"
            })

          });
          message({
            type: "success",
            message: callback.msg
          })
        } else {
          message({
            type: "error",
            message: callback.msg
          })
        }
      })

  }
}

static
modifyPutCarfid(resultArr, row, startTime, endTime)
{
  var data = {};
  var userTelephone = JSON.parse(row.content).userTelephone;
  var userPassword = JSON.parse(row.content).userPassword;
  var content = JSON.parse(row.content);
  var passwordEndTime = moment(endTime).format("YYYYMMDDHHmmss");
  var passwordStartTime = moment(startTime).format("YYYYMMDDHHmmss");
  if (row.type == 1) {
    this.getfiId1(row, function (data) {
      if (data.length > 0) {
        if (data.length > 0) {
          var fpid = "";
          fpid =
            data[0].face.toString(16).length != 2 ?
              "0" + data[0].face.toString(16) :
              data[0].face.toString(16);
          var str = {
            imei: resultArr.imei,
            deviceNum: resultArr.deviceNum,
            password: fpid,
            operateMode: 17,
            order: 6217,
            userPassword: userPassword,
            userTelephone: userTelephone,
            passwordStartTime: passwordStartTime,
            passwordEndTime: passwordEndTime,
            is: false,
            cardName: row.name + '-' + (content.pzname ? content.pzname : ''),
            roomName: resultArr.roomName,
          };
          content['passwordStartTime'] = passwordStartTime
          content['passwordEndTime'] = passwordEndTime
          content['password'] = fpid
          content['cardName'] = str.cardName
          content['roomName'] = str.roomName
          httpPost(str, api.getDeviceOperateUserInfo).then((res1) => {
            if (res1.success) {
              content.passwordStartTime = str.passwordStartTime;
              content.passwordEndTime = str.passwordEndTime;
              var updatedata = {
                cardId: resultArr.cardId,
                deviceNum: resultArr.deviceNum,
                type: row.type,
                imei: resultArr.imei,
                content: JSON.stringify(content),
                serial: res1.data.serialNumber,
                startTime: startTime / 1000,
                endTime: endTime / 1000
              };
              httpPost(updatedata, api.addCertificates)
                .then(
                  (res2) => {
                    message({
                      type: "success",
                      message: "修改成功"
                    })
                  }
                );
              var updatestatus = {
                id: row.id,
                status: 703
              }
              httpPost(updatestatus, api.updateCertificates)
                .then(
                  (res3) => {
                    message({
                      type: "success",
                      message: "更新成功"
                    })
                  });
            } else {
              message({
                type: "error",
                message: "修改失败"
              })
            }
          });
        }
      }
    })
    return false
  } else if (row.type == 2) {
    data = {
      imei: resultArr.imei,
      deviceNum: resultArr.deviceNum,
      userTelephone: userTelephone,
      cardId: row.cardId,
      userPassword: userPassword,
      password: JSON.parse(row.content).password,
      operateMode: 14,
      order: 6214,
      passwordStartTime: passwordStartTime,
      passwordEndTime: passwordEndTime,
      is: false,
      cardName: row.name + '-' + (content.pzname ? content.pzname : ''),
      roomName: row.roomName
    };
  } else if (row.type == 3) {
    data = {
      imei: resultArr.imei,
      deviceNum: resultArr.deviceNum,
      userTelephone: userTelephone,
      cardId: row.cardId,
      userPassword: userPassword,
      password: JSON.parse(row.content).password,
      operateMode: 11,
      order: 6211,
      passwordStartTime: passwordStartTime,
      passwordEndTime: passwordEndTime,
      is: false,
      cardName: row.name + '-' + (content.pzname ? content.pzname : ''),
      roomName: row.roomName
    };
  } else if (row.type == 4) {
    data = {
      imei: resultArr.imei,
      deviceNum: resultArr.deviceNum,
      userTelephone: userTelephone,
      cardId: row.cardId,
      userPassword: userPassword,
      password: JSON.parse(row.content).password,
      operateMode: 8,
      order: 6208,
      passwordStartTime: passwordStartTime,
      passwordEndTime: passwordEndTime,
      is: false,
      cardName: row.name + '-' + (content.pzname ? content.pzname : ''),
      pzname: content.pzname,
      roomName: row.roomName
    };
  }
  ICINLocker.LDRfCardRegister(data.deviceNum, data.imei, data.userTelephone, data.userPassword, data.password, data
    .passwordStartTime, data.passwordEndTime, data.operateMode, data.order, data.cardName, data.roomName, false, (
    callback) => {
    if (callback.success) {
      content['passwordStartTime'] = data.passwordStartTime
      content['passwordEndTime'] = data.passwordEndTime
      content['cardName'] = data.cardName
      content['roomName'] = data.roomName
      var datafid = {
        cardId: resultArr.cardId,
        deviceNum: resultArr.deviceNum,
        type: row.type,
        imei: resultArr.imei,
        content: JSON.stringify(content), //operateMode:NFC-10、把人员添加到凭证-1
        serial: callback.data.serialNumber,
        startTime: moment(startTime).valueOf() / 1000,
        endTime: moment(endTime).valueOf() / 1000,
      };
      httpPost(datafid, api.addCertificates).then((res) => {
        if (res.success) {
          message({
            type: "success",
            message: "发送成功"
          })
        } else {
          message({
            type: "error",
            message: "发送失败"
          })
        }
      });
      var updatestatus = {
        id: row.id,
        status: 703
      }
      httpPost(updatestatus, api.updateCertificates)
        .then(
          (res3) => {
            message({
              type: "success",
              message: "更新成功"
            })
          });
    } else {
      message({
        type: "error",
        message: callback.msg
      })
    }
  })
}
// 下发凭证
static
modifyPutCarfidzg(resultArr, row, startTime, endTime)
{
  var data = {};
  var userTelephone = JSON.parse(row.content).userTelephone;
  var userPassword = JSON.parse(row.content).userPassword;
  var content = JSON.parse(row.content);
  var passwordEndTime = moment(endTime).valueOf() / 1000;
  var passwordStartTime = moment(startTime).valueOf() / 1000;
  if (row.type == 1) {
    this.getfiId1(row, function (data) {
      if (data.length > 0) {
        var fpid = "";
        fpid = data[0].face.toString(16).length != 2 ? "0" + data[0].face : data[0].face;
        var pwd = JSON.parse(row.content).userPassword
        var cardName = row.name + '-' + content.pzname
        ICINLocker.modifyFingerPrints(resultArr.deviceNum, resultArr.imei, pwd, 3,
          fpid, 0, passwordStartTime, passwordEndTime, cardName, resultArr.roomName, (callback) => {
            if (callback.success) {
              var str1 = JSON.parse(row.content);
              str1.fpTimeId = callback.data.serialNumber;
              str1.passwordStartTime = passwordStartTime;
              str1.passwordEndTime = passwordEndTime;
              str1['order'] = 6217
              str1['operateMode'] = 17
              var updatedata = {
                cardId: resultArr.cardId,
                deviceNum: resultArr.deviceNum,
                type: row.type,
                imei: resultArr.imei,
                content: JSON.stringify(str1),
                serial: callback.data.serialNumber,
                startTime: passwordStartTime,
                endTime: passwordEndTime
              };
              httpPost(updatedata, api.addCertificates)
                .then(
                  (res2) => {
                    message({
                      type: "success",
                      message: "下发成功"
                    })
                  });
              var updatestatus = {
                id: row.id,
                status: 703
              }
              httpPost(updatestatus, api.updateCertificates)
                .then(
                  (res3) => {
                    message({
                      type: "success",
                      message: "更新成功"
                    })
                  });
              message({
                type: "success",
                message: callback.msg
              })
            } else {
              message({
                type: "error",
                message: callback.msg
              })
            }
          })
      } else {
        message({
          type: "error",
          message: "修改失败"
        })
      }
    })
  } else if (row.type == 2) {
    var idcard = ''
    if (content.password.length == 16) {
      idcard = content.password
    } else {
      idcard = dec2hex(content.password);
    }
    var userid = JSON.parse(row.content).userPassword
    if (idcard.length != 16) {
      message({
        type: "error",
        message: "卡格式错误，请重新录入"
      })
      return
    }
    var cardName = row.name + '-' + content.pzname
    ICINLocker.RfCardRegister(resultArr.deviceNum, resultArr.imei, userid, 3, 1, idcard
      .toUpperCase(), 36, passwordStartTime, passwordEndTime, 6214, cardName, resultArr
      .roomName, (callback) => {
      if (callback.success) {
        var str = JSON.parse(row.content)
        str['password'] = idcard.toUpperCase()
        str['order'] = 6214
        str['operateMode'] = 14
        var updatedata = {
          cardId: resultArr.cardId,
          deviceNum: resultArr.deviceNum,
          type: row.type,
          imei: resultArr.imei,
          content: JSON.stringify(str),
          serial: callback.data.serialNumber,
          startTime: passwordStartTime,
          endTime: passwordEndTime
        };
        httpPost(updatedata, this.$api.addCertificates).then((res) => {
          message({
            type: "success",
            message: "下发成功"
          })

        });
        var updatestatus = {
          id: row.id,
          status: 703
        }
        httpPost(updatestatus, api.updateCertificates)
          .then(
            (res3) => {
              message({
                type: "success",
                message: "更新成功"
              })
            });
        message({
          type: "success",
          message: callback.msg
        })
      } else {
        message({
          type: "error",
          message: callback.msg
        })
      }
    })
  } else if (row.type == 3) {
    var nfc = "";
    if (content.password.length == 8) {
      nfc = content.password + '00000000'
    } else if (content.password.length == 16) {
      nfc = content.password
    } else {
      message({
        type: "error",
        message: "卡格式错误，请重新录入"
      })
      return
    }
    var userid = JSON.parse(row.content).userPassword
    // if (nfc.length != 8) {
    //   message({
    //     type: "error",
    //     message: "卡格式错误，请重新录入"
    //   })
    //   return
    // }
    var cardName = row.name + '-' + content.pzname
    ICINLocker.RfCardRegister(resultArr.deviceNum, resultArr.imei, userid, 3, 1, nfc.toUpperCase(),
      50, passwordStartTime, passwordEndTime, 6211, cardName, resultArr.roomName, (
        callback) => {
        if (callback.success) {
          var str = JSON.parse(row.content)
          str['password'] = nfc.toUpperCase()
          str['pzname'] = JSON.parse(row.content).pzname
          str['order'] = 6211
          str['operateMode'] = 11
          var updatedata = {
            cardId: resultArr.cardId,
            deviceNum: resultArr.deviceNum,
            type: row.type,
            imei: resultArr.imei,
            content: JSON.stringify(str),
            serial: callback.data.serialNumber,
            startTime: passwordStartTime,
            endTime: passwordEndTime
          };
          httpPost(updatedata, api.addCertificates).then((res) => {
            message({
              type: "success",
              message: "下发成功"
            })

          });

          var updatestatus = {
            id: row.id,
            status: 703
          }
          httpPost(updatestatus, api.updateCertificates)
            .then(
              (res3) => {
                message({
                  type: "success",
                  message: "更新成功"
                })
              });
          message({
            type: "success",
            message: callback.msg
          })
        } else {
          message({
            type: "error",
            message: callback.msg
          })
        }
      })
  } else if (row.type == 4) {
    var pwd = content.password
    var userid = JSON.parse(row.content).userPassword
    var cardName = row.name + '-' + content.pzname
    ICINLocker.addForeverPassword(resultArr.deviceNum, resultArr.imei, userid, 3, pwd, 255,
      passwordStartTime, passwordEndTime, 6208, cardName, resultArr.roomName, (
        callback) => {
        if (callback.success) {
          var str = JSON.parse(row.content)
          str['password'] = content.password
          str['order'] = 6208
          str['operateMode'] = 8
          var updatedata = {
            cardId: resultArr.cardId,
            deviceNum: resultArr.deviceNum,
            type: row.type,
            imei: resultArr.imei,
            content: JSON.stringify(str),
            serial: callback.data.serialNumber,
            startTime: passwordStartTime,
            endTime: passwordEndTime
          };
          httpPost(updatedata, api.addCertificates).then((res) => {
            message({
              type: "success",
              message: "下发成功"
            })

          });
          var updatestatus = {
            id: row.id,
            status: 703
          }
          httpPost(updatestatus, api.updateCertificates)
            .then(
              (res3) => {
                message({
                  type: "success",
                  message: "更新成功"
                })
              });
          message({
            type: "success",
            message: callback.msg
          })
        } else {
          message({
            type: "error",
            message: callback.msg
          })
        }
      })

  }
}
static
timeTotimeimp(obj)
{
  var year = obj.substr(0, 4)
  var month = obj.substr(4, 2)
  var day = obj.substr(6, 2)
  var hours = obj.substr(8, 2)
  var min = obj.substr(8, 2)
  var miao = obj.substr(10, 2)
  var hm = obj.substr(12, 2)
  var str = year + "-" + month + "-" + day + " " + hours + ":" + min + ":" + miao
  var time = new Date(str)
  var time1 = time.getTime()
  return time1 / 1000;
}
// 格式化时间
static
formatTime(time, key)
{
  var time1 = JSON.stringify(time)
  var text = ''
  if (time1.length == 14) {
    text = moment(this.timeTotimeimp(time1) * 1000).format('YYYY年MM月DD日 HH:mm:ss')
  } else if (time1.length == 13) {
    text = moment(time).format('YYYY年MM月DD日 HH:mm:ss')
  } else if (time1.length == 10) {
    text = moment(time * 1000).format('YYYY年MM月DD日 HH:mm:ss')
  }
  return text;
}
// 去重
static
uniqueArray(array, key)
{
  var result = [array[0]];
  for (var i = 1; i < array.length; i++) {
    var item = array[i];
    var repeat = false;
    for (var j = 0; j < result.length; j++) {
      if (item[key] == result[j][key]) {
        repeat = true;
        break;
      }
    }
    if (!repeat) {
      result.push(item);
    }
  }
  return result;
}
// 生成树形数据结构
static
ztreeToElementTree(data, config)
{
  var id = 'id' // 定义ztree数据存储id（自身的id）的key值，可以自定义但一般都是id、pid这种
  var pid = 'pid' // 定义ztree数据存储pid（父id）的key值
  var children = 'children' // 定义生成的element tree存储子节点的key，可以在element中规定defaultProps: {children: 'children'}
  var idMap = {} // 将原始数据转化为以id为key的map
  var elementTree = [] // 输出的element tree数据
  data.forEach(item => {
    item['value'] = item.id
    item['label'] = item.name
    idMap[item.id] = item
  })
  data.forEach(item => {
    // debugger
    if (idMap[item.pid] != idMap[item.id] && idMap[item.pid]) { // 该item项有爸爸，放到对应的父节点下
      !idMap[item.pid].hasOwnProperty(children) && (idMap[item.pid][children] = [])
      idMap[item.pid][children].push(item)
    } else { // 根节点
      elementTree.push(item)
    }
  });
  return elementTree
}
// 根据选择的父级id，获取所有子级id
static
getChild(nodes, item, arr)
{
  for (let el of nodes) {
    if (el.id === item) {
      arr.push(el.id);
      if (el.children) {
        this.childNodesDeep(el.children, arr);
      }
    } else if (el.children) {
      this.getChild(el.children, item, arr);
    }
  }
  return arr;
}
static
childNodesDeep(nodes, arr)
{
  if (nodes)
    nodes.forEach((ele) => {
      arr.push(ele.id);
      if (ele.children) {
        this.childNodesDeep(ele.children, arr);
      }
    });
}
// 过滤两个数组对象相同id的数据
static
filterObj(arr1, arr2)
{
  let arr3 = arr1.filter(obj => !arr2.some(obj1 => obj1 == obj.id))
  return arr3
}
// 过滤两个数组对象相同id的数据
static
filterObj1(arr1, arr2)
{
  let arr3 = arr1.filter(obj => arr2.some(obj1 => obj1 == obj.id))
  return arr3
}
static
loopDepName(treeData, id, joinStr, result)
{
  let res = []
  const fn = (source) => {
    source.forEach(el => {
      res.push(el)
      el.children && el.children.length > 0 ? fn(el.children) : ""
    })
  }
}
static
statusCode(code)
{
  var str = ''
  switch (code) {
    case 0:
      str = "下发中";//已发送
      break;
    case 1:
      str = "下发成功";
      break;
    case 2:
      str = "下发中";//"未下发";
      break;
    case 3:
      str = "下发失败";
      break;
    case 249:
      str = "未发现用户";
      break;
    case 700:
      str = "下发中";//等待发送
      break;
    case 701:
      str = "下发中";
      break;
    case 702:
      str = "下发失败";//发送失败
      break;
    case 703:
      str = "已作废-执行成功";
      break;
    case 704:
      str = "下发超时";
      break;
    //LD返回错误码
    case 101224:
      str = "系统已锁定";
      break;
    case 101225:
      str = "存储读写错误";
      break;
    case 101226:
      str = "管理员手机号比对失败";
      break;
    case 101227:
      str = "存储空间已满";
      break;
    case 101228:
      str = "本地未检测到该凭证";
      break;
    case 101229:
      str = "参数错误";
      break;
    case 101230:
      str = "绑定失败";
      break;
    case 101240:
      str = "设备未绑定";
      break;
    case 101241:
      str = "设备ID不匹配";
      break;
    case 101242:
      str = "未添加蓝牙密码";
      break;
    case 101243:
      str = "蓝牙密码鉴权失败";
      break;
    case 101244:
      str = "门已反锁";
      break;
    case 101245:
      str = "门已开启";
      break;
    case 101246:
      str = "密码长度异常";
      break;
    case 101247:
      str = "当前用户容量已满";
      break;
    case 101248:
      str = "密码已存在(卡片已存在)";
      break;
    case 101249:
      str = "用户不存在";
      break;
    case 101250:
      str = "用户ID匹配失败";
      break;
    case 101251:
      str = "数据错误";
      break;
    case 101252:
      str = "初始密码比对失败";
      break;
    case 101253:
      str = "凭证ID无效";
      break;
    //ZG返回错误码
    case 201002:
      str = "包格式错误";
      break;
    case 201003:
      str = "密码错误";
      break;
    case 201004:
      str = "网络中断";
      break;
    case 201005:
      str = "用户未登记";
      break;
    case 201006:
      str = "参数错误";
      break;
    case 201007:
      str = "需要鉴权";
      break;
    case 201008:
      str = "无权限";
      break;
    case 201009:
      str = "应答超时";
      break;
    case 201010:
      str = "权限校验错误";
      break;
    case 201011:
      str = "钥匙不存在";
      break;
    case 201012:
      str = "钥匙过期";
      break;
    case 201013:
      str = "钥匙数量已到上限";
      break;
    case 201014:
      str = "钥匙无效";
      break;
    case 201015:
      str = "钥匙已存在";
      break;
    case 201016:
      str = "用户已存在";
      break;
    case 201017:
      str = "密码失效";
      break;
    case 201018:
      str = "无效指令";
      break;
    case 201019:
      str = "门锁时间异常";
      break;
    case 201020:
      str = "门锁NB芯片故障";
      break;
    case 201021:
      str = "门锁无NB芯片";
      break;
    case 201022:
      str = "升级程序校验通过";
      break;
    case 201023:
      str = "升级程序项目不匹配";
      break;
    case 201024:
      str = "升级程序版本太低";
      break;
    case 201025:
      str = "升级程序长度超长";
      break;
    case 201026:
      str = "升级程序启动失败";
      break;
    case 201033:
      str = "升级程序进行中";
      break;
    case 201034:
      str = "升级数据写入错误";
      break;
    case 201035:
      str = "升级数据校验和错误";
      break;
    case 201049:
      str = "到达数目定义上限";
      break;
    case 201050:
      str = "密码已经存在";
      break;
    case 201051:
      str = "禁止删除超管";
      break;
    case 201052:
      str = "门禁卡故障";
      break;
    case 201053:
      str = "远程指纹录入进行中";
      break;
    case 201054:
      str = "远程指纹上次录入未完成";
      break;
    case 201055:
      str = "远程指纹录入后,重复添加该用户";
      break;
    case 201254:
      str = "设备没有被发现";
      break;
    case 201255:
      str = "异常，未知错误";
      break;
    default:
      str = "异常";
      break;
  }
  return str
}
}
