var opt0 = ["请选择", "请选择"];
var s = ["province", "city"];
var isOver=false;
var biam = "utf-8";
var file,syslanguage,CustomLanguageLatticeSwitch,faceaddguropid;
var reg = /^[0-9a-zA-Z]+$/;
var userinfos = "Basic " + $.cookie("userInfo");
var issupot,facegroupsum,personperfacesum,personByAllFaceGroup,personImageSizecose,personImageSize,personresolutionwidth,personresolutionheight,efaultwidth,efaultheight;
$(document).ready(function() {
    maxface();
    getsyslangue();
    getcustomswitch();
    var $faceaddPeopleModal = $("#addPeopleModal input[name='extData']").val();
     faceaddguropid = $("#addPeopleModal input[name='dataId']").val();
    if($faceaddPeopleModal){
        $("#inputfileimage").addClass("choosepeopleicon");
        document.getElementById("inputfileimage").setAttribute("src",$faceaddPeopleModal);
        $("#changeimage").show();
        //base64的图片转为二进制的图片
        var tobold = "data:image/jpeg;base64," + $faceaddPeopleModal;
        var imgName = "scenecollect";
        var blob = dataURLtoBlob(tobold);
        file = blobToFile(blob, imgName); //blod和filename
    }
    if (sessionStorage.getItem("playstyle")== "ActiveX") {
        $("#zhupaimode").show()
    }else {
        $("#zhupaimode").hide()
    }
    $("#faceInfo_add_sex_slct,#faceInfo_add_certificateType_slct,#faceInfo_add_country_slct,#province,#city,#faceInfo_add_must_slct,#faceInfo_add_accessrightsmode_slct1").select2({
        minimumResultsForSearch: -1
    });

    $("#faceInfo_add_birth_b").datepicker({
        todayHighlight: true, //设置当天日期高亮
        format: 'yyyy-mm-dd',
        autoclose: true,
        language: 'zh-CN',
    });
    /**
     * 省市切换
     */
    $("#province").change(function() {
      change(1, "")
    });
    /**
     * 区域切换
     */
    $("#city").change(function() {
        change(2, "")
    });
    /**
     * 默认省市切换
     */
    change(0, "");
    /**
     * 表单校验
     */
    var datumInfoFormValidate = $("#addPeopleForm").validate({
        ignore: 'input[type=hidden],select[readonly]', //ignore:数据忽略
        rules: {
            faceInfo_add_name: {
                required: true,
            },
        },
        messages: {
            faceInfo_add_name: {
                required: "不能为空",
            },
        },
        submitHandler: function(form) { //保存
            var Address = "";
            if (JudgeTextLength($("#faceInfo_per_pwd").val(), biam) >= 6) {
                $("#faceInfo_per_pwd").focus();
                $("#faceInfo_per_pwd").val("");
                bootoast({
                    message: "密码最大长度不能超过6位数!",
                    type: 'danger',
                    position: 'bottom-center',
                    timeout: true,
                    animationDuration: 3000,
                    dismissable: true
                });
                return false;
            }
            if (JudgeTextLength($("#faceInfo_add_name").val(), biam) >= 32) {
                $("#faceInfo_add_name").focus();
                $("#faceInfo_add_name").val("");
                bootoast({
                    message: "人员信息名称超过32个字符!",
                    type: 'danger',
                    position: 'bottom-center',
                    timeout: true,
                    animationDuration: 3000,
                    dismissable: true
                });
                return false
            }
            if (JudgeTextLength($("#faceInfo_uniqueid").val(), biam) >= 32) {
                $("#faceInfo_uniqueid").focus();
                $("#faceInfo_uniqueid").val("");
                bootoast({
                    message: "人员信息ID超过32个字符!",
                    type: 'danger',
                    position: 'bottom-center',
                    timeout: true,
                    animationDuration: 3000,
                    dismissable: true
                });
                return false
            }
            if ($("#faceInfo_add_ID").val() != "") {
                if (!reg.test($("#faceInfo_add_ID").val())) {
                    $("#faceInfo_add_ID").focus();
                    bootoast({
                        message: "证件号码只能输入字母和数字!",
                        type: 'danger',
                        position: 'bottom-center',
                        timeout: true,
                        animationDuration: 3000,
                        dismissable: true
                    });
                    return false
                }
            }

            if (sessionStorage.getItem("language") == "zh") { //中文
                Address = $("#province").val() + "#" + $("#city").val();
                var Country = $("#faceInfo_add_country_slct").val();
            } else if (sessionStorage.getItem("language") == "tw") {//繁体中文
                Address = $("#faceInfo_add_address").val() + "#";
                var Country = "";
            } else { //其他语言
                Address = $("#faceInfo_add_address").val() + "#";
                var Country = $("#faceInfo_add_country_slct").val();
            }

            var af = $("#faceInfo_add_sex_slct").val();
            var ae = $("#faceInfo_add_certificateType_slct").val();
            var ag = $("#faceInfo_add_birth_b").val().replace(/-/g, "");
            var ah = "<?xml version='1.0' encoding='UTF-8' ?>" +
                "<PersonInfo><PersonID>" + 0 + "</PersonID>" +
                "<Name>" + af + "</Name>" +
                "<Sex>" + $("#faceInfo_add_sex_slct").val() + "</Sex>" +
                "<CertificateType>" + ae + "</CertificateType>" +
                "<CertificateID>" + $("#faceInfo_add_ID").val() + "</CertificateID>" +
                "<Country>" + Country + "</Country>" +
                "<Address>" + Address + "</Address>" +
                "<Birthday>" + ag + "</Birthday>" +
                "<UniqueID>" + $("#faceInfo_uniqueid").val() + "</UniqueID>" +
                "</PersonInfo>";
            Warehousingverification(ah);//请求
            if (isOver) { //校验通过
                if (file == '') {
                    bootoast({
                        message: "请选择入库图片!",
                        type: 'danger',
                        position: 'bottom-center',
                        timeout: true,
                        animationDuration: 3000,
                        dismissable: true
                    });
                    return false
                }
                addPersonInfoAndFaceImage();

            }
        },

    });
    /**
     * 图片选取
     */
    $("#inputfileimage").click(function () {
        document.getElementById("inputfile").click();
    });

    $("#changeimage").click(function () {
        document.getElementById("inputfile").click();
    });

    $("#inputfile").change(function () {

        //获取dom元素
        var fileButton = document.getElementById("inputfile");
        //读取图片
         file = fileButton.files[0];
        var fileReader = new FileReader();
        if(file!=null){
            var size=file.size;

            if(size>personImageSizecose){
                bootoast({
                    message: "图片大小过大!",
                    type: 'danger',
                    position: 'bottom-center',
                    timeout: true,
                    animationDuration: 3000,
                    dismissable: true
                });
                return false;
            }
            var filetype=file.type;

            if(filetype!="image/jpeg"){
                bootoast({
                    message: "只支持JPG格式!",
                    type: 'danger',
                    position: 'bottom-center',
                    timeout: true,
                    animationDuration: 3000,
                    dismissable: true
                });
                return false;
            }
        }

        //注册加载完整后的事件
        fileReader.onload = function (e) {
            //获取图片的base64的编码
            var imgUrl = e.target.result;

            var image = new Image();

            image.onload=function(){

                var width = image.width;
                var height = image.height;

                if((width>personresolutionwidth)||(height>personresolutionheight)){
                    bootoast({
                        message: "上传图片分辨率不合格,支持最大图片分辨率(736P)",
                        type: 'danger',
                        position: 'bottom-center',
                        timeout: true,
                        animationDuration: 3000,
                        dismissable: true
                    });
                    return false;
                }
                $("#inputfileimage").addClass("choosepeopleicon");
                document.getElementById("inputfileimage").setAttribute("src",imgUrl);
                $("#changeimage").show();
            };
            image.src= imgUrl;

        };
        //获取图片
        if(file!=null) {
            fileReader.readAsDataURL(file);
        }
    });

});

/**
 * 入库校验
 * @param ag
 * @constructor
 */

function Warehousingverification(ag) {
    var ae = config.baseUrl  + "/FaceGroup/CheckPersonInfo";
    $.ajax({
        type: "PUT",
        url: ae,
        processData: false,
        async: false,
        data: ag,
        beforeSend: function (ah) {
            ah.setRequestHeader("If-Modified-Since", "0");
            if (window.localStorage.getItem("Token") != "default") {
                ah.setRequestHeader("TOKEN", window.localStorage.getItem("Token"))
            }
        }, success: function (ai, ak, aj) {
            var ah = $(ai).find("ResponseStatus").eq(0).find("statusCode").eq(0).text();
            if (0 == ah) {
                isOver = true
            }
        },
        error: function (af, ag, ae) {
        }
    })
}


/**
 * 最大最小人人脸获取
 */
function maxface() {
    $.ajax({
        url: config.baseUrl  + "/FaceRecognition/Ability",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function (ae) {
            ae.setRequestHeader("If-Modified-Since", "0");
            if (window.localStorage.getItem("Token") != "default") {
                ae.setRequestHeader("TOKEN", window.localStorage.getItem("Token"))
            }
        },
        success: function (ae, ag, af) {
            issupot = $(ae).find("RecognitionAbility").eq(0).find("isSupportFaceReco").text(); //是否支持人脸识别
            facegroupsum = $(ae).find("RecognitionAbility").eq(0).find("FaceGroupSum").text(); //脸库个数
            personperfacesum = $(ae).find("RecognitionAbility").eq(0).find("PersonPerFaceGroup").text();//脸库最大人数
            personByAllFaceGroup = $(ae).find("RecognitionAbility").eq(0).find("PersonByAllFaceGroup").text();//所有脸库最大人数
            personImageSizecose = $(ae).find("RecognitionAbility").eq(0).find("PersonImageSize").text(); //分辨率
            personImageSize = personImageSizecose / 1024 + "KB";
            personresolutionwidth = $(ae).find("RecognitionAbility").eq(0).find("MaxResolution").eq(0).find("Width").text(); //图片最大宽度
            personresolutionheight = $(ae).find("RecognitionAbility").eq(0).find("MaxResolution").eq(0).find("Height").text();//图片最大高度
            efaultwidth = $(ae).find("RecognitionAbility").eq(0).find("DefaultResolution").eq(0).find("Width").text();//图片默认宽度
            efaultheight = $(ae).find("RecognitionAbility").eq(0).find("DefaultResolution").eq(0).find("Height").text()//图片默认宽度
            $("#maxtip").text("支持最大尺寸（"+personImageSize+"）,"+"支持最大分辨率（"+personresolutionwidth+"）");
        },
        error: function (af, ag, ae) {

        }
    })
}


/**
 * 单个人脸和图片一起添加 使用表单提交 目录提交
 */
function addPersonInfoAndFaceImage() {
    var Address = $("#province").val() + "#" + $("#city").val();
    var addsex = $("#faceInfo_add_sex_slct").val();
    var addtype = $("#faceInfo_add_certificateType_slct").val();
    var Birthday = $("#faceInfo_add_birth_b").val().replace(/-/g, "");
    var name = $("#faceInfo_add_name").val();
    var CertificateID = $("#faceInfo_add_ID").val();
    var Country = $("#faceInfo_add_country_slct").val();
    var UniqueID = $("#faceInfo_uniqueid").val();
    var Password=$("#faceInfo_per_pwd").val();

    if (sessionStorage.getItem("playstyle")== "ActiveX") {
        var xml = "<?xml version='1.0' encoding='UTF-8' ?><StringToLattice_In Version='1.0'>" +
            "<SourceText>" + name + "</SourceText>" +
            "<FontName></FontName>" +
            "<FontSize></FontSize>" +
            "<FontBold></FontBold>" +
            "<FontItalic></FontItalic>" +
            "<FontUnderline></FontUnderline>" +
            "<FontStrikeOut></FontStrikeOut>" +
            "</StringToLattice_In>";
        var returnxml = parseXmlFromStr(setlattice(xml));
        if (syslanguage == "Korean" || syslanguage == "Japanese"||(syslanguage == "Custom"&&CustomLanguageLatticeSwitch=="true")) {
            var ImageWidth = $(returnxml).find('ImageWidth').text();
            var ImageHeight = $(returnxml).find('ImageHeight').text();
            var ImageSize = $(returnxml).find('ImageSize').text();
            var ImageData = $(returnxml).find('ImageData').text();
        } else {
            var ImageWidth = 0;
            var ImageHeight = 0;
            var ImageSize = 0;
            var ImageData = 0;
        }
    }else{
        var ImageWidth = 0;
        var ImageHeight = 0;
        var ImageSize = 0;
        var ImageData = 0;
    }

    if (window.FormData) {

        var formData = new FormData();
        // 建立一个upload表单项，值为上传的文件
        formData.append('IgnoreError', false);
        formData.append('Name', name);
        formData.append('Sex', addsex);
        formData.append('CertificateType', addtype);
        formData.append('CertificateID', CertificateID);
        formData.append('GroupID', faceaddguropid);
        formData.append('Country', Country);
        formData.append('Address', Address);
        formData.append('Birthday', Birthday);
        formData.append('FaceImageID', 1);
        formData.append('UniqueID', UniqueID);
        formData.append('Password', Password);
        formData.append('ImageLatticeData', ImageData);
        formData.append('ImageLatticeLength', ImageSize);
        formData.append('Width', ImageWidth);
        formData.append('Height', ImageHeight);
        formData.append('file', file);
        var xhr = new XMLHttpRequest();
        if (xhr.upload) {
            // 文件上传成功或是失败
            xhr.onreadystatechange = function (e) {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                    }
                }
            };
            xhr.open('POST', '/FaceGroup/AddPersonInfoAndFaceImage');
            xhr.setRequestHeader("Authorization", userinfos);
            if(window.localStorage.getItem("Token")!="default"){
                xhr.setRequestHeader("TOKEN", window.localStorage.getItem("Token"))
            }
            // 定义上传完成后的回调函数
            xhr.onload = function () {
                if (xhr.status === 200) {
                    var xml = this.response;
                    var xmlDoc = parseXmlFromStr(xml);
                    var statusflg = $(xmlDoc).find('ResponseStatus').eq(0).find('statusCode').eq(0).text();
                    if (statusflg == 0) {
                        file = '';
                        bootoast({
                            message: "创建成功",
                            type: 'success',
                            position: 'bottom-center',
                            timeout: true,
                            animationDuration: 3000,
                            dismissable: true
                        });
                    } else {
                        statuscode(statusflg)
                    }
                } else {
                    bootoast({
                        message: "请求失败",
                        type: 'danger',
                        position: 'bottom-center',
                        timeout: true,
                        animationDuration: 3000,
                        dismissable: true
                    });
                    return false;
                }

            };
            xhr.send(formData);
        }
    }


}

function getsyslangue() {
    $.ajax({
        url:  config.baseUrl  + "/System/Language",
        type: "get",
        async: false,//同步
        timeout: 15000,
        beforeSend: function (xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
            if (window.localStorage.getItem("Token") != "default") {
                xhr.setRequestHeader("TOKEN", window.localStorage.getItem("Token"))
            }
        },
        success: function (xmlDoc, textStatus, xhr) {
            syslanguage = $(xmlDoc).find('SystemLanguageConfig').find('Language').text();
        },
        error: function (xhr, textStatus, errorThrown) {
        }
    });
}


function getcustomswitch() {
    $.ajax({
        url:  config.baseUrl  +"/System/1/CustomLanguageLatticeSwitch",
        type: "get",
        async: false,//同步
        timeout: 15000,
        beforeSend: function (xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
            if (window.localStorage.getItem("Token") != "default") {
                xhr.setRequestHeader("TOKEN", window.localStorage.getItem("Token"))
            }
        },
        success: function (xmlDoc, textStatus, xhr) {

            CustomLanguageLatticeSwitch=$(xmlDoc).find('CustomLanguageLatticeSwitch').find('Enable').text();
        },
        error: function (xhr, textStatus, errorThrown) {
        }
    });
}



