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
}

// 校验手机号
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('设备连接失败');
            }
        });
    })
};

/**
 * 区域编码转换为控件需要的格式
 * @param areaCode
 * @returns {string[]}
 */

export function areCodeTrans(areaCode) {
    let areaCodeList = []
    if (!areaCode) {
        return areaCodeList;
    }
    let fullZero = process.env.VUE_APP_AREA_CODE_FULL_ZERO;
    if (fullZero == 'true') {
        //末尾填充0实现
        return areCodeTrans2(areaCode);
    }
    areaCode = areaCode.replaceAll("0000000000", "");
    areaCode = areaCode.replaceAll("00000000", "");
    areaCode = areaCode.replaceAll("000000", "");
    areaCode = areaCode.replaceAll("000", "");
    //末尾不填充0实现
    if (areaCode.length >= 2) {
        areaCodeList.push(areaCode.substring(0, 2))
    }
    if (areaCode.length >= 4) {
        areaCodeList.push(areaCode.substring(0, 4) + "00000000")
    }
    if (areaCode.length >= 6) {
        areaCodeList.push(areaCode.substring(0, 6) + "000000")
    }
    if (areaCode.length >= 9) {
        areaCodeList.push(areaCode.substring(0, 9) + "000")
    }
    if (areaCode.length >= 12) {
        areaCodeList.push(areaCode)
    }
    return areaCodeList
}

//

function areCodeTrans2(areaCode) {
    //let areaCode = "140311103204";
    let areaCodeList = []
    if (!areaCode) {
        return areaCodeList;
    }
    areaCodeList.push(areaCode.substring(0, 2))
    if (areaCode.length === 2) {
        return areaCodeList;
    }
    areaCodeList.push(areaCode.substring(0, 4) + "00000000")
    if (areaCode.substring(4, 6) == "00") {
        return areaCodeList
    }
    areaCodeList.push(areaCode.substring(0, 6) + "000000")
    if (areaCode.substring(6, 9) == "000") {
        return areaCodeList
    }
    areaCodeList.push(areaCode.substring(0, 9) + "000")
    if (areaCode.substring(9, 12) == "000") {
        return areaCodeList
    }
    areaCodeList.push(areaCode)
    return areaCodeList
}
