import moment from 'moment';
import storeInfo from '../../store/index'
import router from "../../router";
import jsonp from 'jsonp';
import Veu from 'vue'

//对象、一维数组去重(返回一个新数组)
export const singleArr = (arr, val) => {
    let newArr = arr.concat()
    let len = newArr.length;
    if (val) {
        for (let i = 0; i < len; i++) {
            for (let j = i + 1; j < len; j++) {
                if (newArr[i][val] == newArr[j][val]) {
                    newArr.splice(j, 1);
                    len--;
                    j--;
                }
            }
        }
    } else {
        for (let i = 0; i < len; i++) {
            for (let j = i + 1; j < len; j++) {
                if (newArr[i] == newArr[j]) {
                    newArr.splice(j, 1);
                    len--;
                    j--;
                }
            }
        }
    }

    return newArr;
}

//删除关闭详情的页面
export const closedDetail = (url, goToUrl) => {
    if (goToUrl) {
        window.sessionStorage.setItem('activeItem', goToUrl)
        window.sessionStorage.setItem('activeKey', goToUrl)
        storeInfo.commit('changeActKey', goToUrl)
        router.push(goToUrl)
    }
}

//判断对象values是否为空 并返回不为空对象
export const isEmptyParams = (obj) => {
    let obje = {}
    Object.assign(obje, obj)
    for (let key in obje) {
        if (obje[key] === '' || typeof obje[key] === 'undefined' || obje[key] === null || obje[key].length == 0) {
            delete obje[key]
        }
    }
    return obje
}

//数组转为树形结构
// toTree(数组，父id,父id属性key, id当前节点id key)
export const toTree = (list, parId, pId, id) => {
    let len = list.length

    function loop(parId) {
        let res = [];
        for (let i = 0; i < len; i++) {
            let item = list[i]
            if (item[pId] == parId) {
                item.children = loop(item[id])
                res.push(item)
            }
        }
        return res
    }

    return loop(parId)
}

//树形数据转数组
export const treeToArray = (source) => {
    let res = []
    const fn = (source) => {
        source.forEach(el => {
            res.push(el)
            el.children && el.children.length > 0 ? fn(el.children) : ""
        })
    }
    return res
}

//删除树状结构数据中空children
export const removeEmptyChildren = (data) => {
    data.forEach(item => {
        if (item.children === null || item.children.length === 0) {
            delete item.children
        } else {
            removeEmptyChildren(item.children)
        }
    })
    return data
}

//修改时间格式
export const timeFormat = (time, format = 'YYYY-MM-DD') => {
    let atime = moment(time).format(format)
    return atime
}

/**
 * 非空判断 已挂载到原型上$isNot
 * 解决Vue Template模板中无法使用可选链的问题
 * eg:
 * let ces = {
                    data: {
                        data1: {
                            name: '测试'
                        }
                    }
                }
 let b = this.$isNot(ces, 'data', 'data1', 'name') //测试
 {{$isNot(ces, 'data', 'data1', 'name')}} //测试
 */
// export const optionalChaining = (obj, ...rest) => {
//     let tmp = obj;
//     for (let key in rest) {
//         let name = rest[key];
//         tmp = tmp?.[name]; //es11可选链
//     }
//     return tmp ?? "未知";
// };


// 校验手机号
export const checkPhone = (rule, value, callback) => {
    if (value == '' || value == undefined) {
        callback();
    }
    let ckPhone = /^1(?:3[0-9]|4[5-9]|5[0-9]|6[12456]|7[0-8]|8[0-9]|9[0-9])[0-9]{8}$/;
    let tell = /^0\d{2,3}-?\d{7,8}$/;
    if (ckPhone.test(value) || tell.test(value)) {
        callback()
    } else {
        callback(new Error('请输入正确的手机号或座机'));
    }
}

//根据枚举标识获取下拉数据
export const getEnumByFlag = (enumFlag) => {
        let result = []
        let enumSessionStorange = JSON.parse(window.sessionStorage.getItem('allEnum'))
        if (enumSessionStorange && enumFlag) {
            for (let obj in enumSessionStorange) {
                if (obj == enumFlag) {
                    result = enumSessionStorange[obj]
                }
            }
    }
    return result
}

//读取cookie
export const getCookie = name => {
    let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
};

//判断一对象是否是空白
export const isBlank = obj => {
    if (obj == null || obj == undefined || obj == '' || obj == ' ') {
        return true;
    }
    if (obj === null || obj === undefined || obj === '' || obj === ' ') {
        return true;
    }
    if (obj == {} || obj == []) {
        return true
    }
    return false;
};
export const isNotBlank = obj => {
    return !isBlank(obj)
}

/**
 * 根据身份证读卡器读取基本信息
 */

export const GetUserInfoByCardDevice = () => {
    let {protocol} = window.location;
    let url = protocol === "https:" ? "https://localhost:9199/api/ReadMsg" : "http://localhost:8989/api/ReadMsg";
    return new Promise((resolve) => {
        // res {code: "-1", retcode: "0x41", retmsg: "读居民身份证操作失败", errmsg: ""}
        jsonp(url, {timeout: 30000}, (err, data) => {
            if (!err) {
                if (data.cardno) {
                    resolve(data);
                } else {
                    let reg = /\d+/g;
                    let messageInfo = data.message;
                    let datault = reg.exec(messageInfo);
                    let status = datault && datault[0];
                    if (/^[45]\d+/.test(status)) {
                        window.parent.parentLibInfo.Antd.message.error('设备连接失败');
                    } else {
                        window.parent.parentLibInfo.Antd.message.error(data.retmsg);
                    }

                }
            } else if (err && err.message === 'Timeout') {
                window.parent.parentLibInfo.Antd.message.error('设备连接失败');
            }
        });
    })
};

