var issOnlineUrl = "http://127.0.0.1:24010/ZKIDROnline";
var browserFlag = getBrowserType();
/*
$().ready(function(){
	$(document).off("DOMNodeInserted","#cert_message_type");
	$("#cert_message_type").on("DOMNodeInserted",function(e){
		openMessage($("#cert_message_type").text(), $("#cert_message").text());
	});
});
*/
//身份证
//includeScript("baseISSObject.js", function(){
//includeScript("baseISSOnline.js", function(){
var setting = {
    Cert: {
        callBack: function (result) {
            setCertificateData(result);
        },
        select: "#button_readID"
    },
    Methods: {
        showMessage: function (type, message) {
            $("#cert_message").text(message);
            $("#cert_message_type").text(msgType[type]);
        },
        downloadDrive: function () {
            $.jBox.closeTip();
            messageBox({
                messageType: "confirm", text: "请安装相关硬件驱动！点击确定下载驱动。",
                callback: function (result) {
                    if (result) {
                        window.location.href = "middleware/ZKIDROnline.exe";
                    }
                    closeMessage();
                }
            });
        }
    }
}
createISSonlineDevice(setting);
//});
//});

function setCertificateData(result) {
    //$("#birthDay").val(result.Certificate.Birthday.replace(/\./g,"-").substr(0,10));
    var birthday = result.Certificate.Birthday;
    $("#birthDay").val(birthday.substring(0, 4) + "-" + birthday.substring(4, 6) + "-" + birthday.substring(6));
    var returnAge = jsGetAge($("#birthDay").val());
    $("#age").val(returnAge);
    $("#idCard").val(result.Certificate.IDNumber);
    queryUserInfoBySocialNo();
    //$("#issuedValidDate").val(result.Certificate.IssuedData+"-"+result.Certificate.ValidDate);
    // imgData =result.Certificate.Base64Photo;
    // $("#id_img_pers").attr("src","data:image/jpg;base64,"+imgData);
    // $("#personIdPhoto").val(imgData);
    // $("#personPhoto").val("");
    $("#userName").val(result.Certificate.Name);
    if (result.Certificate.Sex == "男") {
        $("#gender").val(1);
        $('#gender').selectpicker('refresh');
    } else if (result.Certificate.Sex == "女") {
        $("#gender").val(2);
        $('#gender').selectpicker('refresh');
    }
    //$("#nation").val(result.Certificate.Nation);
    $("#address").val(result.Certificate.Address);
    try{
        $("#imageIdCard").val(result.Certificate.Base64Photo);
        setNation(result.Certificate.Nation);
        $("#nationToUpload").val(result.Certificate.Nation);
        $("#idIssued").val(result.Certificate.IDIssued);
        $("#issuedData").val(result.Certificate.IssuedData);
        $("#validDate").val(result.Certificate.ValidDate);

    }catch (e) {
        
    }
}

/**
 * 设置民族
 */
function setNation(nation) {
    var nationKey=null;
    if(nation=="阿昌"){
        nationKey="AC";
    }else if(nation=="白"){
        nationKey="BA";
    }else if(nation=="崩龙"){
        nationKey="BE";
    }else if(nation=="布朗"){
        nationKey="BL";
    }else if(nation=="保安"){
        nationKey="BN";
    }else if(nation=="布依"){
        nationKey="BY";
    }else if(nation=="穿青人"){
        nationKey="CQ";
    }else if(nation=="朝鲜"){
        nationKey="CX";
    }else if(nation=="傣"){
        nationKey="DA";
    }else if(nation=="侗"){
        nationKey="DO";
    }else if(nation=="独龙"){
        nationKey="DR";
    }else if(nation=="达斡尔"){
        nationKey="DU";
    }else if(nation=="东乡"){
        nationKey="DX";
    }else if(nation=="鄂温克"){
        nationKey="EW";
    }else if(nation=="京"){
        nationKey="GI";
    }else if(nation=="仡佬"){
        nationKey="GL";
    }else if(nation=="高山"){
        nationKey="GS";
    }else if(nation=="汉"){
        nationKey="HA";
    }else if(nation=="哈尼"){
        nationKey="HN";
    }else if(nation=="回"){
        nationKey="HU";
    }else if(nation=="赫哲"){
        nationKey="HZ";
    }else if(nation=="基诺"){
        nationKey="JN";
    }else if(nation=="景颇"){
        nationKey="JP";
    }else if(nation=="柯尔克孜"){
        nationKey="KG";
    }else if(nation=="哈萨克"){
        nationKey="KZ";
    }else if(nation=="珞巴"){
        nationKey="LB";
    }else if(nation=="拉祜"){
        nationKey="LH";
    }else if(nation=="黎"){
        nationKey="LI";
    }else if(nation=="傈僳"){
        nationKey="LS";
    }else if(nation=="满"){
        nationKey="MA";
    }else if(nation=="门巴"){
        nationKey="MB";
    }else if(nation=="蒙古"){
        nationKey="MG";
    }else if(nation=="苗"){
        nationKey="MI";
    }else if(nation=="仫佬"){
        nationKey="ML";
    }else if(nation=="毛难"){
        nationKey="MN";
    }else if(nation=="怒族"){
        nationKey="NU";
    }else if(nation=="纳西"){
        nationKey="NX";
    }else if(nation=="鄂伦春"){
        nationKey="OR";
    }else if(nation=="普米族"){
        nationKey="PM";
    }else if(nation=="羌"){
        nationKey="QI";
    }else if(nation=="其他"){
        nationKey="QT";
    }else if(nation=="俄罗斯"){
        nationKey="RS";
    }else if(nation=="畲"){
        nationKey="SH";
    }else if(nation=="撒拉"){
        nationKey="SL";
    }else if(nation=="水"){
        nationKey="SU";
    }else if(nation=="塔吉克"){
        nationKey="TA";
    }else if(nation=="土家"){
        nationKey="TJ";
    }else if(nation=="塔塔尔"){
        nationKey="TT";
    }else if(nation=="土"){
        nationKey="TU";
    }else if(nation=="维吾尔"){
        nationKey="UG";
    }else if(nation=="乌孜别克"){
        nationKey="UZ";
    }else if(nation=="佤"){
        nationKey="VA";
    }else if(nation=="外国血统"){
        nationKey="WG";
    }else if(nation=="锡伯"){
        nationKey="XB";
    }else if(nation=="瑶"){
        nationKey="YA";
    }else if(nation=="裕固"){
        nationKey="YG";
    }else if(nation=="彝"){
        nationKey="YI";
    }else if(nation=="藏"){
        nationKey="ZA";
    }else if(nation=="壮"){
        nationKey="ZH";
    }
    $('#nation').selectpicker('val', nationKey);
    $('#nation').selectpicker('refresh');
}


function getRandomNum() {
    var random = parseInt(Math.random() * 10000);
    return random;
}

//消息控件的使用类型的类
var msgType =
    {
        info: "info",
        success: "success",
        warning: "warning",
        error: "error",
        loading: "loading"
    };

function getBrowserType() {
    var browserFlag = "";
    //是否支持html5的cors跨域
    if (typeof(Worker) !== "undefined") {
        browserFlag = "html5";
    }
    //此处判断ie8、ie9
    else if (navigator.userAgent.indexOf("MSIE 7.0") > 0 || navigator.userAgent.indexOf("MSIE 8.0") > 0 || navigator.userAgent.indexOf("MSIE 9.0") > 0) {
        browserFlag = "simple";
    }
    else {
        browserFlag = "upgradeBrowser";//当前浏览器不支持该功能,请升级浏览器
    }
    return browserFlag;
}


function openMessage(type, text, ptimeout) {
    text = (text == "" ? null : text);
    var timeout = 1000;
    if (type == msgType.warning || type == msgType.info)//警告
    {
        timeout = 3000;
    }
    else if (type == msgType.success)//成功
    {

        text = (text && text != null ? text : "操作成功");//${common_op_succeed}:操作成功
        var num = strlen(text) / 30;
        num = num > 8 ? 8 : num;
        timeout = Math.ceil(num) * timeout;//动态判断显示字符数的长度来延长显示时间
    }
    else if (type == msgType.error)//失败
    {
        text = (text && text != null) ? text : "操作失败";//${common_op_failed}:操作失败，程序出现异常
        timeout = 3000;
    }
    else if (type == msgType.loading)//处理中
    {
        timeout = 0;//当为'loading'时，timeout值会被设置为0，表示不会自动关闭。
        text = text && text != null ? text : "处理中";//${common_op_processing}:处理中
    }
    var width = strlen(text) * 6.1 + 45;//按字符计算宽度
    timeout = ptimeout ? ptimeout : timeout;
    $.jBox.tip(text, type, {timeout: timeout, width: (width > 400 ? 400 : "auto")});//设定最大宽度为400
}


function closeMessage(timeout) {
    timeout = timeout ? timeout : 1000;
    window.setTimeout("$.jBox.closeTip();", timeout);//设定最小等待时间
}

function strlen(str) {
    var len = 0;
    if (str != null) {
        for (var i = 0; i < str.length; i++) {
            var c = str.charCodeAt(i);
            if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
                len++;
            }
            else {
                len += 2;
            }
        }
    }
    return len;
}

function messageBox(paramsJson) {

    this.messageType = paramsJson.messageType ? $.trim(paramsJson.messageType) : "confirm";
    this.types = "";
    if (paramsJson.type) {
        this.typeArray = paramsJson.type.split(" ");
        for (var i = 0; i < this.typeArray.length; i++) {
            this.types += this.typeArray[i] + " ";
        }
    }
    switch (this.messageType) {
        case "confirm":
            $.jBox.confirm(paramsJson.text, "提示", function (v, h, f) {
                if (v == "ok") {
                    paramsJson.callback(true);
                }
            });
            break;
    }
}


/**
 * 根据出生日期算出年龄
 * @param strBirthday
 * @returns {number}
 */
function jsGetAge(strBirthday) {
    var returnAge;
    var strBirthdayArr = strBirthday.split("-");
    var birthYear = strBirthdayArr[0];
    var birthMonth = strBirthdayArr[1];
    var birthDay = strBirthdayArr[2];
    d = new Date();
    var nowYear = d.getFullYear();
    var nowMonth = d.getMonth() + 1;
    var nowDay = d.getDate();

    if (nowYear == birthYear) {
        returnAge = 0;//同年 则为0岁
    }
    else {
        var ageDiff = nowYear - birthYear; //年之差
        if (ageDiff > 0) {
            if (nowMonth == birthMonth) {
                var dayDiff = nowDay - birthDay;//日之差
                if (dayDiff < 0) {
                    returnAge = ageDiff - 1;
                }
                else {
                    returnAge = ageDiff;
                }
            }
            else {
                var monthDiff = nowMonth - birthMonth;//月之差
                if (monthDiff < 0) {
                    returnAge = ageDiff - 1;
                }
                else {
                    returnAge = ageDiff;
                }
            }
        }
        else {
            returnAge = -1;//返回-1 表示出生日期输入错误 晚于今天
        }
    }
    return returnAge;//返回周岁年龄
}


/**
 * 身份证号有变化后查询病人信息
 */
function queryUserInfoBySocialNo() {
    var idCard = $("#idCard").val();
    if (idCard.length == 18) {
        $.ajax({
            type: "GET",
            url: '/thmz/getBySocialNo?socialNo=' + idCard,
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
            success: function (res) {
                if (res == '401' || res == 401) {
                    window.location.href = '/thmz/login/view'
                    return;
                }
                if (res.code == 0) {
                    if (res.data != null && res.data.length > 0) {
                        fitPatient(res);
                    } else {
                        var birthday = idCard.substring(6, 14);
                        birthday = birthday.substring(0, 4) + "-" + birthday.substring(4, 6) + "-" + birthday.substring(6);
                        $("#birthDay").val(birthday);
                        var returnAge = jsGetAge(birthday);
                        $("#age").val(returnAge);
                        var gender = idCard.substring(16, 17);
                        if (gender % 2 == 0) {
                            $("#gender").val(2);
                        } else {
                            $("#gender").val(1);
                        }
                        $('#gender').selectpicker('refresh');
                    }
                } else {
                    new PNotify({
                        title: '错误提示',
                        text: res.message,
                        type: 'error',
                        hide: true,
                        styling: 'bootstrap3'
                    });
                }
            }
        });

    }
}



/**
 * 查询患者信息
 */
function fitPatient(res) {
    if (res.data.length > 0) {
        $("#patientModal").modal();
        $("#patientTable").html(null);
        for (var i = 0; i < res.data.length; i++) {
            var gender = '未知';
            if (res.data[i].sex == 1) {
                gender = '男';
            } else if (res.data[i].sex == 2) {
                gender = '女';
            }
            var icCardNo = res.data[i].icCardNo;
            if (icCardNo == null || icCardNo == "null") {
                icCardNo = "";
            }
            var phoneNo = res.data[i].phoneNo;
            if (phoneNo == null || phoneNo == "null") {
                phoneNo = "";
            }
            var birthDay = format(res.data[i].birthDay, "yyyy-MM-dd");
            if (birthDay == null || birthDay == "null") {
                birthDay = "";
            }
            var socialNo = res.data[i].socialNo;
            if (socialNo == null || socialNo == "null") {
                socialNo = "";
            }
            $("<tr data-target='" + res.data[i].patientId + "'><td>" + res.data[i].patientId + "</td><td>" + res.data[i].name + "</td><td>" + gender + "</td><td>" + icCardNo + "</td><td>" + phoneNo + "</td><td>" + birthDay + "</td><td>" + socialNo + "</td></tr>").appendTo("#patientTable").bind('click', function () {
                $("#patientModal").modal("hide");
                fillPatinet($(this).attr("data-target"));
            });
        }
    }
}

