import { httpGet, httpPost } from "../api";
import { api } from "../api/all";
import ICINLocker from "../utils/equipment.js"
import utils from "../utils/util.js"
import moment from 'moment'
import {
    message
} from './resetMessage';
/**
 * @param {Function} fn 防抖函数
 * @param {Number} delay 延迟时间
 */
export function debounce(fn, delay) {
    var timer;
    return function() {
        var context = this;
        var args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function() {
            fn.apply(context, args);
        }, delay);
    };
}
export function compare(prop,align){
	return function(a,b){
        var value1=a[prop];
        var value2=b[prop];
        if(align=="positive"){//正序
            return new Date(value1)-new Date(value2);
        }else if(align=="inverted"){//倒序
            return new Date(value2)-new Date(value1);
        }
	}
}
// zTree传参
export function getlist(id) {
    console.log(1111);
    // this.$parent.fatherMethod(id);
}
export function setRemoveTitle(treeId, treeNode) {
    console.log(treeNode)
    return treeNode.isParent ? "删除父节点" : "删除叶子节点";
}
/**
 * @param {date} time 需要转换的时间
 * @param {String} fmt 需要转换的格式 如 yyyy-MM-dd、yyyy-MM-dd HH:mm:ss
 */
export function formatTime(time, fmt) {
    if (!time) return '';
    else {
        const date = new Date(time);
        const o = {
            'M+': date.getMonth() + 1,
            'd+': date.getDate(),
            'H+': date.getHours(),
            'm+': date.getMinutes(),
            's+': date.getSeconds(),
            'q+': Math.floor((date.getMonth() + 3) / 3),
            S: date.getMilliseconds(),
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(
                RegExp.$1,
                (date.getFullYear() + '').substr(4 - RegExp.$1.length)
            );
        for (const k in o) {
            if (new RegExp('(' + k + ')').test(fmt)) {
                fmt = fmt.replace(
                    RegExp.$1,
                    RegExp.$1.length === 1 ?
                    o[k] :
                    ('00' + o[k]).substr(('' + o[k]).length)
                );
            }
        }
        return fmt;
    }
}



// 标准时间转日期
export function palindrome(str) {
    // 先后去除空格和非数字字母的字符
    var newStr = str.replace(/\s/g, "").replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
    //判断翻转后的字符串是否与原字符串相等
    console.log(newStr, '------')
    var reverStr = newStr.split("").reverse().join("");
    if (reverStr === newStr) {
        return true;
    } else {
        return false;
    }
}

export function timestampToTime(timestamp) {
    var chinaStandard = timestamp;
    var date = new Date(chinaStandard);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m.toString();
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    var minute = date.getMinutes();
    h = h < 10 ? ('0' + h) : h;
    minute = minute < 10 ? ('0' + minute) : minute;
    var second = date.getSeconds();
    second = second < 10 ? ('0' + second) : second;
    var Time = y + m + d + h + minute + second;
    if (Time.length < 14) {
        var str = ''
        for (var i = Time.length; i < 14; i++) {
            str += '0'
        }
        Time += str
    }
    return Time;
}

//日期转为UTC国际时间  format the date string from webservice to UTC time;
export function toUTCtime(dateStr) {
    return new Date(dateStr).toISOString()
}

// 获取当前时间
export function getNowTime() {
    let dateTime
    let yy = new Date().getFullYear()
    let mm = new Date().getMonth() + 1
    let dd = new Date().getDate()
    let hh = new Date().getHours()
    let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() :
        new Date().getMinutes()
    let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() :
        new Date().getSeconds()
    dateTime = yy + '-' + mm + '-' + dd + ' ' + '00' + ':' + '00' + ':' + '00'
    return dateTime
}

export function writeCurrentDate(n) {
    var now = new Date();
    var time = now.setTime(now.getTime() - n * 24 * 60 * 60 * 1000);
    let date = new Date(parseInt(time))
    let y = date.getFullYear()
    let MM = date.getMonth() + 1
    MM = MM < 10 ? ('0' + MM) : MM
    let d = date.getDate()
    d = d < 10 ? ('0' + d) : d
    let h = date.getHours()
    h = h < 10 ? ('0' + h) : h
    let m = date.getMinutes()
    m = m < 10 ? ('0' + m) : m
    let s = date.getSeconds()
    s = s < 10 ? ('0' + s) : s
    return y + '-' + MM + '-' + d + ' ' + '00' + ':' + '00' + ':' + '00'
}
export function writeCurrentDate1(n) {
    var now = new Date();
    var time = now.setTime(now.getTime() - n * 24 * 60 * 60 * 1000);
    return time
}

// 树形数据转化
export function ztreeToElementTree(data, config) {
    var id = config.id || 'id' // 定义ztree数据存储id（自身的id）的key值，可以自定义但一般都是id、pid这种
    var pid = config.pid || 'pid' // 定义ztree数据存储pid（父id）的key值
    var children = config.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)
            idMap[item.pid][children].sort((a,b) => { return a.index - b.index })
        } else { // 根节点
            elementTree.push(item)
        }
    });
    return elementTree
}
// 树形数据转化2
export function ztreeToElementTree2(data, config) {
    var id = config.id || 'id' // 定义ztree数据存储id（自身的id）的key值，可以自定义但一般都是id、pid这种
    var pid = config.pid || 'pid' // 定义ztree数据存储pid（父id）的key值
    var children = config.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
        // if(item.layout){
        //   item['disabled']=false
        // }else{
        //   item['disabled']=true
        // }
        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
}

export function recursion(arr, newArr = []) {
    arr.forEach(item => {
        typeof item === 'object' && item.id && newArr.push(item.id) // 先判断当前项是否是对象。 当前项是否存在你想要的数据。都符合，把数据push到新数组里
        item.children && item.children instanceof Array && recursion(item.children, newArr) // 当前项是否还有子节点，子节是否是数组, 如果是继续调用自己。再循环遍历一次.
    })
    return newArr
}

// 树形数据转化2
export function ztreeToElementTree3(data, config) {
    var id = config.id || 'id' // 定义ztree数据存储id（自身的id）的key值，可以自定义但一般都是id、pid这种
    var pid = config.pid || 'pid' // 定义ztree数据存储pid（父id）的key值
    var children = config.children || 'children' // 定义生成的element tree存储子节点的key，可以在element中规定defaultProps: {children: 'children'}
    var idMap = {} // 将原始数据转化为以id为key的map
    var elementTree = [] // 输出的element tree数据
    data.forEach(item => {
        // if(item.layout){
        //   item['disabled']=false
        // }else{
        //   item['disabled']=true
        // }
        idMap[item.id] = item
    })
    data.forEach(item => {
        // debugger
        idMap[item.pid]['label'] = item.name
        idMap[item.pid]['value'] = item.id
        var num = idMap[item.id] - idMap[item.pid]
        if ((idMap[item.pid] != idMap[item.id]) && num != 0) { // 该item项有爸爸，放到对应的父节点下
            !idMap[item.pid].hasOwnProperty(children) && (idMap[item.pid][children] = [])
            item['label'] = item.name
            item['value'] = item.id
            idMap[item.pid][children].push(item)
        } else { // 根节点
            elementTree.push(item)
        }
    });
    return elementTree
}

export function get_header_row(sheet) {
    const headers = [];
    /* sheet['!ref']表示所有单元格的范围，例如从A1到F8则记录为 A1:F8*/
    const range = XLSX.utils.decode_range(sheet['!ref']);
    let C, R = range.s.r; /* 从第一行开始 */
    /* 按列进行数据遍历 */
    for (C = range.s.c; C <= range.e.c; ++C) {
        /* 查找第一行中的单元格 */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]

        let hdr = "UNKNOWN " + C; // <-- 进行默认值设置
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell);

        headers.push(hdr);
    }
    return headers;
}
export function processFile(file, fileList) {
    const reader = new FileReader();
    reader.onload = (e) => {
        /* 解析数据 */
        const bstr = e.target.result;
        const wb = XLSX.read(bstr, { type: 'binary' });
        /* 获取文件的第一个工作表（WorkSheet） */
        const wsname = wb.SheetNames[0];
        const ws = wb.Sheets[wsname];
        /* 数组转换 */
        const data = XLSX.utils.sheet_to_json(ws, { header: 1 });
        /* 进行表格数据更新 */
        this.tableData = data;
        /* 进行表格表头数据更新 */
        this.cols = getHeaderRow(ws);
    };
    reader.readAsBinaryString(file.raw);
    console.log(reader.readAsBinaryString(file.raw))
}



export function 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;
}
export function uniqueArray1(array, key) {
    var result = [array[0]];
    for (var i = 1; i < array.length; i++) {
        array[i]['label'] = array[i].name
        array[i]['value'] = array[i].id
        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;
}
// 合并
export function hbFun(arrayName) {
    var idArray = [];
    var newAarray = [];
    arrayName.forEach(function(ele, i) {

        if (idArray.indexOf(arrayName[i].name) === -1) {

            newAarray.push({
                'openType': arrayName[i].openType,
                'name': arrayName[i].name,
                'total': arrayName[i].total,
                'time': moment().format('YYYY-MM-DD')
            })
            idArray.push(arrayName[i].name);
        } else {
            newAarray.forEach(function(dom, k) {
                if (newAarray[k].name == arrayName[i].name) { //把具有相同id的course值进行合并
                    // var num=parseInt(newAarray[k].total)
                    // var num1=parseInt(arrayName[i].total)
                    // newAarray[k].total=num+num1
                }
            })

        }
    })

    console.log(newAarray)
}
// 进制转换
export function dec2hex(str) {
    var dec = str.toString().split(""),
        sum = [],
        hex = [],
        i,
        s;
    while (dec.length) {
        s = 1 * dec.shift();
        for (i = 0; s || i < sum.length; i++) {
            s += (sum[i] || 0) * 10;
            sum[i] = s % 16;
            s = (s - sum[i]) / 16;
        }
    }
    while (sum.length) {
        hex.push(sum.pop().toString(16));
    }
    var card = hex.join("")
    var zero = '00000000';
    var tmp = 8 - card.length;
    var clength = zero.substring(0, tmp) + card
    return clength;
}
export function group(array, len) {
    let index = 0
    let newarray = []
    while (index < array.length) {
        newarray.push(array.slice(index, index += len))
    }
    return newarray
}

export function delArrVal(arr, val) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] == val) {
            arr.splice(i, 1)
            i--;
        }
    }
    return arr;
}

export function isContained(a, b) {
    if (!(a instanceof Array) || !(b instanceof Array)) return false;
    if (a.length < b.length) return false;
    var aStr = a.toString();
    for (var i = 0, len = b.length; i < len; i++) {
        if (aStr.indexOf(b[i]) == -1) return false;
    }
    return true;
}

export function duplicateRemoval(obj) {
    var uniques = [];
    var stringify = {};
    for (var i = 0; i < obj.length; i++) {
        var keys = Object.keys(obj[i]);
        keys.sort(function(a, b) {
            return (Number(a) - Number(b));
        });
        var str = '';
        for (var j = 0; j < keys.length; j++) {
            str += JSON.stringify(keys[j]);
            str += JSON.stringify(obj[i][keys[j]]);
        }
        if (!stringify.hasOwnProperty(str)) {
            uniques.push(obj[i]);
            stringify[str] = true;
        }
    }
    uniques = uniques;
    return uniques;
}

export function getcurrentTime() {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    if (month < 10) {
        month = "0" + month;
    }
    if (day < 10) {
        day = "0" + day;
    }
    var nowDate = year + "/" + month + "/" + day + ' 08:00:00';
    var str = new Date(nowDate).getTime()
    return new Date(str);
}


export function getcurrentTime1(y) {
    var date = new Date();
    var year = date.getFullYear() + y;
    var month = date.getMonth() + 1;
    var day = date.getDate();
    if (month < 10) {
        month = "0" + month;
    }
    if (day < 10) {
        day = "0" + day;
    }
    var nowDate = year + "/" + month + "/" + day + ' 08:00:00';
    var str = new Date(nowDate).getTime()
    return new Date(str);
}

export function 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;
}


export function reverse(text) {
    var aaa = text;
    var bbb = [...aaa];
    var ccc = aaa.split('');
    var a, b;
    var aIndex = 0;
    var bIndex = 1;
    var arr = [];

    bbb.forEach((str, index) => {
        if (index % 2 === 0) {
            a = str;
            aIndex += 1

        } else {
            b = str
            bIndex += 1
        }
        if (a && b && (bIndex - aIndex === 1)) {
            arr.push(a + b)
        }
    });
    var str = arr.reverse().join('')
    console.log(str)
    return str
}


export function backDevice(row, callback) {
    var data = {
        q: JSON.stringify({ imei: row.imei })
    }
    httpPost(data, api.getDeviceItems).then(res => {
        callback(res)
    })
}
export function deleteZgVoucher(row, callback) {
    if (row.type == 1) {
        getfiId1(row, function(data) {
          console.log(data)
            if (data.length > 0) {
                    var _cardName=JSON.parse(row.content).username+'-'+JSON.parse(row.content).pzname
                    var _roomName=data[0].roomName
                    var startTime=JSON.stringify(row.startTime)
                    var endTime=JSON.stringify(row.endTime)
                    var _startTime=row.startTime,_endTime=row.endTime
                    if(startTime.length==13){
                      _startTime=row.startTime/1000
                    }
                    if(endTime.length==13){
                      _endTime=row.endTime/1000
                    }
                ICINLocker.delFingerPrints(row.deviceNum, row.imei, JSON.parse(row.content).userPassword, 2, data[0].face, 0, _startTime, _endTime,_cardName, _roomName, (callback1) => {
                    callback(callback1)
                })
            } else {
                message({
                    type: "error",
                    message: "还未下发"
                })
            }
        })
    } else if (row.type == 2) {
        getfiId1(row, function(data) {
            if (data.length > 0) {
                    var _cardName=JSON.parse(row.content).username+'-'+JSON.parse(row.content).pzname
                    var _roomName=data[0].roomName
                    var startTime=JSON.stringify(row.startTime)
                    var endTime=JSON.stringify(row.endTime)
                    var _startTime=row.startTime,_endTime=row.endTime
                    if(startTime.length==13){
                      _startTime=row.startTime/1000
                    }
                    if(endTime.length==13){
                      _endTime=row.endTime/1000
                    }
                ICINLocker.delCardRegister(row.deviceNum, row.imei, JSON.parse(row.content).userPassword, 2, 1, JSON.parse(row.content).password, 36, _startTime, _endTime, 6212, data[0].face,_cardName, _roomName, (callback1) => {
                    callback(callback1)
                })
            } else {
                message({
                    type: "error",
                    message: "还未下发"
                })
            }
        })
    } else if (row.type == 3) {
        getfiId1(row, function(data) {
            if (data.length > 0) {
                    var _cardName=JSON.parse(row.content).username+'-'+JSON.parse(row.content).pzname
                    var _roomName=data[0].roomName
                    var startTime=JSON.stringify(row.startTime)
                    var endTime=JSON.stringify(row.endTime)
                    var _startTime=row.startTime,_endTime=row.endTime
                    if(startTime.length==13){
                      _startTime=row.startTime/1000
                    }
                    if(endTime.length==13){
                      _endTime=row.endTime/1000
                    }
                ICINLocker.delCardRegister(row.deviceNum, row.imei, JSON.parse(row.content).userPassword, 2, 1, JSON.parse(row.content).password, 50,  _startTime, _endTime, 6212, data[0].face,_cardName, _roomName, (callback1) => {
                    callback(callback1)
                })
            } else {
                message({
                    type: "error",
                    message: "还未下发"
                })
            }
        })
    } else if (row.type == 4) {
        getfiId1(row, function(data) {
            if (data.length > 0) {
                    var _cardName=JSON.parse(row.content).username+'-'+JSON.parse(row.content).pzname
                    var _roomName=data[0].roomName
                    var startTime=JSON.stringify(row.startTime)
                    var endTime=JSON.stringify(row.endTime)
                    var _startTime=row.startTime,_endTime=row.endTime
                    if(startTime.length==13){
                      _startTime=row.startTime/1000
                    }
                    if(endTime.length==13){
                      _endTime=row.endTime/1000
                    }
                ICINLocker.delForeverPassword(row.deviceNum, row.imei, JSON.parse(row.content).userPassword, 2, JSON.parse(row.content).password, 255,  _startTime, _endTime, 6209, data[0].face,_cardName, _roomName, (callback1) => {
                    callback(callback1)
                })
            } else {
                message({
                    type: "error",
                    message: "还未下发"
                })
            }
        })
    }
}

export function deleteVoucher(row, callback) {
    var str = {};
    var _cardName=JSON.parse(row.content).username+'-'+JSON.parse(row.content).pzname
    if (row.type == 1) {
        getfiId(row, function(data) {
            if (data.length > 0) {
                var fpid = "";
                if (data[0].face) {
                    fpid = data[0].face.toString(16);
                    if (fpid.length != 2) {
                        fpid = "0" + fpid;
                    }
                } else {
                    if (data[0].face == 0) {
                        fpid = data[0].face.toString(16);
                        fpid = "0" + fpid;
                    }
                }
                str = {
                    imei: row.imei,
                    deviceNum: row.deviceNum,
                    userTelephone: JSON.parse(row.content).userTelephone,
                    operateMode: 18,
                    order: 6218,
                    password: fpid,
                    userPassword: JSON.parse(row.content).userPassword,
                    is: false,
                    passwordStartTime: JSON.parse(row.content).passwordStartTime,
                    passwordEndTime: JSON.parse(row.content).passwordEndTime,
                    cardName:_cardName,
                    roomName:data[0].roomName
                };
                httpPost(str, api.getDeviceOperateUserInfo).then((res1) => {
                    callback(res1)
                });
            } else {
                message({
                    type: "error",
                    message: "该凭还未下发"
                })
            }
        });
        return false;
    } else if (row.type == 2) {
        str = {
            cardId: row.cardId,
            imei: row.imei,
            deviceNum: row.deviceNum,
            userTelephone: JSON.parse(row.content).userTelephone,
            userPassword: JSON.parse(row.content).userPassword,
            operateMode: 13,
            order: 6213,
            password: JSON.parse(row.content).password,
            passwordStartTime: "20210813010101",
            passwordEndTime: "20680813010101",
            is: false,
            cardName:_cardName,
        };
    } else if (row.type == 3) {
        str = {
            cardId: row.cardId,
            imei: row.imei,
            deviceNum: row.deviceNum,
            userTelephone: JSON.parse(row.content).userTelephone,
            operateMode: 12,
            order: 6212,
            userPassword: JSON.parse(row.content).userPassword,
            is: false,
            passwordStartTime: "20210813010101",
            passwordEndTime: "20680813010101",
            cardName:_cardName,
        };
    } else if (row.type == 4) {
        str = {
            cardId: row.cardId,
            imei: row.imei,
            deviceNum: row.deviceNum,
            userTelephone: JSON.parse(row.content).userTelephone,
            operateMode: 9,
            order: 6209,
            userPassword: JSON.parse(row.content).userPassword,
            password: JSON.parse(row.content).password,
            is: false,
            passwordStartTime: "20210813010101",
            passwordEndTime: "20680813010101",
            cardName:_cardName,
        };
    }
    httpPost(str, api.getDeviceOperateUserInfo).then((res1) => {
        callback(res1)
    })
}
// 获取指纹id
export function getfiId(row, callback) {
    var content = JSON.parse(row.content);
    var data = {
        q: JSON.stringify({
            fpTimeId: content.fpTimeId,
        }),
        pageNum: 1,
        pageSize: 10,
    };
    httpPost(data, api.getDeviceResult).then((res) => {
		let datalist=utils.zlib_unzip(res.data)
        callback(datalist);
    });
}
export function getfiId1(row, callback) {
    var data = {
        q: JSON.stringify({
            serial: row.serial,
        }),
        pageNum: 1,
        pageSize: 10,
    };
    httpPost(data, api.getDeviceResult).then((res) => {
		let datalist=utils.zlib_unzip(res.data)
        callback(datalist);
    });
}

export function modifyCraiAllFun(row, modifyvalue2, certificatesContent, callback) {
    var data = {
        q: JSON.stringify({
            imei: row.imei
        }),
        pageNum: 1,
        pageSize: 10,
    };
    httpPost(data, api.getDeviceItems).then((res) => {
        if (res.data.list.length > 0) {
            if (res.data.list[0].manufactureId == 201 || res.data.list[0].manufactureId == 221) {
                var startTime = new Date(modifyvalue2[0]).getTime() / 1000
                var endTime = new Date(modifyvalue2[1]).getTime() / 1000
                if (row.type == 1) {
                    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
                            ICINLocker.modifyFingerPrints(row.deviceNum, row.imei, pwd, 3, fpid, 0, startTime, endTime, (callback1) => {
                                callback(callback1)
                            })
                        } else {
                            message({
                                type: "error",
                                message: "修改失败"
                            })
                        }
                    })
                } else if (row.type == 2) {
                    var idcard = JSON.parse(row.content).password
                    var userid = JSON.parse(row.content).userPassword
                    if (idcard.length != 16) {
                        message({
                            type: "error",
                            message: "卡格式错误，请重新录入"
                        })
                        return
                    }
                    ICINLocker.RfCardRegister(row.deviceNum, row.imei, userid, 3, 1, idcard.toUpperCase(), 36, startTime, endTime, 6211, (callback1) => {
                        callback(callback1)
                    })
                } else if (row.type == 3) {
                    var nfc = JSON.parse(row.content).password
                    var userid = JSON.parse(row.content).userPassword
                    if (nfc.length != 8) {
                        message({
                            type: "error",
                            message: "卡格式错误，请重新录入"
                        })
                        return
                    }
                    ICINLocker.RfCardRegister(row.deviceNum, row.imei, userid, 3, 1, nfc.toUpperCase(), 50, startTime, endTime, 6211, (callback1) => {
                        callback(callback1)
                    })
                } else if (row.type == 4) {
                    var pwd = JSON.parse(row.content).password
                    var userid = JSON.parse(row.content).userPassword
                    ICINLocker.addForeverPassword(row.deviceNum, row.imei, userid, 3, pwd, 255, startTime, endTime, 6208, (callback1) => {
                        callback(callback1)
                    })
                }
            } else if (res.data.list[0].manufactureId == 101) {
                var content = JSON.parse(row.content);
                var userTelephone = content.userTelephone;
                var userPassword = content.userPassword;
                var data = {};
                if (row.type == 1) {
                    this.getfiId(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.toString(16);
                            var str = {
                                imei: row.imei,
                                deviceNum: row.deviceNum,
                                pzname: certificatesContent.pzname,
                                cardId: row.cardId,
                                password: fpid,
                                operateMode: 17,
                                order: 6217,
                                userPassword: userPassword,
                                userTelephone: userTelephone,
                                passwordStartTime: timestampToTime(modifyvalue2[0]),
                                passwordEndTime: timestampToTime(modifyvalue2[1]),
                                is: false,
                            };
                            httpPost(str, that.$api.getDeviceOperateUserInfo).then((res1) => {
                                callback(res1)
                            });
                        }
                    });
                    return false;
                } else if (row.type == 2) {
                    var arr2 = content.password
                    data = {
                        imei: row.imei,
                        deviceNum: row.deviceNum,
                        userTelephone: userTelephone,
                        pzname: certificatesContent.pzname,
                        cardId: row.cardId,
                        userPassword: userPassword,
                        password: arr2.toUpperCase(),
                        operateMode: 14,
                        order: 6214,
                        passwordStartTime: timestampToTime(modifyvalue2[0]),
                        passwordEndTime: timestampToTime(modifyvalue2[1]),
                        is: false,
                    };
                    if (arr2 == "") {
                        message({
                            type: "error",
                            message: "请填写完整信息"
                        })
                        return false;
                    }
                } else if (row.type == 3) {
                    var arr4 = content.password;
                    data = {
                        imei: row.imei,
                        deviceNum: row.deviceNum,
                        userTelephone: userTelephone,
                        pzname: certificatesContent.pzname,
                        cardId: row.cardId,
                        userPassword: userPassword,
                        password: arr4.toUpperCase(),
                        operateMode: 11,
                        order: 6211,
                        passwordStartTime: timestampToTime(modifyvalue2[0]),
                        passwordEndTime: timestampToTime(modifyvalue2[1]),
                        is: false,
                    };
                    if (arr4 == "") {
                        message({
                            type: "error",
                            message: "请填写完整信息"
                        })
                        return false;
                    }
                } else if (row.type == 4) {
                    data = {
                        imei: row.imei,
                        deviceNum: row.deviceNum,
                        userTelephone: userTelephone,
                        pzname: certificatesContent.pzname,
                        cardId: row.cardId,
                        userPassword: userPassword,
                        password: content.password,
                        operateMode: 8,
                        order: 6208,
                        passwordStartTime: timestampToTime(modifyvalue2[0]),
                        passwordEndTime: timestampToTime(modifyvalue2[1]),
                        is: false,
                    };
                    if (content.password == "") {
                        message({
                            type: "error",
                            message: "请填写完整信息"
                        })
                        return false;
                    }
                }
                httpPost(data, api.getDeviceOperateUserInfo).then((res) => {
                    callback(res1)
                });
            }
        } else {
            message({
                type: "error",
                message: "未找到该凭证对应门锁"
            })
        }
    })
}


// 判断字段是否有效
export function paramsValidate(obj) {
  var array = {}
  for (let key in obj) {
    if (obj[key]) {
      array[key] = obj[key]
    }
  }
  return array
}


//金额小写转大写
export function smallToBig(money = '') {
  // 汉字的数字
  const cnNums = ['零', '壹','贰','叁','肆','伍', '陆','柒','捌','玖',]
  // 基本单位
  const cnIntRadice = ['', '拾', '佰', '仟']
  // 对应整数部分扩展单位
  const cnIntUnits = ['', '万', '亿', '兆']
  // 对应小数部分单位
  const cnDecUnits = ['角', '分']
  // 整数金额时后面跟的字符
  const cnInteger = '整'
  // 整型完以后的单位
  const cnIntLast = '元'
  // 最大处理的数字
  const maxNum = 9999999999999999.99
  // 金额整数部分
  let integerNum
  // 金额小数部分
  let decimalNum
  // 输出的中文金额字符串
  let chineseStr = ''
  // 分离金额后用的数组，预定义
  let parts
  if (money === '') {
    return ''
  }
  money = parseFloat(money)
  if (money >= maxNum) {
    // 超出最大处理数字
    return ''
  }
  if (money === 0) {
    chineseStr = cnNums[0] + cnIntLast + cnInteger
    return chineseStr
  }
  // 转换为字符串
  money = money.toString()
  if (money.indexOf('.') === -1) {
    integerNum = money

    decimalNum = ''
  } else {
    parts = money.split('.')
    integerNum = parts[0]
    decimalNum = parts[1].substr(0, 4)
  }
  // 获取整型部分转换
  if (parseInt(integerNum, 10) > 0) {
    let zeroCount = 0
    const IntLen = integerNum.length
    for (let i = 0; i < IntLen; i++) {
      const n = integerNum.substr(i, 1)
      const p = IntLen - i - 1
      const q = p / 4
      const m = p % 4
      if (n === '0') {
        zeroCount++
      } else {
        if (zeroCount > 0) {
          chineseStr += cnNums[0]
        }
        // 归零
        zeroCount = 0
        //alert(cnNums[parseInt(n)])
        chineseStr += cnNums[parseInt(n)] + cnIntRadice[m]
      }
      if (m === 0 && zeroCount < 4) {
        chineseStr += cnIntUnits[q]
      }
    }
    chineseStr += cnIntLast
  }
  // 小数部分
  if (decimalNum !== '') {
    const decLen = decimalNum.length
    for (let i = 0; i < decLen; i++) {
      const n = decimalNum.substr(i, 1)
      if (n !== '0') {
        chineseStr += cnNums[Number(n)] + cnDecUnits[i]
      }
    }
  }
  if (chineseStr === '') {
    chineseStr += cnNums[0] + cnIntLast + cnInteger
  } else if (decimalNum === '') {
    chineseStr += cnInteger
  }
  return chineseStr
}
