// 公共方法
import {
    Modal
} from 'antd';
import * as CryptoJS from 'crypto-js'; // ase加密
import {
    createHashHistory
} from 'history'; // 如果是hash路由
import {
    $http
} from 'containers/config/https';
import fetchJsonp from 'fetch-jsonp';

import {
    kValueA
} from 'containers/config/kValue/kValueA.js';
import {
    kValueB
} from 'containers/config/kValue/kValueB.js';
import {
    kValueC
} from 'containers/config/kValue/kValueC.js';
import {
    kValueD
} from 'containers/config/kValue/kValueD.js';
import {
    kValueE
} from 'containers/config/kValue/kValueE.js';
import {
    kValueF
} from 'containers/config/kValue/kValueF.js';
import {
    kValueG
} from 'containers/config/kValue/kValueG.js';
import {
    kValueH
} from 'containers/config/kValue/kValueH.js';

import {
    vValueA
} from 'containers/config/vValue/vValueA.js';
import {
    vValueB
} from 'containers/config/vValue/vValueB.js';
import {
    vValueC
} from 'containers/config/vValue/vValueC.js';
import {
    vValueD
} from 'containers/config/vValue/vValueD.js';
import {
    vValueE
} from 'containers/config/vValue/vValueE.js';
import {
    vValueF
} from 'containers/config/vValue/vValueF.js';
import {
    vValueG
} from 'containers/config/vValue/vValueG.js';
import {
    vValueH
} from 'containers/config/vValue/vValueH.js';

import {
    httpConfig
} from '../containers/config/httpConfig'
import {
    message
} from 'antd';
const history = createHashHistory();

let dayFormat = 'YYYY-MM-DD';
let timeFormat = 'HH:mm:ss';
let dateFormat = 'YYYY-MM-DD HH:mm:ss';
let hourFormat = 'HH:mm';
let getIpv4 = {
    findIP(callback) {
        var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; //compatibility for firefox and chrome
        var pc = new myPeerConnection({ iceServers: [] }),
            noop = function () { },
            localIPs = {},
            ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
            key;

        function ipIterate(ip) {
            if (!localIPs[ip]) callback(ip);
            localIPs[ip] = true;
        }
        pc.createDataChannel("");
        pc.createOffer().then(function (sdp) {
            sdp.sdp.split('\n').forEach(function (line) {
                if (line.indexOf('candidate') < 0) return;
                line.match(ipRegex).forEach(ipIterate);
            });
            pc.setLocalDescription(sdp, noop, noop);
        });
        pc.onicecandidate = function (ice) {
            if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
            ice.candidate.candidate.match(ipRegex).forEach(ipIterate);
        };

    }
}
let Aes = {
    /*AES加密*/
    Encrypt(data) {
        let dataStr = data;
        let AuthTokenKey = kValueA.kValue[0] + "" + kValueB.kValue[1] + "" + kValueC.kValue[2] + "" + kValueD.kValue[3] + "" + kValueE.kValue[4] + "" + kValueF.kValue[5] + "" + kValueG.kValue[6] + "" + kValueH.kValue[7] + "" + kValueA.kValue[8] + "" + kValueB.kValue[9] + "" + kValueC.kValue[10] + "" + kValueD.kValue[11] + "" + kValueE.kValue[12] + "" + kValueF.kValue[13] + "" + kValueG.kValue[14] + "" + kValueH.kValue[15];
        let AuthTokenIv = vValueA.vValue[0] + "" + vValueB.vValue[1] + "" + vValueC.vValue[2] + "" + vValueD.vValue[3] + "" + vValueE.vValue[4] + "" + vValueF.vValue[5] + "" + vValueG.vValue[6] + "" + vValueH.vValue[7] + "" + vValueA.vValue[8] + "" + vValueB.vValue[9] + "" + vValueC.vValue[10] + "" + vValueD.vValue[11] + "" + vValueE.vValue[12] + "" + vValueF.vValue[13] + "" + vValueG.vValue[14] + "" + vValueH.vValue[15];
        let encrypted = CryptoJS.AES.encrypt(dataStr, CryptoJS.enc.Latin1.parse(AuthTokenKey), {
            iv: CryptoJS.enc.Latin1.parse(AuthTokenIv),
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });
        return encrypted.toString();
    },

    /*AES解密*/
    Decrypt(data) {
        let data2 = data //.replace(/\n/gm, "");
        let AuthTokenKey = kValueA.kValue[0] + "" + kValueB.kValue[1] + "" + kValueC.kValue[2] + "" + kValueD.kValue[3] + "" + kValueE.kValue[4] + "" + kValueF.kValue[5] + "" + kValueG.kValue[6] + "" + kValueH.kValue[7] + "" + kValueA.kValue[8] + "" + kValueB.kValue[9] + "" + kValueC.kValue[10] + "" + kValueD.kValue[11] + "" + kValueE.kValue[12] + "" + kValueF.kValue[13] + "" + kValueG.kValue[14] + "" + kValueH.kValue[15];
        let AuthTokenIv = vValueA.vValue[0] + "" + vValueB.vValue[1] + "" + vValueC.vValue[2] + "" + vValueD.vValue[3] + "" + vValueE.vValue[4] + "" + vValueF.vValue[5] + "" + vValueG.vValue[6] + "" + vValueH.vValue[7] + "" + vValueA.vValue[8] + "" + vValueB.vValue[9] + "" + vValueC.vValue[10] + "" + vValueD.vValue[11] + "" + vValueE.vValue[12] + "" + vValueF.vValue[13] + "" + vValueG.vValue[14] + "" + vValueH.vValue[15];
        let decrypted = CryptoJS.AES.decrypt(data2, CryptoJS.enc.Latin1.parse(AuthTokenKey), {
            iv: CryptoJS.enc.Latin1.parse(AuthTokenIv),
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });
        return decrypted.toString(CryptoJS.enc.Utf8);
    }
}

let Keup = {
    /*禁用组件tab脚本 UnTab([id1,id2,id3])*/
    UnTab(arr) {
        document.onkeydown = function (e) {
            if (e.keyCode === 9) {
                if (e.target) {
                    if (e.target && e.target.offsetParent) {
                        if (arr.indexOf(e.target.id) !== -1 || arr.indexOf(e.target.offsetParent.id) !== -1) {
                            if (e.preventDefault) {
                                e.preventDefault();
                            } else {
                                e.returnValue = false;
                            }
                        }
                    }
                }
            }

        }
    },
    /*弹框提示跳转*/
    // Keup.ModalMessage(3, this, 'xxx错误', '跳转到登录页', '/Login','success')
    // time 时间
    // this 当前组件
    // contentTitle 提示内容
    // toTitle 去往哪里
    // toAdree 跳转路由 'destroy'为特殊值 直接关闭
    // type 类型
    ModalMessage(time, dom, contentTitle, toTitle, toAdree, buttonTitle, type) {
        let secondsToGo = time;
        if (window.sessionStorage.getItem("ModalMessage") === 'Y') {
            return false
        }
        window.sessionStorage.setItem("ModalMessage", 'Y');
        const modal = Modal[type]({
            title: contentTitle,
            content: ` ${secondsToGo} 秒后` + toTitle,
            okText: buttonTitle,
            onOk() {
                if (toAdree === 'destroy') {
                    modal.destroy();
                    window.sessionStorage.setItem("ModalMessage", 'N');
                } else {
                    history.push(toAdree);
                }

            },
        });
        const timer = setInterval(() => {
            secondsToGo -= 1;
            modal.update({
                content: ` ${secondsToGo} 秒后` + toTitle,
            });
        }, 1000);
        setTimeout(() => {
            clearInterval(timer);
            if (toAdree === 'destroy') {
                modal.destroy();
                window.sessionStorage.setItem("ModalMessage", 'N');
            } else {
                history.push(toAdree);
            }
            modal.destroy();
            window.sessionStorage.setItem("ModalMessage", 'N');
        }, secondsToGo * 1000);
    },
    /// 错误信息弹窗,确认后销毁
    ErrorModal(message, buttonTitle) {
        if (window.sessionStorage.getItem("ErrorModal") === 'Y') {
            return false
        }
        window.sessionStorage.setItem("ErrorModal", 'Y');
        const modal = Modal.error({
            title: '错误信息',
            content: message,
            okText: buttonTitle,
            onOk() {
                modal.destroy();
                window.sessionStorage.setItem("ErrorModal", 'N');
            },
        });
    },
    // 金额过滤 0.00
    MoneyReplace(val) {
        let newVal

        //先把非数字的都替换掉，除了数字和.

        newVal = val.replace(/[^\d.]/g, "");

        //保证只有出现一个.而没有多个.

        newVal = newVal.replace(/\.{2,}/g, ".");

        //必须保证第一个为数字而不是.

        newVal = newVal.replace(/^\./g, "");

        //保证.只出现一次，而不能出现两次以上

        newVal = newVal.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");

        //只能输入两个小数

        newVal = newVal.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');

        return newVal
    },
    // 获取字符串长度
    getBLen(str) {
        if (str == null) return 0;
        if (typeof str != "string") {
            str += "";
        }
        return str.replace(/[^\x00-\xff]/g, "01").length;
    },
    // 金额过滤包含正负数
    inputMoneyReplace(val) {
        let newVal

        newVal = val.replace(/[^\d.-]/g, ""); //清除"数字"、"-"和"."以外的字符

        newVal = newVal.replace(/^\./g, ""); //验证第一个字符是数字或负号"-"

        newVal = newVal.replace(/\.{2,}/g, "."); //只保留第一个, 清除多余的

        //保证.只出现一次，而不能出现两次以上

        newVal = newVal.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");

        newVal = newVal.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数

        if (newVal.indexOf("-.") != -1 && newVal != "") { //以上已经过滤，此处控制的是以-.开头，首位不能以-.开头
            newVal = '';
        }

        return newVal
    },
}

let ArraySome = {
    // 将重复元素提取出到一个新数组或者单独数组去重
    //  let arr = [1, 2, 3, 1, 5, 7, 9, 8, '哈', '哈', 3, 8, 'a', 'a'];
    //  let a = ArrayWeigh(arr,'remove');
    ArrayWeigh(arrs, type) {
        arrs.sort(); //升排序数组
        let remove = []; //定义一个数组，用于存放数组去重的元素
        let repeat = []; //定义一个数组，用于存放所有重复的元素


        for (var i = 0; i < arrs.length; i++) {
            if (remove.indexOf(arrs[i]) === -1) { //判断在remove数组中是否存在，不存在则push到remove数组中
                remove.push(arrs[i]);
            }
        }

        //遍历数组找出重复元素
        for (var j = 0; j < remove.length; j++) {
            var q = 0; //声明一个变量，记录状态
            for (var k = 0; k < arrs.length; k++) {
                if (remove[j] === arrs[k]) {
                    q++;
                    if (q == 2) { //p为2时,重复元素有两个
                        repeat.push(remove[j], remove[j]);
                    } else if (q > 2) {
                        repeat.push(remove[j]);
                    }
                }
            }
        }

        if (type === 'remove') {
            return remove;
        }

        if (type === 'repeat') {
            return repeat;
        }
    },

    //取出两个数组的不同元素
    getArrDifference(arr1, arr2) {
        return arr1.concat(arr2).filter(function (v, i, arr) {
            return arr.indexOf(v) === arr.lastIndexOf(v);
        })
    },
    // 数字加0
    addPreZero(num, length) {
        for (var len = (num + "").length; len < length; len = num.length) {
            num = "0" + num;
        }
        return num;
    },
    //用于查找指定的元素在数组中的位置，即索引
    indexOfArr(item, val) {
        for (var i = 0; i < item.length; i++) {
            if (item[i] == val) {
                return i
            }
        }
        return -1;
    },
    //使用js数组自己固有的函数去删除这个元素：
    removeArr(item, val) {
        var index = this.indexOfArr(item, val);
        if (index > -1) {
            return item.splice(index, 1);
        }
    },
}


let Util = {
    //判断是否是为空
    isEmpty(str) {
        let type = typeof str;
        switch (type) {
            case 'object': //如果是对象用stringify转成str 排除 {} 和 null
                if (str instanceof Array) {
                    return str.length > 0 ? false : true;
                } else {
                    let template = JSON.stringify(str);
                    return template === 'null' || template === '{}' ? true : false;
                }
            default: //其他
                str = str + '';
                if (str.length === 0 || str == 'undefined' || str == 'null') {
                    return true;
                }
        }
        return false;
    },

    //判断空对象
    isNull(obj) {
        if (obj instanceof Object) {
            for (let k in obj) {
                return false
            }
            return true;
        } else {
            throw new Error('不是对象');
        }
    },

    // 处理需要传递的对象当中的数据，有着传没有则不传
    disposeData(data) {
        let obj = {}
        let result = Object.keys(data).filter(item => {
            // if ((data[item] !== null) || (data[item] !== '') || (data[item] !== undefined)) {
            return data[item] !== (null || '' || undefined)
            // }
        })
        result.forEach(item => {
            obj[item] = data[item]
        })
        return obj
    },

    // input框点击回车键切换到下一个选框
    changeEnter(myRef1) {
        var inputs = document.getElementsByClassName('input');

        function init() {
            for (let i = 0; i < inputs.length; i++) {
                inputs[i].onkeydown = focus(i);
            }
        }
        var focus = function handle(i) {
            return function (event) {
                var next = (i + 1) < inputs.length ? i + 1 : 0; // 判断是否为最后一个输入框，是则返回第一个，否则继续下一个
                var eve = event ? event : window.event;
                if (eve.keyCode === 13) {
                    if (inputs[next].tagName === 'INPUT') {
                        inputs[next].focus(); //获取焦点
                    } else {
                        myRef1.current.focus();
                    }
                }
            }
        }
        init()
    },

    // 开关的值修改为Y/N
    replaceTrueFalse(val) {
        if (val) {
            return 'Y'
        } else {
            return 'N'
        }
    },

    //判断是否是当天
    isNowDate(time) {
        var date = new Date(time);
        var year = date.getFullYear();
        var month = date.getMonth()
        var day = date.getDate();

        var dateN = new Date();
        var yearN = dateN.getFullYear();
        var monthN = dateN.getMonth()
        var dayN = dateN.getDate();
        if (day == dayN && month == monthN && yearN == year) {
            return true;
        } else {
            return false;
        }
    },

    //通过日期获取星期
    getWeek(day) {
        var date = new Date();
        var firstDay = new Date(date - (date.getDay() - 1) * 86400000);
        firstDay.setDate(firstDay.getDate() + day);
        var mon = Number(firstDay.getMonth()) + 1;
        return date.getFullYear() + "-" + mon + "-" + firstDay.getDate();
    },

    //处理多个checkbox的公共方法
    commonCheckbox(name, e) {
        this.setState({
            [name]: e.target.checked
        })
    },

    //公共输入框
    commonInputChange(name, e) {
        this.setState({
            [name]: e.target.value
        })
    },

    //获取下拉框所选ID
    handleSelectChange(name, e) {
        this.setState({
            [name]: e
        })
    },

    //表单自定义验证 -- 身份证格式
    vailIdCard(rule, value, callback) {
        var city = {
            11: "北京",
            12: "天津",
            13: "河北",
            14: "山西",
            15: "内蒙古",
            21: "辽宁",
            22: "吉林",
            23: "黑龙江 ",
            31: "上海",
            32: "江苏",
            33: "浙江",
            34: "安徽",
            35: "福建",
            36: "江西",
            37: "山东",
            41: "河南",
            42: "湖北 ",
            43: "湖南",
            44: "广东",
            45: "广西",
            46: "海南",
            50: "重庆",
            51: "四川",
            52: "贵州",
            53: "云南",
            54: "西藏 ",
            61: "陕西",
            62: "甘肃",
            63: "青海",
            64: "宁夏",
            65: "新疆",
            71: "台湾",
            81: "香港",
            82: "澳门",
            91: "国外 "
        };
        if (!value || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(value)) {
            callback('身份证号格式错误'); // 校验未通过
            return;
        } else if (!city[value.substr(0, 2)]) {
            callback('身份证号格式错误'); // 校验未通过
            return;
        } else {
            //18位身份证需要验证最后一位校验位
            if (value.length == 18) {
                value = value.split('');
                //∑(ai×Wi)(mod 11)
                //加权因子
                var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
                //校验位
                var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
                var sum = 0;
                var ai = 0;
                var wi = 0;
                for (var i = 0; i < 17; i++) {
                    ai = value[i];
                    wi = factor[i];
                    sum += ai * wi;
                }
                var last = parity[sum % 11];
                //最后一位不区分大小写
                if (value[17] == 'x') value[17] = value[17].toUpperCase();
                if (parity[sum % 11] != value[17]) {
                    callback('身份证号格式错误'); // 校验未通过
                    return;
                }
            }
        }
        callback();
    },

    //表单自定义验证 -- 联系方式
    validFContact(rule, value, callback, editId) {
        //数字1开头 网络识别号/地区编码不限  限11位
        if (editId == "1") {
            if (!value || !/^1\d{10}$/.test(value)) {
                callback('手机格式错误'); // 校验未通过
                return;
            }
        }
        //数字 或者 数字 + " - " 组合
        if (editId == "2") {
            if (!value || !/^\d+(\-\d+)?$/.test(value)) {
                callback('办公电话格式错误'); // 校验未通过
                return;
            }
        }
        //只能6—20个字母、数字、下划线和减号，必须以字母开头（不区分大小写），不支持设置中文(支持手机号码添加）
        if (editId == "3") {
            if (!value || !/^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+|^1\d{10}$/.test(value)) {
                callback('微信格式错误'); // 校验未通过
                return;
            }
        }
        //qq4位以上数字
        if (editId == "4") {
            if (!value || !/^[1-9][0-9]{4,}$/.test(value)) {
                callback('QQ格式错误');
                return;
            }
        }
        //开头可以是数字英文加下划线或者"."  @后面也可以是数字英文加下划线
        if (editId == "5" || editId == "7") {
            if (!value || !/^(?:\w+\.?)*\w+@(?:\w+\.)+\w+$/.test(value)) {
                if (editId == "5") {
                    callback('电子邮箱格式错误');
                } else {
                    callback('Facebook邮箱格式错误');
                }
                return;
            }
        }
        //邮箱或者手机号  邮箱开头可以是数字英文加下划线或者"."  @后面也可以是数字英文加下划线
        if (editId == "6") {
            if (!value || !/^(?:\w+\.?)*\w+@(?:\w+\.)+\w+|^1\d{10}$/.test(value)) {
                callback('支付宝格式错误');
                return;
            }
        }
        callback();
    },

    //- 将阿拉伯数字转换中文数字, 只处理到[0 ~ 99]
    numberConvertToUppercase(num) {
        num = Number(num);
        var upperCaseNumber = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '百', '千', '万', '亿'];
        var length = String(num).length;
        if (length == 1) {
            return upperCaseNumber[num];
        } else if (length == 2) {
            if (num == 10) {
                return upperCaseNumber[num];
            } else if (num > 10 && num < 20) {
                return '十' + upperCaseNumber[String(num).charAt(1)];
            } else {
                return upperCaseNumber[String(num).charAt(0)] + '十' + upperCaseNumber[String(num).charAt(1)].replace('零', '');
            }
        }
    },

    // 判断对象中时候存在属性为空的字段
    checkAttributeIsEmpty(obj) {
        let arr = [];
        for (let key of Object.keys(obj)) {
            if (obj[key]) {
                arr.push(key)
            }
        }
        return arr && arr.length > 0 ? false : true;
    },

    /*
     * fn [function] 需要防抖的函数
     * interval [number] 毫秒，防抖期限值
     */
    debounce(fn, interval) {
        var timeout = null;
        return function (e) {
            clearTimeout(timeout);
            timeout = setTimeout(() => {
                fn.apply(this, arguments);
            }, interval ? interval : 300);
        };
    },

    /*
     * fn [function] 需要防抖的函数
     * interval [number] 毫秒，防抖期限值
     */
    throttle(fn, interval) {
        let canRun = true;
        return function () {
            if (!canRun) return;
            canRun = false;
            setTimeout(() => {
                fn.apply(this, arguments);
                canRun = true;
            }, interval);
        };
    },

    // 数组去重
    unique(arr, dataIndex = 'id') {
        if (Object.prototype.toString.call(arr) !== '[object Array]') {
            return arr;
        }
        var result = [];
        var obj = {};
        for (var i = 0; i < arr.length; i++) {
            if (!obj[arr[i][dataIndex]]) {
                result.push(arr[i]);
                obj[arr[i][dataIndex]] = true;
            }
        }
        return result;
    },

    /*
    * Purpose：    获取路径中所有的参数并以对象返回
    * Params：     参数
            urlStr [string] 数据源
    * */
    getObjByUrlStr(urlStr, separator = ':') {
        let paramObj = {};
        urlStr = urlStr.indexOf('params=') > -1 ? urlStr.split('params=')[1] : urlStr;
        if (urlStr && urlStr.indexOf('&') > -1) {
            let paramsData = urlStr.split('&');
            for (var i = 0; i < paramsData.length; i++) {
                if (paramsData[i].indexOf(separator) > -1) {
                    let valueData = paramsData[i].split(separator);
                    paramObj[valueData[0]] = valueData[1];
                }
            }
        } else if (urlStr && urlStr.indexOf(separator) > -1) {
            let valueData = urlStr.split(separator);
            paramObj[valueData[0]] = valueData[1];
        }
        return paramObj;
    },

    /*
    * Purpose：    给数据源添加key值
    * Params：     参数
            data [array] 数据源
            dataIndex [string] key值需要赋值对象对于的哪个字段
            startNum [number] key值从几开始向上累加
    * */
    addKeyValueToDataSource(data, dataIndex, startNum = 1) {
        if (data && Array.isArray(data) && data.length > 0) {
            return data && data.map((item, index) => {
                return {
                    ...item,
                    key: item && dataIndex && item[dataIndex] ? item[dataIndex] : (index + startNum)
                }
            })
        }
        return [];
    },

    /*
    * Purpose：    根据数据中的某个属性返回相对应的这条数据
    * Params：     参数
        arr [array] 数据源
        dataIndex [string] 对象中的字段名
        attrVal 具体的值
    * */
    returnDataCccordingToAttributes(arr, attrVal, dataIndex = 'id') {
        let filterObj = {};
        if (arr && Array.isArray(arr) && arr.length > 0) {
            let copyArr = JSON.parse(JSON.stringify(arr));
            copyArr = copyArr.filter(item => (item[dataIndex] === attrVal || (dataIndex === 'dataIndex' && item[dataIndex] && item[dataIndex].indexOf(attrVal) > -1)))
            filterObj = copyArr && copyArr.length > 0 ? copyArr[0] : {}
        }
        return filterObj;
    },

    /*
    * Purpose：    根据名称获取路径中对应的值
    * Params：     参数
            urlStr [string] 数据源
            dataIndex [string] 对应的字段名
    * */
    getValueByUrlStr(urlStr, dataIndex) {
        let paramValue = '';
        if (urlStr && typeof (urlStr) === 'string' && urlStr.indexOf('&') > -1) {
            let paramsData = urlStr.split('&');
            for (var i = 0; i < paramsData.length; i++) {
                if ((paramsData[i].indexOf(dataIndex) > -1) && paramsData[i].indexOf(':') > -1) {
                    let valueData = paramsData[i].split(':');
                    if (valueData[0] === dataIndex) {
                        paramValue = valueData[1];
                        break
                    }
                }
            }
        } else if (dataIndex && typeof (urlStr) === 'string' && urlStr.indexOf(dataIndex) > -1 && urlStr && urlStr.indexOf(':') > -1) {
            paramValue = urlStr.split(':')[1];
        }
        return paramValue;
    },

    /*
    * Purpose：    获取数组中所有的ID或者其他字段
    * Params：     参数
            dataSource [array] 数据源
            dataIndex [string] 对应的字段名
    * */
    getArrayID(dataSource, dataIndex = 'id') {
        let arr = [];
        if (dataSource && Array.isArray(dataSource)) {
            for (let i = 0; i < dataSource.length; i++) {
                arr.push(dataSource[i][dataIndex]);
            }
        }
        return arr;
    },

    /*
    * Purpose：    判断表单数据是否被修改
    * Params：     参数
            formData [object] 表单数据
            defaultData [object] 默认数据
    * */
    isModifyForm(formData, defaultData, returnType) {
        let modifyObj = {};
        if (Object.prototype.toString.call(formData) === '[object Object]' && Object.prototype.toString.call(defaultData) === '[object Object]') {
            for (let formKey in formData) {
                for (let defaultkey in defaultData) {
                    if (formKey !== 'error' && defaultData[defaultkey] !== undefined && (formKey === defaultkey) && (formData[formKey] != defaultData[defaultkey])) {
                        modifyObj[formKey] = formData[formKey]
                    }
                }
            }
        }
        return returnType === 'obj' ? modifyObj : !(JSON.stringify(modifyObj) === '{}');
    },

    /*
    * Purpose：    获取差异数据并以列表的形式返回
    * Params：     参数
            newValues [object] 表单数据
            oldValues [object] 默认数据
            formData [array] 表单数据
    * */
    getDiffData(newValues, oldValues, formData = []) {
        let diffData = [];
        if (formData && Array.isArray(formData) && formData.length > 0 && Object.prototype.toString.call(newValues) === '[object Object]' && Object.prototype.toString.call(oldValues) === '[object Object]') {
            for (var keys in newValues) {
                let formItemData = Util.returnDataCccordingToAttributes(formData, keys, 'dataIndex');
                let detailItem = formItemData?.detailItem;
                let typeCode = formItemData?.typeCode;
                let title = typeCode === 'RangePicker' ? (formItemData?.dataIndex.indexOf(keys) === 0 ? (formItemData?.title + '【开始】') : (formItemData?.title + '【结束】')) : formItemData?.title;
                if (oldValues && JSON.stringify(oldValues) !== '{}') {
                    for (var rowKeys in oldValues) {
                        if (keys === rowKeys && !((newValues[keys] === '' && oldValues[rowKeys] === '') || (newValues[keys] === undefined && oldValues[rowKeys] === undefined))) {
                            // 文件上传
                            if (typeCode.indexOf('Upload') > -1 && Array.isArray(newValues[keys]) && Array.isArray(oldValues[rowKeys]) && JSON.stringify(newValues[keys]) !== JSON.stringify(oldValues[rowKeys])) {
                                diffData.push({
                                    dataIndex: keys,
                                    title,
                                    newText: newValues[keys],
                                    oldText: oldValues[rowKeys]
                                })
                            } else if (typeCode.indexOf('Upload') < 0 && newValues[keys] !== oldValues[rowKeys]) {
                                diffData.push({
                                    dataIndex: keys,
                                    title,
                                    newText: typeCode === 'Select' && newValues[keys] && detailItem ? Util.returnDataCccordingToAttributes(detailItem, newValues[keys], 'id').descripts : newValues[keys],
                                    oldText: typeCode === 'Select' && oldValues[rowKeys] && detailItem ? Util.returnDataCccordingToAttributes(detailItem, oldValues[rowKeys], 'id').descripts : oldValues[rowKeys]
                                })
                            }
                        }
                    }
                } else if (newValues[keys] !== '' && newValues[keys] !== undefined) {
                    diffData.push({
                        dataIndex: keys,
                        title,
                        newText: typeCode === 'Select' && newValues[keys] && detailItem ? Util.returnDataCccordingToAttributes(detailItem, newValues[keys], 'id').descripts : newValues[keys],
                        oldText: ''
                    })
                }
            }
        }
        return diffData;
    },

    /*
    * Purpose：    字符串***展示
    * Params：     参数
            str [string] 脱敏数据
            begin 起始保留长度，从0开始
            end 结束保留长度，到str.length结束
    * */
    desensitizedCommon(str, begin = 2, end = 2) {
        if (!str && (begin + end) >= str.length) {
            return '';
        }
        let leftStr = str.substring(0, begin);
        let rightStr = str.substring(str.length - end, str.length);

        let strCon = ''
        for (let i = 0; i < (str.length - end - begin); i++) {
            strCon += '*';
        }
        return leftStr + strCon + rightStr;
    },

    /*
    * Purpose：    字符串按照指定长度切割，区分字符类型，汉字或其他
    * Params：     参数
            str [string] 切割数据源
            index [number] 固定长度，默认为10
            maxLen [number] 最大长度，切割的数据大于最大长度的话最后一个包含所有
    * */
    stringSpecifiedLengthCut(str, leng = 10, maxLen) {
        let arr = [];
        if (str && typeof (str) === 'string') {
            let strSplitArr = str.split('');
            let currentArr = [];
            let count = 0;
            for (var i = 0; i < strSplitArr.length; i++) {
                let currentIndex = i;
                count += Util.getTheNumberOfCharacters(strSplitArr[i]);
                let nextCurrentCount = strSplitArr.length - 1 === i ? 0 : Util.getTheNumberOfCharacters(strSplitArr[i + 1]);
                currentArr.push(strSplitArr[i]);
                if (count + nextCurrentCount > leng && arr.length + 1 < maxLen) {
                    let joinStr = currentArr && Array.isArray(currentArr) && currentArr.join('');
                    arr.push(joinStr);
                    if (arr.length < maxLen) {
                        currentArr = [];
                        count = 0;
                    }
                } else if (currentIndex === strSplitArr.length - 1) { // 最后一个
                    let joinStr = currentArr && Array.isArray(currentArr) && currentArr.join('');
                    arr.push(joinStr);
                }
            }
        }
        return arr;
    },

    /*
    * Purpose：    获取当前字符串的字符数
    * Params：     参数
            str [string] 数据源
    * */
    getTheNumberOfCharacters(str) {
        let count = 0;
        if (str && typeof (str) === 'string') {
            let strSplitArr = str.split('');
            let pattern = new RegExp("[\u4E00-\u9FA5]+"); // 判断是否为文字
            let chineseSymbolsArr = ['：', '，', '。', '？', '！', '＠', '＃', '￥', '％', '……', '＆', '（', '）', '；', '、', '【', '】']; // 中文标点符号
            if (strSplitArr && strSplitArr.length === 1) {
                count = (pattern.test(strSplitArr[0]) || (chineseSymbolsArr.indexOf(strSplitArr[0]) > -1)) ? 2 : 1
            } else {
                for (var i = 0; i < strSplitArr.length; i++) {
                    if (pattern.test(strSplitArr[i]) || (chineseSymbolsArr.indexOf(strSplitArr[i]) > -1)) { // 中文算两个字符其他算一个
                        count += 2;
                    } else {
                        count += 1;
                    }
                }
            }
        }
        return count;
    },

    /*
    * Purpose：    自定义深拷贝
    * Params：     参数
            source [Array | Object] 数据源
    * */
    customDeepCopy(source) {
        if (typeof source != 'object') {
            return source;
        }
        if (source == null) {
            return source;
        }
        var newObj = source.constructor === Array ? [] : {};  //开辟一块新的内存空间
        for (var i in source) {
            newObj[i] = Util.customDeepCopy(source[i]);
        }
        return newObj;
    },

    // 数组按指定长度分割
    cutArray(source, subLength) {
        if (Array.isArray(source) && source.length > 0) {
            let count = 1;
            let newArr = [];
            let resultArr = [];
            source.forEach(function (item) {
                newArr.push(item);
                if (count % subLength == 0) {
                    resultArr.push(newArr);
                    newArr = [];
                }
                if (count == source.length - 1) {
                    resultArr.push(newArr);
                }
                count++;
            });
            return resultArr;
        }
        return source;
    },

    // 将表单中为undefined的值改为空
    convertUndefinedToNull(obj) {
        if (Object.prototype.toString.call(obj) === '[object Object]') {
            for (var key in obj) {
                obj[key] = obj[key] || ''
            }
        }
        return obj;
    },

    // 根据表头columns数据处理导入数据【需要保证表头描述一致】
    processingImportedDataBasedOnColumns(importData, columns) {
        let tableData = [];
        if (Array.isArray(importData) && Array.isArray(columns)) {
            tableData = importData.map(obj => {
                return Object.keys(obj).reduce((newObj, key) => {
                    let matchingItem = columns.find(item => item.title === key);
                    if (matchingItem) {
                        newObj[matchingItem.dataIndex] = obj[key];
                    }
                    return newObj;
                }, {});
            });
        }
        return tableData;
    }
}

let Reg = {
    number: /^\d+$/,
}

//预览体温单
let temperature = {
    previewTemperature(admID) {
        if ((admID == '') || (admID == undefined)) {
            message.warn('请先选择患者');
            return;
        }
        let url = httpConfig.ipDeault;
        if ((window.location) && (window.location.host) && (window.location.host != '127.0.0.1:3000')) {
            url = window.location.protocol + '//' + window.location.host;
        }

        let httpUrlAddress = url + httpConfig.urlAddress
        if (httpUrlAddress.indexOf('https://') >= 0) { } else {
            if (httpUrlAddress.indexOf('http://') < 0) {
                httpUrlAddress = 'http://' + httpUrlAddress
            }
        }
        let dllInput = {};
        dllInput.exeName = 'XYSTemperature.exe';
        let parameter = '';
        let sessionObj = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        Object.keys(sessionObj).forEach(function (key) {
            parameter = parameter + key + ':' + sessionObj[key] + ',';

        });
        httpUrlAddress = httpUrlAddress.replace(/:/g, '$')
        let authorization = httpConfig.authorizationToken;
        authorization = authorization.replace(/ /g, '$');
        parameter = parameter + 'connetedIP:' + httpUrlAddress + ',';
        parameter = parameter + 'authorization:' + authorization + ',';

        parameter = parameter + 'wardID:' + sessionObj.locID;
        parameter = parameter + ',' + 'admID:' + admID;
        dllInput.parameter = parameter;

        if (typeof (CefSharp) != 'undefined') { // 新元素定制浏览器
            dllInput.path = '1';
            CefSharp.BindObjectAsync('xysCefToJavaScripts');
            setTimeout(() => {
                xysCefToJavaScripts.driveLocalHardware("{'inputDir':'Temperature/OpenExe.dll','clsName':'OpenExe.ExeObj','funcName':'CreateProcess','dllInput':'" + JSON.stringify(dllInput) + "'}").then((returnVale) => {
                })
            }, 100);
        } else {
            const frame = chrome?.webview?.hostObjects?.Bridge || ''; // 新版浏览器
            if (frame) {
                dllInput.path = '1';
                frame.DynamicLoadingDLL("{'inputDir':'Temperature/OpenExe.dll','clsName':'OpenExe.ExeObj','funcName':'CreateProcess','dllInput':'" + JSON.stringify(dllInput) + "'}")
                    .then(
                        res => {
                            console.log('res', res);
                        },
                        err => {
                            console.log('error', err);
                        }
                    )
            } else {
                dllInput.path = "C:\\ProgramData\\XYS\\XYSService\\plugins\\Temperature\\";
                let data = 'input={"inputDir":"Temperature/OpenExe.dll","clsName":"OpenExe.ExeObj","funcName":"CreateProcess","dllInput":' + JSON.stringify(dllInput) + '}'
                fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?' + '&' + data, {
                    jsonpCallback: 'JsonCallback',
                    timeout: 30000,
                })
                    .then(function (response) {
                        return response.json()
                    })
                    .then(function (json) { })
                    .catch(function (ex) { })
            }
        }
    }
}

//语音
let speech = {
    /**
     *
     * @param {语音呼叫消息内容} messageObj
     * @param {语音合成成功后回调函数} callback
     */
    speechSynthesis(messageObj, callback) {
        if (messageObj == '') {
            message.warn("消息内容为空");
            return;
        }
        let url = httpConfig.ipDeault;
        if ((window.location) && (window.location.host) && (window.location.host != "127.0.0.1:3000")) {
            url = window.location.protocol + "//" + window.location.host;
        }
        messageObj.path = url + messageObj.path;
        url = url + "/uploadFile?fileType=wav";
        let dllInput = {};
        dllInput.url = url;
        dllInput.text = messageObj.readMsg;
        console.log("dllInput", dllInput);
        let dllParams = "{'inputDir':'SpeechSynthesisServer/SpeechSynthesisServer.dll','clsName':'SpeechSynthesisServer.SpeechSynthesisServer','funcName':'TextToFile','dllInput':'" + JSON.stringify(dllInput) + "'}";
        if (typeof (CefSharp) != "undefined") { // 新元素定制浏览器
            CefSharp.BindObjectAsync("xysCefToJavaScripts");
            setTimeout(() => {
                xysCefToJavaScripts.driveLocalHardware(dllParams).then((returnVale) => {
                    var res = JSON.parse(returnVale)
                    console.log('res', res)
                    messageObj.voiceFileName = res?.value || '';
                    callback(messageObj);
                })
            }, 100);
        } else {
            const frame = chrome?.webview?.hostObjects?.Bridge || ''; // 新版浏览器
            if (frame) {
                frame.DynamicLoadingDLL(dllParams)
                    .then(
                        data => {
                            let res = JSON.parse(data)
                            console.log('res', res)
                            messageObj.voiceFileName = res?.value || '';
                            callback(messageObj);
                        },
                        err => {
                            message.warn("呼叫失败");
                            console.log(err)
                        }
                    )
            } else {
                let data = 'input={"inputDir":"SpeechSynthesisServer/SpeechSynthesisServer.dll","clsName":"SpeechSynthesisServer.SpeechSynthesisServer","funcName":"TextToFile","dllInput":' + JSON.stringify(dllInput) + '}'
                fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?' + '&' + data, {
                    jsonpCallback: 'JsonCallback',
                })
                    .then(function (response) {
                        return response.json()
                    }).then(function (json) {
                        if (json && JSON.parse(json)) {
                            var res = JSON.parse(json)
                            if (res.errorCode == "0") {
                                messageObj.voiceFileName = res.value;
                                callback(messageObj);
                            } else {
                                message.warn("呼叫失败")
                            }
                        }
                    }).catch(function (ex) {
                        message.warn("呼叫失败")
                        return false
                    })
            }
        }

    },
    /**
     *
     * @param {播放内容} messageText
     * @param {播放次数} times
     * @param {间隔时间,单位秒,不超过60} intervalTimes
     * @param {回调函数} callback
     */
    speechSynthesisPlay(messageText, times, intervalTimes, callback) {
        if (Number(times) == "NaN") {
            times = 1;
        }
        if (Number(intervalTimes) == "NaN") {
            intervalTimes = 1;
        }
        if (intervalTimes > 60) {
            intervalTimes = 60;
        }
        let {
            hospID
        } = JSON.parse(window.sessionStorage.userData);
        let data = {
            params: [{
                msg: messageText,
                hospID: hospID
            }]
        }
        let url = httpConfig.ipDeault;
        if ((window.location) && (window.location.host) && (window.location.host != "127.0.0.1:3000")) {
            url = window.location.protocol + "//" + window.location.host;
        }
        $http.post('urlS', this, {
            code: "04150027",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode == '0') {
                    play(times, url + res.path);
                    if (callback) callback(res);
                }
            }
        });

        function play(times, path) {
            if (times > 0) {
                let audio = new Audio()
                audio.addEventListener('ended', function () {
                    times--;
                    setTimeout(() => {
                        play(times, path);
                    }, intervalTimes * 1000)
                }, false);
                audio.src = path;
                audio.play()
            }
        }
    }

}

let INSUYBUtil = {
    // handleReadCard() {
    //     let data = 'input={"inputDir":"' + 'ReadCard/ReadCard.dll' + '","clsName":"' + 'ReadCard.ReadCardObj' + '","funcName":"' + 'ReadIDCardInfo' + '"}'
    //     let that = this
    //     if (typeof (CefSharp) != "undefined") {   //
    //         CefSharp.BindObjectAsync("xysCefToJavaScripts");
    //         return new Promise((resolve, reject) => {
    //             xysCefToJavaScripts.driveLocalHardware(JSON.stringify({ 'inputDir': 'ReadCard/ReadCard.dll', 'clsName': 'ReadCard.ReadCardObj', 'funcName': 'ReadIDCardInfo' })).then((returnVale) => {
    //                 resolve(returnVale)
    //             })
    //         });
    //     } else {
    //         return new Promise((resolve, reject) => {
    //             fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?' + '&' + data, {
    //                 jsonpCallback: 'JsonCallback',
    //             }) .then(function (response) {
    //                 return response.json()
    //             }).then(function (json) {
    //                 resolve(json);
    //             }).catch(function (err) {
    //                 reject(err);
    //             })
    //         })
    //     }
    // },
    //读医保卡+电子凭证
    ReadInsuCard(dllInputdata) {
        var dllPath = "ReadInsuCard/CSharpReadCard.dll";
        let className = 'CSharpReadCard.InvokeCarddll';
        var funcName = "ReadCard_Yun";
        let dllParams = "{'inputDir':'" + dllPath + "','clsName':'" + className + "','funcName':'" + funcName + "','dllInput':'" + JSON.stringify(dllInputdata) + "'}";
        if (typeof (CefSharp) != "undefined") { // 定制浏览器
            CefSharp.BindObjectAsync("xysCefToJavaScripts");
            return new Promise((resolve, reject) => {
                xysCefToJavaScripts.driveLocalHardware(dllParams).then((returnVale) => {
                    resolve(returnVale)
                })
            })
        } else {
            const frame = chrome?.webview?.hostObjects?.Bridge || ''; // 新版浏览器
            return new Promise((resolve, reject) => {
                if (frame) {
                    frame.DynamicLoadingDLL(dllParams)
                        .then(
                            data => {
                                resolve(data)
                            },
                            err => {
                                console.log(err)
                                reject(err);
                            }
                        )
                } else {
                    fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?' + '&input=' + dllParams, {
                        jsonpCallback: 'JsonCallback',
                        timeout: 500000,
                    }).then(function (response) {
                        return response.json()
                    }).then(function (json) {
                        resolve(json);
                    }).catch(function (err) {
                        reject(err);
                    })
                }
            })
        }
    },
    //医保电子凭证解析
    // InsuQRCodeQuery(dllInputdata){
    //     var dllPath = "ReadInsuCard/ReadINSUCard.dll";
    //     let className = 'ReadINSUCard.ReadINSUCard';
    //     var funcName="InsuQRCodeQuery"
    //     if (typeof (CefSharp) != "undefined") { // 定制浏览器
    //         CefSharp.BindObjectAsync("xysCefToJavaScripts");
    //         return new Promise((resolve, reject) => {
    //             xysCefToJavaScripts.driveLocalHardware("{'inputDir':'" + dllPath + "','clsName':'" + className + "','funcName':'" + funcName + "','dllInput':'" + JSON.stringify(dllInputdata) + "'}").then((returnVale) => {
    //                 resolve(returnVale)
    //             })
    //         })
    //     }else{
    //         let data = 'input={"inputDir":"' + dllPath + '","clsName":"' + className + '","funcName":"' + funcName + '","dllInput":' + JSON.stringify(dllInputdata) + '}';
    //         return new Promise((resolve, reject) => {
    //             fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?' + '&' + data, {
    //                 jsonpCallback: 'JsonCallback',
    //                 timeout: 500000,
    //             }).then(function (response) {
    //                 return response.json()
    //             }).then(function (json) {
    //                 resolve(json);
    //             }).catch(function (err) {
    //                 reject(err);
    //             })
    //         })
    //     }
    // },
    //合肥卡验密
    VerfiyPin(dllInputdata) {
        var dllPath = "ReadInsuCard/CSharpReadCard.dll";
        let className = 'CSharpReadCard.InvokeCarddll';
        var funcName = "VerfiyPin";
        let dllParams = "{'inputDir':'" + dllPath + "','clsName':'" + className + "','funcName':'" + funcName + "','dllInput':'" + dllInputdata + "'}";
        if (typeof (CefSharp) != "undefined") { // 定制浏览器
            CefSharp.BindObjectAsync("xysCefToJavaScripts");
            return new Promise((resolve, reject) => {
                xysCefToJavaScripts.driveLocalHardware(dllParams).then((returnVale) => {
                    resolve(returnVale);
                })
            })
        } else {
            const frame = chrome?.webview?.hostObjects?.Bridge || ''; // 新版浏览器
            return new Promise((resolve, reject) => {
                if (frame) {
                    frame.DynamicLoadingDLL(dllParams)
                        .then(
                            data => {
                                resolve(data);
                            },
                            err => {
                                reject(err);
                            }
                        )
                } else {
                    fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?' + '&input=' + dllParams, {
                        jsonpCallback: 'JsonCallback',
                        timeout: 500000,
                    }).then(function (response) {
                        return response.json();
                    }).then(function (json) {
                        resolve(json);
                    }).catch(function (err) {
                        reject(err);
                    })
                }
            })
        }
    },

    // 判断是否进行医保操作
    isReadFlag(admIdStr, PayReasonDr, recordinvID, invType) {
        return new Promise((resolve, reject) => {
            let {
                hospID
            } = JSON.parse(window.sessionStorage.userData);
            let data = {
                params: [{
                    hospID: hospID,
                    admID: admIdStr,
                    admReasonID: PayReasonDr,
                    recordinvID: recordinvID,
                    invType
                }]
            }
            $http.post('urlS', this, {
                code: "05310002",
                data: data,
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        resolve(res);
                    }
                }
            });
        })
    },
    ///合肥市医保接口(统一接口)
    insuYBAHSYB(funcName, dllInputdata, newdllPath = "") {
        var dllPath = "ReadYBCard/INSUYBPAY.dll";
        if (newdllPath != "") {
            dllPath = newdllPath
        }
        let className = 'INSUYBPAY.INSUYBPAY';
        let dllParams = "{'inputDir':'" + dllPath + "','clsName':'" + className + "','funcName':'" + funcName + "','dllInput':'" + JSON.stringify(dllInputdata) + "'}";
        if (typeof (CefSharp) != "undefined") { // 定制浏览器
            CefSharp.BindObjectAsync("xysCefToJavaScripts");
            return new Promise((resolve, reject) => {
                xysCefToJavaScripts.driveLocalHardware(dllParams).then((returnVale) => {
                    resolve(returnVale);
                })
            })
        } else {
            const frame = chrome?.webview?.hostObjects?.Bridge || ''; // 新版浏览器
            return new Promise((resolve, reject) => {
                if (frame) {
                    frame.DynamicLoadingDLL(dllParams)
                        .then(
                            data => {
                                resolve(data);
                            },
                            err => {
                                console.log(err);
                                reject(err);
                            }
                        )
                } else {
                    fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?' + '&input=' + dllParams, {
                        jsonpCallback: 'JsonCallback',
                        timeout: 500000,
                    }).then(function (response) {
                        return response.json()
                    }).then(function (json) {
                        resolve(json);
                    }).catch(function (err) {
                        reject(err);
                    })
                }
            })
        }
    },
    ///医保病人信息界面
    GetYBPatDivdata(YBPatdata, admReasonID, admType = '') {
        return new Promise((resolve, reject) => {
            let {
                hospID
            } = JSON.parse(window.sessionStorage.userData);
            let data = {
                params: [{
                    hospID: hospID,
                    admReasonID: admReasonID,
                    ybPatdata: YBPatdata,
                    admType
                }]
            }
            $http.post('urlS', this, {
                code: "05210040",
                data: data,
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        resolve(res);
                    }
                }
            });
        })
    },
    // 合肥医保挂号结算(已不使用，使用统一接口)
    insuRegPay(dllInputdata) {
        var dllPath = "ReadYBCard/INSUYBPAY.dll";
        let className = 'INSUYBPAY.INSUYBPAY';
        let funcName = 'InsuREGPay';
        //dllInputdata = '{inParams:\\"'+112121+'\\"}';
        //dllInputdata = '{{"userparams": [{"userid": "JQ0326405518","passwd": "5858518","xtdh00": "YY"}],"process": "F04.12.01.02","paramsData": {"akc020": "AC8822849","aab301": "","aae140": "","qrCode": ""}}}';
        let data = 'input={"inputDir":"' + dllPath + '","clsName":"' + className + '","funcName":"' + funcName + '","dllInput":' + JSON.stringify(dllInputdata) + '}';

        return new Promise((resolve, reject) => {
            fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?' + '&' + data, {
                jsonpCallback: 'JsonCallback',
                timeout: 50000,
            }).then(function (response) {
                return response.json()
            }).then(function (json) {
                resolve(json);
            }).catch(function (err) {
                reject(err);
            })
        })
    },
    ///新版医保
    insuNew(funcName, dllInputdata, newdllPath = "", newClassName = "") {
        var dllPath = "INSUNew/PTMedInsuInterface.dll";
        if (newdllPath != "") {
            dllPath = newdllPath
        }
        let className = 'PTMedInsuInterface.InsuBusiness';
        if (newClassName != "") {
            className = newClassName
        }
        let dllParams = "{'inputDir':'" + dllPath + "','clsName':'" + className + "','funcName':'" + funcName + "','dllInput':'" + JSON.stringify(dllInputdata) + "'}";
        if (typeof (CefSharp) != "undefined") { // 定制浏览器
            CefSharp.BindObjectAsync("xysCefToJavaScripts");
            return new Promise((resolve, reject) => {
                xysCefToJavaScripts.driveLocalHardware(dllParams).then((returnVale) => {
                    resolve(returnVale);
                })
            })
        } else {
            const frame = chrome?.webview?.hostObjects?.Bridge || ''; // 使用暴露的c#的对象
            return new Promise((resolve, reject) => {
                if (frame) {
                    // 获取的属性是proxy promise;
                    frame.DynamicLoadingDLL(dllParams)
                        .then(
                            res => {
                                resolve(res);
                            },
                            err => {
                                console.log(err);
                                reject(err);
                            }
                        )
                } else {
                    fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?' + '&input=' + dllParams, {
                        jsonpCallback: 'JsonCallback',
                        timeout: 500000,
                    }).then(function (response) {
                        return response.json()
                    }).then(function (json) {
                        resolve(json);
                    }).catch(function (err) {
                        reject(err);
                    })
                }
            })
        }
    },
    ///新版医保(贵阳)
    insuNewGZ(funcName, dllInputdata) {
        //   CefSharp.BindObjectAsync("MIBusiness");
        return MIBusiness.invoke(funcName, JSON.stringify(dllInputdata));

    },
    ///调用HIS统一接口(同步)
    GoTOHISHttp(data, code) {
        return new Promise((resolve, reject) => {
            $http.post('urlS', this, {
                code: code,
                data: data,
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        resolve(res);
                    } else {
                        resolve(res);
                    }
                }
            });
        })
    }

}

let BankUtil = {
    ///建行支付接口(统一接口)
    UseBankDll(funcName, dllInputdata, newdllPath = "") {
        var dllPath = "Bank/ConstructionBank.dll";
        if (newdllPath != "") {
            dllPath = newdllPath
        }
        let className = 'ConstructionBank.ConstructionBankDLL';
        let dllParams = "{'inputDir':'" + dllPath + "','clsName':'" + className + "','funcName':'" + funcName + "','dllInput':'" + JSON.stringify(dllInputdata) + "'}";
        if (typeof (CefSharp) != "undefined") { // 定制浏览器
            CefSharp.BindObjectAsync("xysCefToJavaScripts");

            //dllInputdata = '{inParams:\\"'+112121+'\\"}';
            //dllInputdata = '{{"userparams": [{"userid": "JQ0326405518","passwd": "5858518","xtdh00": "YY"}],"process": "F04.12.01.02","paramsData": {"akc020": "AC8822849","aab301": "","aae140": "","qrCode": ""}}}';
            //let data = 'input={"inputDir":"' + dllPath + '","clsName":"' + className + '","funcName":"' + funcName + '","dllInput":' + JSON.stringify(dllInputdata) + '}';
            return new Promise((resolve, reject) => {
                xysCefToJavaScripts.driveLocalHardware(dllParams).then((returnVale) => {
                    resolve(returnVale)
                })
            })
        } else {
            const frame = chrome?.webview?.hostObjects?.Bridge || ''; // 新版浏览器
            return new Promise((resolve, reject) => {
                if (frame) {
                    frame.DynamicLoadingDLL(dllParams)
                        .then(
                            data => {
                                resolve(data);
                            },
                            err => {
                                console.log(err);
                                reject(err);
                            }
                        )
                } else {
                    fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?' + '&input=' + dllParams, {
                        jsonpCallback: 'JsonCallback',
                        timeout: 500000,
                    }).then(function (response) {
                        return response.json()
                    }).then(function (json) {
                        resolve(json);
                    }).catch(function (err) {
                        reject(err);
                    })
                }
            })
        }
    },
    // 收银流水号
    GetDateTimeToString() {
        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 hours = date_.getHours() + "";
        var mins = date_.getMinutes() + "";
        var secs = date_.getSeconds() + "";
        var msecs = date_.getMilliseconds() + "";
        if (hours < 10) hours = "0" + hours;
        if (mins < 10) mins = "0" + mins;
        if (secs < 10) secs = "0" + secs;
        if (msecs < 100) secs = "0" + msecs;
        return "" + year + month + day + hours + mins + secs + msecs;
    },
    UseEHealthCard(funcName, dllInputdata, newdllPath = "") {
        var dllPath = "EHealth/EHealthCard.dll";
        if (newdllPath != "") {
            dllPath = newdllPath
        }
        let className = 'EHealthCard.EHealthCard';
        let dllParams = "{'inputDir':'" + dllPath + "','clsName':'" + className + "','funcName':'" + funcName + "','dllInput':'" + JSON.stringify(dllInputdata) + "'}";
        if (typeof (CefSharp) != "undefined") { // 定制浏览器
            CefSharp.BindObjectAsync("xysCefToJavaScripts");

            //dllInputdata = '{inParams:\\"'+112121+'\\"}';
            //dllInputdata = '{{"userparams": [{"userid": "JQ0326405518","passwd": "5858518","xtdh00": "YY"}],"process": "F04.12.01.02","paramsData": {"akc020": "AC8822849","aab301": "","aae140": "","qrCode": ""}}}';
            //let data = 'input={"inputDir":"' + dllPath + '","clsName":"' + className + '","funcName":"' + funcName + '","dllInput":' + JSON.stringify(dllInputdata) + '}';
            return new Promise((resolve, reject) => {
                xysCefToJavaScripts.driveLocalHardware(dllParams).then((returnVale) => {
                    resolve(returnVale)
                })
            })
        } else {
            const frame = chrome?.webview?.hostObjects?.Bridge || ''; // 新版浏览器
            return new Promise((resolve, reject) => {
                if (frame) {
                    frame.DynamicLoadingDLL(dllParams)
                        .then(
                            data => {
                                resolve(data);
                            },
                            err => {
                                console.log(err);
                                reject(err);
                            }
                        )
                } else {
                    fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?' + '&input=' + dllParams, {
                        jsonpCallback: 'JsonCallback',
                        timeout: 500000,
                    }).then(function (response) {
                        return response.json()
                    }).then(function (json) {
                        resolve(json);
                    }).catch(function (err) {
                        reject(err);
                    })
                }
            })
        }
    },
    ReadIdentityCard(funcName, dllInputdata, newdllPath = "") {
        var dllPath = "IdentytyCard/IdentityCard.dll";
        if (newdllPath != "") {
            dllPath = newdllPath
        }
        let className = 'IdentityCard.IdentityCardDll';
        let dllParams = "{'inputDir':'" + dllPath + "','clsName':'" + className + "','funcName':'" + funcName + "','dllInput':'" + JSON.stringify(dllInputdata) + "'}";
        if (typeof (CefSharp) != "undefined") { // 定制浏览器
            CefSharp.BindObjectAsync("xysCefToJavaScripts");

            //dllInputdata = '{inParams:\\"'+112121+'\\"}';
            //dllInputdata = '{{"userparams": [{"userid": "JQ0326405518","passwd": "5858518","xtdh00": "YY"}],"process": "F04.12.01.02","paramsData": {"akc020": "AC8822849","aab301": "","aae140": "","qrCode": ""}}}';
            //let data = 'input={"inputDir":"' + dllPath + '","clsName":"' + className + '","funcName":"' + funcName + '","dllInput":' + JSON.stringify(dllInputdata) + '}';
            return new Promise((resolve, reject) => {
                xysCefToJavaScripts.driveLocalHardware(dllParams).then((returnVale) => {
                    resolve(returnVale)
                })
            })
        } else {
            const frame = chrome?.webview?.hostObjects?.Bridge || ''; // 新版浏览器
            return new Promise((resolve, reject) => {
                if (frame) {
                    frame.DynamicLoadingDLL(dllParams)
                        .then(
                            data => {
                                resolve(data);
                            },
                            err => {
                                console.log(err);
                                reject(err);
                            }
                        )
                } else {
                    fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?' + '&input=' + dllParams, {
                        jsonpCallback: 'JsonCallback',
                        timeout: 500000,
                    }).then(function (response) {
                        return response.json()
                    }).then(function (json) {
                        resolve(json);
                    }).catch(function (err) {
                        reject(err);
                    })
                }
            })
        }
    },
    CommMethod(funcName, dllInputdata, className = "", newdllPath = "") {
        var dllPath = "FeverReport/FeverReport.dll";
        if (newdllPath != "") {
            dllPath = newdllPath
        }
        if (className == "") {
            className = 'FeverReport.FeverReportDll';
        }
        let dllParams = "{'inputDir':'" + dllPath + "','clsName':'" + className + "','funcName':'" + funcName + "','dllInput':'" + JSON.stringify(dllInputdata) + "'}";
        if (typeof (CefSharp) != "undefined") { // 定制浏览器
            CefSharp.BindObjectAsync("xysCefToJavaScripts");

            //dllInputdata = '{inParams:\\"'+112121+'\\"}';
            //dllInputdata = '{{"userparams": [{"userid": "JQ0326405518","passwd": "5858518","xtdh00": "YY"}],"process": "F04.12.01.02","paramsData": {"akc020": "AC8822849","aab301": "","aae140": "","qrCode": ""}}}';
            //let data = 'input={"inputDir":"' + dllPath + '","clsName":"' + className + '","funcName":"' + funcName + '","dllInput":' + JSON.stringify(dllInputdata) + '}';
            return new Promise((resolve, reject) => {
                xysCefToJavaScripts.driveLocalHardware(dllParams).then((returnVale) => {
                    resolve(returnVale)
                })
            })
        } else {
            const frame = chrome?.webview?.hostObjects?.Bridge || ''; // 新版浏览器
            return new Promise((resolve, reject) => {
                if (frame) {
                    frame.DynamicLoadingDLL(dllParams)
                        .then(
                            data => {
                                resolve(data);
                            },
                            err => {
                                console.log(err);
                                reject(err);
                            }
                        )
                } else {
                    fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?' + '&input=' + dllParams, {
                        jsonpCallback: 'JsonCallback',
                        timeout: 500000,
                    }).then(function (response) {
                        return response.json()
                    }).then(function (json) {
                        resolve(json);
                    }).catch(function (err) {
                        reject(err);
                    })
                }
            })
        }
    },
    GetDateTime() {
        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 time = year + "-" + month + "-" + day;
        return time;
    }
}

export {
    Util,
    ArraySome,
    Aes,
    Keup,
    dayFormat,
    timeFormat,
    dateFormat,
    hourFormat,
    Reg,
    temperature,
    INSUYBUtil,
    speech,
    BankUtil,
    getIpv4
};
