//个人信息初始化
function load(){
    layer.load(3);
    $.ajax({
        url: "/personal/getPresonalMessage",
        type: "get",
        data: {},
        headers: {"token": localStorage.getItem("token")},
        dataType: "json",
        success: (data) => {
            if(data.msg == "200"){
                $(".name_div_val").find("div").html(data.data.name);
                $(".buy_account").html("充值人：&nbsp;&nbsp;&nbsp;&nbsp;" + data.data.name);
                $(".phoen_left").find(".phone_val").html(data.data.phone );
                $(".account_div .blance_content").find("p").html(data.data.balanceOf);
                $(".permissions_div .blance_content").find("p").html(data.data.offerNum);
                $(".headpir_img").attr("src", data.data.headpir);
                //首页报价单权限余额 账户信息业务无用
                $(".offer_num_div .balance_of_fount").find("p").html(data.data.offerNum);
                //收支明细
                $(".bottom_content div").remove();
                $.each(data.payments.data, (index, item) => {
                    var totalFee = item.total_fee;//付款金额
                    var refund_fee = item.refund_fee == undefined ? 0 : item.refund_fee;//退款金额
                    $(".bottom_content").append("<div class=\"content_div_font\" uuid=\""+ item.uuid +"\">\n" +
                        "                    <div class=\"date_detail\">"+ item.jdrq +"</div>\n" +
                        "                    <div class=\"content_detail\">"+ item.offer_name +"</div>\n" +
                        "                    <div class=\"amount_detail\">￥"+ (totalFee - refund_fee) +"</div>\n" +
                        "                </div>");
                });
            }
            layer.closeAll("loading");
        },
        error: () => {
            layer.closeAll("loading");
            layer.alert("网络错误 请联系管理员");
        }
    });
}
//充值弹框
function topUp(){
    topUpNum();//次数渲染 余额渲染
    layer.open({
        type: 1,
        title: false,
        shadeClose: true,
        anim: 1,
        closeBtn: 0,
        area: ['auto', '700px'],
        content: $(".top_up_div"),
        end: () => {
            clearInterval(runInterval);
            $("#qrcode").find("img").remove();
            $("input[name=totalFee]").val("");
            runInterval = null;
        },
        cancel: () => {
            clearInterval(runInterval);
            $("#qrcode").find("img").remove();
            $("input[name=totalFee]").val("");
            runInterval = null;
        }
    });
}
//权限购买弹框
function buyPermissions(){
    getByNumber();
    layer.open({
        type: 1,
        title: false,
        shadeClose: true,
        anim: 1,
        closeBtn: 0,
        area: ['auto', '700px'],
        content: $(".quotation_number"),
        end: () => {
            clearInterval(offerNumPayRunInterval);
            offerNumPayRunInterval = null;
            getByNumber();
            gysTopUpNum();
        },
        cancel: () => {
            clearInterval(offerNumPayRunInterval);
            offerNumPayRunInterval = null;
            getByNumber();
            gysTopUpNum();
        }
    });
}
//充值自定义切换
function selectAmout(obj){
    if($(obj).hasClass("select_amount_val_click")){
        $(obj).removeClass("select_amount_val_click");
    } else {
        $(".select_amount_val").removeClass("select_amount_val_click");
        $(obj).addClass("select_amount_val_click");
    }
}
//选择支付方式
function selectPay(obj){
    $(".pay_div_mode").removeClass("select_pay_click");
    $(".pay_div_mode").find("div").html(" ");
    $(obj).addClass("select_pay_click");
    $(".select_pay_click").find("div").html("<i class=\"layui-icon\">&#xe605;</i>")
}
//生成二维码
function onblurEle(){
    // layer.load(3);
    var totalFee = 0;
    //判断是否选择给定的金额
    if(typeof($(".top_up_div .select_amount_val_click").attr("value")) != "undefined"){
        totalFee = $(".top_up_div .select_amount_val_click").attr("value");
    }
    //获取输入的自定义金额
    if($("input[name=totalFee]").val() != null && $("input[name=totalFee]").val() != ""){
        totalFee = $("input[name=totalFee]").val();
    }
    //判断金额不能小于1
    if(totalFee < 1){
        layer.msg("金额不能小于1", {icon: 2});
        layer.closeAll("loading");
        return false;
    }
    //非空验证
    if(totalFee == 0){
        layer.msg("请填写或选择金额", {icon: 2});
        layer.closeAll("loading");
        return false;
    }
    $("#qrcode").find("img").remove();
    clearInterval(runInterval);
    runInterval = null;
    $.ajax({
        url: "/wxpay/wxpaySupplierBalance",
        type: "get",
        data: {
            "price": totalFee
        },
        headers: {"token": localStorage.getItem("token")},
        dataType: "json",
        success: (data) => {
            var qrcode = new QRCode(document.getElementById("qrcode"), {    // 显示二维码的元素或该元素的 ID
                text: data.code_url,   // 内容可以是文字，链接，邮箱
                width: 120,          //设置宽度
                height: 120,        // 设置高度
                colorDark : "#000",        // 设置前景色
                colorLight : "#fff",        // 设置背景色
                // correctLevel : QRCode.CorrectLevel.L       // 设置容错级别，上面有介绍
            });
            rotationTrainingStatus(data.out_trade_no);
            layer.closeAll("loading");
        },
        error: () => {
            layer.alert("服务器异常，请联系管理员", {icon: 2});
            layer.closeAll("loading");
        }
    });
}
//生成二维码
function qrCode(){
    layer.load(3);
}
//轮训查询状态
var runInterval; //定时任务
function rotationTrainingStatus(uuid){
    runInterval = setInterval(function (){
        $.ajax({
            url: "/wxpay/getTopUp",
            type: "get",
            data: {
                "uuid": uuid
            },
            headers: {"token": localStorage.getItem("token")},
            dataType: "json",
            success: (data) => {
                if(data.data == 1){
                    clearInterval(runInterval);
                    layer.closeAll();
                    parent.layer.msg("充值成功", {icon: 1});
                    load();
                }
            },
            error: () => {
                layer.alert("服务器异常，请联系管理员", {icon: 2});
                layer.closeAll("loading");
            }
        });
    }, 1000)
}
//查询报价单单价
function getByNumber(){
    layer.load(3);
    $.ajax({
        url: "/personal/getByNumber",
        type: "get",
        data: {},
        headers: {"token": localStorage.getItem("token")},
        dataType: "json",
        success: (data) => {
            $(".price_calculate").html(data.data.power_unit);
            unitPrice = data.data.power_unit;
            topUpNum();//次数渲染 余额渲染
            eachNumberAmout(); //次数余额
            layer.closeAll("loading");
        },
        error: () => {
            layer.alert("服务器异常，请联系管理员", {icon: 2});
            layer.closeAll("loading");
        }
    });
}
//监听输入框
function getValue(obj){
    var num = $(obj).val();
    $("#qrcode_ok").find("img").remove();
    $(".price_calculate").html((Number(num * unitPrice).toFixed(2)));
}
//支付方式
function payType(obj){
    var offerNum = $("input[name=offerNum]").val();//次数
    var offerNumSelect = $(".quotation_number .select_amount_val_click").attr("value");//次数
    if(offerNum == "" && typeof(offerNumSelect) == "undefined"){
        layer.msg("次数不能为空，请输入或者选择购买次数");
        return false;
    }
    $(".quotation_number .pay_div_mode").removeClass("select_pay_click");
    $(".quotation_number .pay_div_mode").find("div").html(" ");
    $(obj).addClass("select_pay_click");
    $(".select_pay_click").find("div").html("<i class=\"layui-icon\">&#xe605;</i>");
    var name = $(obj).find("span").text();
    if(name == "余额支付"){
        $(".blance_button").show();
        $("#qrcode_ok").find("img").remove();
        clearInterval(offerNumPayRunInterval);
    } else if(name == "微信支付"){
        $(".blance_button").hide();
        offerNumPay();
    }
}
//购买次数生成二维码
var offerNumPayRunInterval = null;
function offerNumPay(){
    layer.load(3);
    clearInterval(offerNumPayRunInterval);
    offerNumPayRunInterval = null;
    //如果存在二维码则不执行下面信息
    if($("#qrcode_ok").html().indexOf("<img") != -1){
        return false;
    }
    var offerNum = $("input[name=offerNum]").val();//次数
    var offerNumSelect = $(".select_amount_val_click").attr("value");//次数
    var numOffer = 0;
    if(typeof(offerNumSelect) != "undefined"){
        numOffer = offerNumSelect;
    }
    if(offerNum != "" && offerNum != null){
        numOffer = offerNum;
    }
    $.ajax({
        url: "/wxpay/wxpaySupplierOfferNum",
        type: "get",
        data: {
            "offerNum": numOffer
        },
        headers: {"token": localStorage.getItem("token")},
        dataType: "json",
        success: (data) => {
            var qrcode = new QRCode(document.getElementById("qrcode_ok"), {    // 显示二维码的元素或该元素的 ID
                text: data.code_url,   // 内容可以是文字，链接，邮箱
                width: 120,          //设置宽度
                height: 120,        // 设置高度
                colorDark : "#000",        // 设置前景色
                colorLight : "#fff",        // 设置背景色
                // correctLevel : QRCode.CorrectLevel.L       // 设置容错级别，上面有介绍
            });
            rotationTrainingOfferNum(data.out_trade_no);
            layer.closeAll("loading");
        },
        error: () => {
            layer.alert("服务器异常，请联系管理员", {icon: 2});
            layer.closeAll("loading");
        }
    });
}
//供应商充值次数回调
function rotationTrainingOfferNum(uuid){
    offerNumPayRunInterval = setInterval(function (){
        $.ajax({
            url: "/wxpay/getOfferNum",
            type: "get",
            data: {
                "uuid": uuid
            },
            headers: {"token": localStorage.getItem("token")},
            dataType: "json",
            success: (data) => {
                if(data.data == 1){
                    clearInterval(offerNumPayRunInterval);
                    gysTopUpNum();
                    layer.closeAll();
                    layer.msg("充值成功", {icon: 1});
                    load();
                }
            },
            error: () => {
                layer.alert("服务器异常，请联系管理员", {icon: 2});
                layer.closeAll("loading");
            }
        });
    }, 1000)
}
//余额确认
function balanceOfOk(){
    var offerNum = $("input[name=offerNum]").val();//次数
    var offerNumSelect = $(".select_amount_val_click").attr("value");//次数
    if(offerNum == "" && typeof(offerNumSelect) == "undefined"){
        layer.msg("次数不能为空，请输入或者选择购买次数");
        return false;
    }
    var numOffer;
    if(typeof(offerNumSelect) != "undefined"){
        numOffer = offerNumSelect;
    }
    if(offerNum != "" && offerNum != null){
        numOffer = offerNum;
    }
    layer.load(3);
    $.ajax({
        url: "/personal/payBlance",
        type: "get",
        data: {"offerNum": numOffer},
        headers: {"token": localStorage.getItem("token")},
        dataType: "json",
        success: (data) => {
            console.log(data)
            if(data.msg == "200"){
                parent.layer.msg("购买成功", {icon: 1});
                gysTopUpNum();
                layer.closeAll();
                load();
            } else if(data.msg == "500"){
                layer.msg(data.errMsg, {icon: 2});
            }
            layer.closeAll("loading");
        },
        error: () => {
            layer.alert("服务器异常，请联系管理员", {icon: 2});
            layer.closeAll("loading");
        }
    });
}
//将base64转换为blob
function dataURLtoBlob (dataurl) {
    var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}
//将blob转换为file
function blobToFile(theBlob, fileName){
    let file = new window.File([theBlob], fileName, {type: theBlob.type});
    return file;
}
//上传到oos图片 修改头像
function cutOos(formData){
    layer.load(2);
    $.ajax({
        url: "https://www.tuyatrip.com/api/upload/uploadFile",
        type: "post",
        data: formData,
        headers: {"token": localStorage.getItem("token")},
        processData: false,
        contentType: false,
        dataType: "json",
        success: (data) => {
            if(data.msg == "200"){
                $.ajax({
                    url: "/personal/updateName",
                    type: "put",
                    data: {
                        "headpir": data.data
                    },
                    // contentType: "application/json",
                    headers: {"token": localStorage.getItem("token")},
                    dataType: "json",
                    success: (dataVal) => {
                        if(dataVal.msg == "200"){
                            layer.closeAll();
                            parent.layer.msg("上传头像成功", {icon: 1});
                            console.log(data.data)
                            parent.$(".head_portrait").attr("src", data.data);
                            parent.conn.updateOwnUserInfo({avatarurl: data.data});
                            load();
                        } else if(dataVal.msg == "300"){
                            layer.closeAll("loading");
                            layer.msg(dataVal.errMsg, {icon: 2});
                        }
                    },
                    error: () => {
                        layer.closeAll("loading");
                        layer.alert("网络错误 请联系管理员");
                    }
                });
            }
        },
        error: () => {
            layer.closeAll("loading");
            layer.alert("网络错误 请联系管理员");
        }
    });
}
//查询充值次数
function topUpNum(){
    $.ajax({
        url: "/personal/topUpNum",
        type: "get",
        data: {},
        headers: {"token": localStorage.getItem("token")},
        dataType: "json",
        success: (data) => {
            if(data.msg == "200"){
                $(".balance_of_val").html(data.data.balance_of);//余额
                $(".cumulative_num").html(paramReturn("累计充值", parent.type)+ (typeof data.data.topUp == "undefined" ? "0" :  data.data.topUp) + paramReturn("次", parent.type));//充值次数
                $(".quotation_num").html(paramReturn("报价单单价", parent.type) +  "：" + unitPrice);//充值次数
            }
            layer.closeAll("loading");
        },
        error: () => {
            layer.closeAll("loading");
            layer.alert("网络错误 请联系管理员");
        }
    });
}
//循环计算次数金额
function eachNumberAmout(){
    $.each($(".select_number_val"), (index, item) => {
        var num = $(item).attr("value");
        $(item).find(".amount_number_val").html("￥" + (Number(num * unitPrice).toFixed(2)));
    });
}
//供应商充值次数成功后元素恢复初始化
function gysTopUpNum(){
    $("input[name=offerNum]").val("")
    $("#qrcode_ok").find("img").remove();
    if(!$($(".select_number_val")[0]).hasClass("select_amount_val_click")){
        $($(".select_number_val")[0]).click();
    }
    $(".quotation_number .pay_div_mode").removeClass("select_pay_click");
    $(".quotation_number .pay_div_mode").find("div").html(" ");

    $($(".quotation_number .pay_div_mode")[0]).addClass("select_pay_click");
    $(".quotation_number .select_pay_click").find("div").html("<i class=\"layui-icon\">&#xe605;</i>");
    $(".blance_button").show();
}