window.onload = function () {
    var user = localStorage.getItem("user");
    document.body.oncopy = function () {
        if (isNullOrEmpty(user)) {
            user = JSON.parse(user);
            clearInterval(interval)
            $("#popLogin").show();
        }
    };
}

var checkPhone = function (str) {
    var flag = (/(^1[2|3|4|5|6|7|8|9]\d{9}$)|(^09\d{8}$)/).test(str)
    return flag;
};


//对手机进行加密后发送后端验证用户是否注册并获取验证码
function encryptPhoneGetCode(phone) {
    var encrypt = new JSEncrypt();
    encrypt.setPublicKey($("#publicKey").val())
    phone = encrypt.encrypt(phone);
    phone = encodeURI(phone).replace(/\+/g, '%2B');
    $.ajax({
        url: "/reg/checkPhoneAndTakeCode",
        type: "POST",
        data: {"phone": phone},
        success: function (result) {
            if (result.code === 200) {
                $(".message").fadeIn(300)
                $(".message").text(result.data)
                setTimeout(function () {
                    $(".message").fadeOut(300)
                }, 2000)
            } else {
                $(".message").fadeIn(300)
                $(".message").text(result.msg)
                setTimeout(function () {
                    $(".message").fadeOut(300)
                }, 2000)
            }
        }
    })
}

// 获取验证码(短信登录，不需要验证用户是否存在)
function getVerify(phone) {
    var encrypt = new JSEncrypt();
    encrypt.setPublicKey($("#publicKey").val())
    phone = encrypt.encrypt(phone);
    phone = encodeURI(phone).replace(/\+/g, '%2B');
    $.ajax({
        url: "/login/takeVerify",
        type: "POST",
        data: {"phone": phone},
        success: function (result) {
            if (result.code === 200) {
                $(".message").fadeIn(300)
                $(".message").text(result.msg)
                setTimeout(function () {
                    $(".message").fadeOut(300)
                }, 2000)
            } else {
                $(".message").fadeIn(300)
                $(".message").text(result.msg)
                setTimeout(function () {
                    $(".message").fadeOut(300)
                }, 2000)
            }
        }
    })
}

// 用户注册
function userRegister(phone, pwd, verify) {
    var encrypt = new JSEncrypt();
    encrypt.setPublicKey($("#publicKey").val());
    // 加密手机号
    phone = encrypt.encrypt(phone);
    phone = encodeURI(phone).replace(/\+/g, '%2B');
    // 加密验证码
    verify = encrypt.encrypt(verify);
    verify = encodeURI(verify).replace(/\+/g, '%2B');
    // 加密密码
    pwd = encrypt.encrypt(pwd);
    pwd = encodeURI(pwd).replace(/\+/g, '%2B');

    $.ajax({
        url: "/reg/postRegister",
        type: "POST",
        data: {phone: phone, pwd: pwd, verify: verify},
        success: function (result) {
            if (result.code === 200) {
                if (result.data.state === 1) {
                    $(".message").fadeIn(300)
                    $(".message").text(result.msg)
                    setTimeout(function () {
                        $(".message").fadeOut(300)
                    }, 2000)
                    window.location.href = "/login/";
                } else {
                    $(".message").fadeIn(300)
                    $(".message").text(result.msg)
                    setTimeout(function () {
                        $(".message").fadeOut(300)
                    }, 2000)
                }
            } else {
                $(".message").fadeIn(300)
                $(".message").text(result.msg)
                setTimeout(function () {
                    $(".message").fadeOut(300)
                }, 2000)
            }
        }
    })
}

// 立即订购
function lijidinggou(obj) {
    // 登录过的用户
    var user = localStorage.getItem("user");
    if (isNullOrEmpty(user)) {
        window.location.href = "//www.gov-bid.com/goVip/";
    } else {
        $(obj).attr("href", "//www.gov-bid.com/gov/home/openVip");
    }
}

// 当前时间
function getNowDate() {
    var myDate = new Date();
    var now_month = myDate.getMonth() + 1 <= 9 ? "0" + (myDate.getMonth() + 1) : myDate.getMonth() + 1; //获取当前月
    var date1 = myDate.getDate() <= 9 ? "0" + myDate.getDate() : myDate.getDate(); //获取当前日
    var now_data = myDate.getFullYear() + "-" + now_month + "-" + date1
    return now_data;
}

// 获取之前n个月时间
function getBeforeDate(number) {
    var d = new Date();
    var n = new Date(d.getTime() - 86400000 * (30 * number));
    var before_year = n.getFullYear();
    var before_month = n.getMonth() + 1 <= 9 ? "0" + (n.getMonth() + 1) : n.getMonth() + 1;
    var date2 = n.getDate() <= 9 ? "0" + n.getDate() : n.getDate();
    var before_date = before_year + "-" + before_month + "-" + date2;
    return before_date;
}

// 获取之前n天的日期
function getBeforeDayDate(number) {
    var d = new Date();
    var n = new Date(d.getTime() - 86400000 * (number));
    var before_year = n.getFullYear();
    var before_month = n.getMonth() + 1 <= 9 ? "0" + (n.getMonth() + 1) : n.getMonth() + 1;
    var date2 = n.getDate() <= 9 ? "0" + n.getDate() : n.getDate();
    var before_date = before_year + "-" + before_month + "-" + date2;
    return before_date;
}

// 服务协议
function serviceAgree() {
    let xieyi = localStorage.getItem("xieyi")
    if (xieyi == null) {
        $(".scris").html("");
        $.ajax({
            url: "/reg/serviceAgree",
            type: "POST",
            success: function (result) {
                if (result.state === 1) {
                    localStorage.setItem("xieyi", result.returnvalue);
                    $(".scris").html(result.returnvalue);
                }
            }
        })
    } else {
        $(".scris").html("");
        $(".scris").html(xieyi);
    }

}

function replaceAl(keyword, oldStr, newStr) {
    var pattern = /["]+|[']+/;
    while (pattern.exec(keyword)) {
        keyword = keyword.replace("\"", newStr).replace("'", "");
    }
    return keyword;
}

// 通过省代码和市代码获取完整地区名称
function getAreaNameByProvinceCodeOrCityCode(provicecode, citycode) {
    var areaName = "";
    if (provicecode != null) {
        if (AreaList.prototype.getNameByCode(provicecode) === "北京" || AreaList.prototype.getNameByCode(provicecode) === "天津" || AreaList.prototype.getNameByCode(provicecode) === "上海" || AreaList.prototype.getNameByCode(provicecode) === "重庆") {
            areaName += AreaList.prototype.getNameByCode(provicecode) + "市";
        } else {
            areaName += AreaList.prototype.getNameByCode(provicecode) + "省";
        }
    }
    if (citycode !== "" && citycode != null && AreaList.prototype.getNameByCode(provicecode) !== "北京" && AreaList.prototype.getNameByCode(provicecode) !== "天津" && AreaList.prototype.getNameByCode(provicecode) !== "上海" && AreaList.prototype.getNameByCode(provicecode) !== "重庆") {
        var cityName = AreaList.prototype.getNameByCode(citycode);
        if (cityName !== "") {
            areaName += AreaList.prototype.getNameByCode(citycode) + "市";
        }
    }
    return areaName;
}


/**
 * 显示页面消息
 * @param msg 也秒消息内容
 * @param duration 小时窗口延时关闭时间，单位毫秒
 * @param callback 回调函数
 * @constructor
 */
function Toast(msg, duration, callback) {
    duration = isNullOrEmpty(duration) ? 3000 : duration;
    var m = document.createElement('div');
    m.innerHTML = msg;
    m.style.cssText = "max-width:60%;min-width: 150px;padding:0 14px;height: 40px;color: rgb(255, 255, 255);line-height: 40px;text-align: center;border-radius: 4px;position: fixed;top: 50%;left: 50%;transform: translate(-50%, -50%);z-index: 99999999;background: rgba(0, 0, 0,.7);font-size: 16px;";
    document.body.appendChild(m);
    setTimeout(function () {
        var d = 0.5;
        m.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in';
        m.style.opacity = '0';
        setTimeout(function () {
            document.body.removeChild(m);
            if (typeof callback !== "undefined") {
                callback();
            }
        }, d * 1000);
    }, duration);
}

/**
 * 显示全局遮罩
 * @param text
 */
function loaddingShow(text) {
    loaddingHidden();
    text = text || "加载中...";
    var htmltext = "<div class=\"loadding-tip\" id='loadding_tip'>";
    htmltext += "<div class=\"loadding-tip-content\"><img src=\"/images/common/loading.gif\"> <label>" + text + "</label></div>";
    htmltext += "</div>";
    $("body").append(htmltext);
}

/***
 * 关闭全局遮罩
 */
function loaddingHidden() {
    if (!isNullOrEmpty($("#loadding_tip"))) {
        $("#loadding_tip").remove();
    }
}

/**
 * ajax请求
 * @param url
 * @param pagram
 * @param callback
 * @param contentType "application/x-www-form-urlencoded"  "application/json"
 * @param httptype  "POST"  "GET"
 * @param rebacktype "json" "xml"  "text" "html"
 * @param timeout
 * @constructor
 */
function AjaxRequest(url, pagram, callback, contentType, httptype, rebacktype, timeout) {
    timeout = timeout || 15000;
    httptype = httptype || "POST";
    rebacktype = rebacktype || "json";
    contentType = contentType || "application/x-www-form-urlencoded";
    var toekn = null;
    var userdata = localStorage.getItem("user");
    if (!isNullOrEmpty(userdata)) {
        var user = JSON.parse(userdata);
        toekn = user.token;
    }
    $.ajax({
        type: httptype,
        dataType: rebacktype,
        cache: false,
        url: url,
        data: pagram,
        contentType: contentType,
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("Authorization", toekn);
        },
        success: function (rebackdata) {
            if (rebackdata.code == 404) {//未登录
                $("#popLogin").show();
                if ("undefined" !== typeof interval) {
                    clearInterval(interval);
                }
            } else if (rebackdata.code == 401) {
                Toast("您不是VIP会员或已过期", 1000, function () {
                    $vip.unVipPopup();
                })
            } else if (rebackdata.code == 201) {//业务异常，需要进行别的业务----------------------常用
                switch (rebackdata.data.State) {
                    case 4://积分不足
                        if (isNullOrEmpty(userdata)) {//未登录用户
                            $("#popLogin").show();
                        } else {//已登录用户
                            Toast("积分不足，请充值", 1000, function () {
                                $userscore.popRechargeScore();
                            });
                        }
                        break;
                    case 6://积分不足
                        if (isNullOrEmpty(userdata)) {//未登录用户
                            $("#popLogin").show();
                        } else {//已登录用户
                            Toast("VIP已过期", 1000, function () {
                                $vip.expiredVipPopup();
                            });
                        }
                        break;
                    default :
                        Toast(rebackdata.data.Msg,3000,function () {
                            if (typeof callback !== "undefined") {
                                callback(rebackdata);
                            }
                        });
                        break;
                }
            } else {
                if (typeof callback !== "undefined") {
                    callback(rebackdata);
                }
            }
        },
        error: function () {
            Toast("程序失败，请联系管理员，谢谢！");
        }
    });
}

/***
 * 判读字符或对象是否为空
 * @param str
 * @returns {boolean}
 */
function isNullOrEmpty(str) {
    if (str === 0) {
        return false;
    } else if (str === "null" || str === "" || str === null || str === undefined || str === "undefined") {
        return true;
    } else {
        if (typeof str === "string" && str === "") {
            return true;
        } else {
            return false;
        }
    }
}


//回到顶部
$(".up").click(function () {
    document.body.scrollTop = 0;
    document.documentElement.scrollTop = 0;
})

//对象属性合并，重复的属性则直接去掉了，故不能有重复的属性
if (typeof Object.assign != 'function') {
    Object.assign = function (target) {
        'use strict';
        if (target == null) {
            throw new TypeError('Cannot convert undefined or null to object');
        }
        target = Object(target);
        for (var index = 1; index < arguments.length; index++) {
            var source = arguments[index];
            if (source != null) {
                for (var key in source) {
                    if (Object.prototype.hasOwnProperty.call(source, key)) {
                        target[key] = source[key];
                    }
                }
            }
        }
        return target;
    };
}
/**
 * 用户相关操作组件
 */
!(function (window) {
    var user = {};
    /*
     * 获取用户js缓存数据
     */
    user.getData = function () {
        let user = localStorage.getItem("user");
        if (isNullOrEmpty(user)) {
            user=null;
        } else {
            user = JSON.parse(user);
        }
        return user;
    }
    user.checkIsExpire=function(){
        let result=true;
        let userdata =$user.getData();
        if(userdata!=null){
            result=userdata.userState.isExpire;
        }
        return result;
    }
    user.checkIsVip = function () {
        let result = false;
        let userdata = $user.getData();
        if (userdata != null) {
            result = userdata.userState.isVIP;
        }
        return result;
    }
    user.checkEnableVip=function(){
        let result=false;
        let userdata =$user.getData();
        if(userdata!=null){
            if(!userdata.userState.isExpire && userdata.userState.isVIP){
                result=true;
            }
        }
        return result;
    }
    window.$user = user;
}(window));

/**
 * 企业报告下载
 */
!(function (window) {
    var companyReport = {};
//定时查询企业报告状态
    companyReport.companyReportInterval = null;
    companyReport.reQuesrycompanyReportCount = 0;
//下载企业全景报告
    companyReport.downCompanyReport = function (companyName) {
        companyReport.reQuesrycompanyReportCount = 0;
        if (!isNullOrEmpty(companyName)) {
            var user = localStorage.getItem("user");
            if (isNullOrEmpty(user)) {//未登录用户
                $("#popLogin").show();
            } else {
                var apiurl = "/api/companyfullreport/fullReportInfoByName";
                var postparam = {companyName: companyName};
                AjaxRequest(apiurl, postparam, function (result) {
                    if (result.code == 200) {
                        var msg = "下载企业报告将花费<font color=\"red\">" + result.data.score + "</font>积分，确认下载？"
                        $layuitool.alert(msg, function () {
                            if (result.data.score > result.data.userScore) {//积分不足，弹窗充值
                                Toast("积分不足，请充值", 1000, function () {
                                    $userscore.popRechargeScore();
                                });
                            } else {
                                loaddingShow("报告生成中...");
                                companyReport.companyReportInterval = setInterval(function () {
                                    companyReport.fullReportProgressInfo(result.data.companyID);
                                }, 2000);
                            }
                        });
                    } else {
                        Toast(result.msg);
                    }
                });
            }
        }
    }

    companyReport.fullReportProgressInfo = function (companyID) {
        apiurl = "/api/companyfullreport/fullReportProgressInfo";
        postparam = {companyID: companyID};
        AjaxRequest(apiurl, postparam, function (result) {
            companyReport.reQuesrycompanyReportCount += 1;
            if ((result.code == 201 && result.data.State == 12) || (result.code == 200 && result.data.createStatus < 2)) {
                if (companyReport.reQuesrycompanyReportCount >= 6) {
                    // console.log("下载超时，清除定时器");
                    loaddingHidden();
                    window.clearInterval(companyReport.companyReportInterval);
                    Toast("下载超时，请重试");
                }
            } else if (result.code == 201 && result.data.State == 4) {
                loaddingHidden();
                window.clearInterval(companyReport.companyReportInterval);
                Toast("积分不足，请充值", null, function () {
                    window.open("/gov/myIntegral/myIntegralList");
                })
            } else if (result.code == 200 && result.data.createStatus >= 2) {
                // console.log("下载成功，清除定时器");
                loaddingHidden();
                window.clearInterval(companyReport.companyReportInterval);
                window.open(result.data.fileDownURL);
            }

        });
    }
    window.$companyReport = companyReport;
}(window));

/**
 * VIP业务
 */
!(function (window) {
    var vip = {};
    vip.expiredVipPopup=function(){
        $layuitool.dialogPage("VIP已过期", "/htmluicreate/expiredVipPopup", {type: 2,title: false,closeBtn: 0,area: ['796px', '572px']}, function (layero,index ) {
            let $body = $(layer.getChildFrame('body', index));
            let $bntclose = $body.find("#bnt_close");
            let $bntopenvip = $body.find("#bnt_open_vip");
            $bntclose.click(function () {
                layer.close(index);
            });
            $bntopenvip.click(function () {
                window.location.href="/gov/home/openVip";
            });
        });
    }
    vip.unVipPopup=function(){
        $layuitool.dialogPage("VIP已过期", "/htmluicreate/unVipPopup", {type: 2,title: false,closeBtn: 0,area: ['796px', '572px']}, function (layero,index ) {
            let $body = $(layer.getChildFrame('body', index));
            let $bntclose = $body.find("#bnt_close");
            let $bntopenvip = $body.find("#bnt_open_vip");
            $bntclose.click(function () {
                layer.close(index);
            });
            $bntopenvip.click(function () {
                window.location.href="/gov/home/openVip";
            });
        });
    }
    window.$vip=vip;
}(window));
/**
 * 积分业务
 */
!(function (window) {
    var userscore = {};
    /**
     * 积分充值弹窗
     */
    userscore.buyOrderStateInterval = null;
    userscore.reQuesrycompanyReportCount = 0;
    userscore.popRechargeScore = function () {
        userscore.reQuesrycompanyReportCount = 0;
        $layuitool.dialogEditPage("积分充值", "/htmluicreate/rechargeScore", {area: ['730px', '620px']}, function (index, layero) {
            let $body = $(layer.getChildFrame('body', index));
            let paymoney = $body.find("#payMoney").val();
            let postdata = {payMoney: paymoney};
            AjaxRequest("/api/pay/scorePayConfig", postdata, function (result) {
                if (result.code == 200) {
                    $layuitool.dialogPage("请扫描支付", "/htmluicreate/qrCodePay?orderNumber=" + result.data.orderNumber + "&qrCodeWX=" + result.data.qrCode_WX + "&qrCodeALi=" + result.data.qrCode_ALi, {
                        type: 2,
                        area: ['500px', '300px'],
                    }, function (layero, indexcode) {
                        $body = $(layer.getChildFrame('body', indexcode));
                    });
                    layer.close(index);
                    userscore.buyOrderStateInterval = setInterval(function () {
                        userscore.getBuyOrderState(result.data.orderNumber, $body);
                    }, 2000);
                } else {
                    Toast(result.msg);
                }
            });
        });
    }
    userscore.getBuyOrderState = function (orderNumber, pageObj) {
        if (userscore.reQuesrycompanyReportCount <= 50) {
            userscore.reQuesrycompanyReportCount += 1;
            AjaxRequest("/api/pay/GetBuyOrderState", {orderNum: orderNumber}, function (buyOrderState) {
                if (buyOrderState.state == 1) {
                    window.clearInterval(userscore.buyOrderStateInterval);
                    Toast("充值已成功", 1000, function () {
                        window.location.reload();
                    });
                }
            });
        } else {
            window.clearInterval(userscore.buyOrderStateInterval);
            pageObj.find('.qrcode-img').html("<span class='qrcode_expired_bg'></span><span  class='qrcode_expired_remark'>二维码已失效</span>");
            pageObj.find('.qrcode_expired_bg')
                .css("display", "block")
                .css("background", "url(/images/qrloginInvalid.png) no-repeat")
                .css("background-size", "100% 100%")
                .css("opacity", "0.2")
                .css("width", "150px")
                .css("height", "150px")
                .css("position", "absolute")
            pageObj.find('.qrcode_expired_remark')
                .css("display", "block")
                .css("padding-top", "70px");
        }
    }
    window.$userscore = userscore;
}(window));

//layui组件二次封装
!(function (window) {
    var layuitool = {};
    /**
     * 弹出页面
     * @param {any} title
     * @param {any} content
     */
    layuitool.alert = function (content, callback) {
        layui.use(['layer'], function () {
            var layer = layui.layer;
            layer.alert(content, function (index) {
                //do something
                layer.close(index);
                if (typeof callback !== "undefined") {
                    callback();
                }
            });
        });
    }
    /**
     * 弹出页面
     * @param {any} title
     * @param {any} content
     * @param {any} otherparam
     * @param {any} loadcallback
     */
    layuitool.dialogPage = function (title, content, otherparam, loadcallback) {
        title = title || '信息';
        let param = {
            type: 1,
            scrollbar: true,
            title: title,
            content: content, //这里content是一个普通的String
            success: function (layero, index) {
                if (typeof loadcallback !== "undefined") {
                    loadcallback(layero, index);
                }
            }
        };
        Object.assign(param, otherparam || {});
        layui.use(['layer'], function () {
            let layer = layui.layer;
            layer.open(param);
        });
    }
    layuitool.dialogEditPage = function (title, pageurl, otherparam, bntSubCallback) {
        title = title || '信息';
        let param = {
            type: 2,
            scrollbar: true,
            title: title,
            content: pageurl, //这里content是一个普通的String
            area: ['800px', '500px'],
            btn: ["取消", "确定"]
            , btn1: function (index, layero) {
                //按钮【按钮一】的回调
                layer.close(index);
            }
            , btn2: function (index, layero) {
                //按钮【按钮二】的回调
                bntSubCallback(index, layero);
                return false;
            }
        };
        Object.assign(param, otherparam || {});
        layui.use(['layer'], function () {
            let layer = layui.layer;
            layer.open(param);
        });
    }
    window.$layuitool = layuitool;
}(window));

