var ccwl = {
    http: location.origin,
    // http: 'http://10.0.0.91',
    reg: {
        phone: /^1(3[0-9]|4[0-9]|5[0-9]|6[0-9]|7[0-9]|8[0-9]|9[0-9])\d{8}$/
    },
    idFlag: true,
    ajaxFlag: true,
    relationRole: {}

};

ccwl.ajax = function (data, callback, fileCallback) {
    data.data['_token'] = $('meta[name="token"]').attr("value");
    // if(ccwl.ajaxFlag){
    $.ajax({
        type: data.type ? data.type : 'GET',
        url: ccwl.http + data.url,
        dataType: "json",
        data: data.data,
        error: function (err) {
            ccwl.ajaxFlag = false;
            try {
                var error = err.responseText;
                ccwl.showToast({
                    msg: error.message,
                    type: 'error'
                })
            } catch (e) {
                ccwl.showToast({
                    msg: '系统开小差~~',
                    type: 'error'
                })
            }
        },
        success: function (res) {
            ccwl.ajaxFlag = false;
            if (res.error === 0) {
                callback(res);
            } else {
                try {
                    if (data.url === '/ald_bind_info' || data.url === '/user/bind_realname') {
                        fileCallback(res);
                        return false;
                    }
                    ccwl.showToast({
                        msg: res.message
                    });
                    fileCallback(res);
                } catch (e) {

                }

            }
        }
    });
    //     setTimeout(function(){
    //         ccwl.ajaxFlag = true;
    //     },1000)
    // }else{
    //     ccwl.showToast({
    //         msg:'不要重复点击'
    //     })
    // }

}
// 获取url参数
ccwl.formatSearch = function (search) {
    search = location.search;
    if (typeof search !== "undefined") {
        search = search.substr(1);
        var arr = search.split("&"),
            obj = {},
            newarr = [];
        $.each(arr, function (i, v) {
            newarr = v.split("=");
            if (typeof obj[newarr[0]] === "undefined") {
                obj[newarr[0]] = newarr[1];
            }
        });
        return location.search ? obj : '';
    }
}
// 提示信息
var timer = null;
ccwl.showToast = function (params) {

    $.Toast("", params.msg, params.type ? params.type : 'warn', {
        stack: true,
        has_icon: false,
        has_close_btn: false,
        fullscreen: false,
        timeout: 2000,
        sticky: false,
        has_progress: false,
        rtl: false,
    });
}

// 注册
ccwl.handleRegister = function (params) {
    this.ajax({
        url: '/register',
        type: 'POST',
        data: params,
    }, function (res) {
        location.href = res.data.next_url;
    })
}

// 发送验证码
ccwl.handleSendCode = function (params, dom) {
    this.ajax({
        url: '/service/get_authcode',
        type: 'POST',
        data: params
    }, function (res) {
        ccwl.handleCutDown(dom)
    })
}
// 倒计时
ccwl.handleCutDown = function (dom) {
    var count = 60;
    var countDown = setInterval(function () {
        if (count === 0) {
            $(dom).text('重新发送').removeAttr('disabled');
            $(dom).css({
                color: '#0099ff',
            });
            clearInterval(countDown);
        } else {
            $(dom).attr('disabled', true);
            $(dom).css({
                color: '#ababab',
            });
            $(dom).text(count + 'S后重新获取');
        }
        count--;
    }, 1000);
}

// 登录
ccwl.handleLogin = function (params, type) {
    this.ajax({
        url: type === "10001" ? '/ald_login' : '/login',
        type: 'POST',
        data: params
    }, function (res) {
        location.href = res.data.next_url;
    })
}

// 找回密码
ccwl.handleFindPassword = function (params) {
    this.ajax({
        url: '/password/getback',
        type: 'POST',
        data: params
    }, function (res) {
        $('.dialog-confirm').fadeIn();
    })
}

// 修改密码
ccwl.handleChangePassword = function (params, type) {
    this.ajax({
        url: '/password/change',
        type: 'POST',
        data: params
    }, function (res) {
        if (type == 1) {
            // 账户安全里修改密码成功
            $('.update-success').fadeIn();
            $('.update-form').hide();
        }
        $('.dialog.resize-password').fadeOut();
        $('.dialog-confirm').fadeIn();
    })
}

// 实名认证
ccwl.handleAuthRealName = function (params) {
    this.ajax({
        url: '/service/real_name_auth',
        type: 'POST',
        data: {
            real_name: params.real_name,
            id_card: params.id_card
        }
    }, function (res) {
        ccwl.idFlag = true;
    }, function () {
        ccwl.idFlag = false;
    })
}
// 绑定识别码
ccwl.handleBindOrangeCode = function (params, type) {
    this.ajax({
        url: '/user/bind_aldzn',
        type: 'POST',
        data: params
    }, function (res) {
        if (type === "ald") {
            $('.dialog-confirm .toast-msg').text(res.message);
            $('.dialog-confirm .btn').attr('href', '/');
            $('.dialog-confirm').fadeIn();
            return false;
        } else {
            ccwl.showToast({
                msg: res.message,
            })
        }
    }, function (res) {
        var leaveTimes = $('.leave-times span').text();
        $('.leave-times span').text(leaveTimes - 1 < 0 ? 0 : leaveTimes - 1);
        if (leaveTimes - 1 <= 0) {
            $('.dialog-orange').fadeOut();
            $('.bind-orange').remove();
            $('.icon-orange').append('<span class="error-msg">今日错误次数达上限</span>');
            if (type === "ald") {
                location.href = "/wx/index"
                return false;
            }
        }
        if (res.error === 1020) {
            $('.leave-times span').text(res.data.left_times);
            if (res.data.left_times === 0) {
                $("input[name='orangeCode'],.btn-bind-orange").attr('disabled', true);
            }
        }
    })
}
// 获取服务器和用户id
ccwl.handleGetServer = function (receive) {
    this.ajax({
        url: '/ald_bind_info',
        type: 'get',
        data: {}
    }, function (res) {
        if (receive === "0") {
            $('.confirm-container').show();
            $('.confirm-container .message-content p').text('您暂未获得活动资格，请关注后续活动资讯');
            $('.confirm-container .message-content a').text('确定').addClass('close-click').attr('onclick', '');
            return false;
        }
        var params = {
            serverId: res.data.serverId,
            userId: res.data.userId
        }
        ccwl.handleGetRoleList(params);
    }, function (res) {
        $('.confirm-container p').text(res.message);
        $('.confirm-container').show();
    })
}

// 获取角色列表
ccwl.handleGetRoleList = function (params) {
    this.ajax({
        url: '/get_role_list',
        type: 'POST',
        data: params
    }, function (res) {
        var data = res.data,
            html = '',
            sArr = [];
        ccwl.relationRole = data;
        for (var key in data) {
            sArr.push({id: key, name: data[key].name});
        }
        $(sArr).each(function (index, item) {
            html += '<li data-value="' + item.id + '">' + item.name + '</li>';
        })
        $('.server-select').html(html);
        $('.dialog-received-gift').fadeIn();
    }, function (res) {

    })
}
// 角色领取礼包
ccwl.handleGetRoleGift = function (params) {
    this.ajax({
        url: '/send_role_gift',
        type: 'POST',
        data: params
    }, function (res) {
        $('.btn-receive-package').hide();
        $('.package-info').append('<a href="/ald_gift_detail" class="btn btn-small gift-detail">查看礼包</a>');
        $('.dialog-received-gift').fadeOut();
        ccwl.showToast({
            msg: res.message,
        })
    }, function (res) {

    })
}
// 初始化服务器列表
var initRoleList = function (serverId) {
    var roleList = ccwl.relationRole[serverId].list;
    var sHtml = '';
    $(roleList).each(function (index, item) {
        sHtml += '<li data-value="' + item.roleId + '">' + item.roleName + '</li>'
    });
    $('.role-select').html(sHtml)
    $('.role').text('请选择角色');
}

// 跳转用户信息页面
function goUserInfo() {
    var type = $('.btn-receive-package').attr('data-type');
    if (type > 0) {
        localStorage.setItem('showOrange', true);
        window.location.href = '/user/dashboard'
    }
}

function isWeChat() {
    //window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
    var ua = window.navigator.userAgent.toLowerCase();
    //通过正则表达式匹配ua中是否含有MicroMessenger字符串
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        return true;
    } else {
        return false;
    }
}


$(function () {
    $('.container-mb .menu').click(function () {
        $('.left-container').addClass('current');
        $('.container').addClass('fixed');
    });
    $('.container-mb .left-container').click(function () {
        $(this).removeClass('current');
        $('.container').removeClass('fixed');
    });
    $('.left-menu').click(function (e) {
        e = e || window.event;
        e.stopPropagation();
    });
    // 用户协议
    $('.protocol .checkbox').click(function () {
        $(this).toggleClass('current');
    })
    //
    $('.user-protocol').click(function () {
        $('.dialog-protocol').fadeIn();
        $('.protocol-title').text('橙橙网络用户服务协议');
        $('.protocol-p').show();
        $('.protocol-v').hide();
    })
    $('.user-privacy').click(function () {
        $('.dialog-protocol').fadeIn();
        $('.protocol-title').text('橙橙网络隐私保护政策');
        $('.protocol-v').show();
        $('.protocol-p').hide();
    })
    // 校验身份证
    $("input[name='idCard']").on('blur', function () {
        var realName = $("input[name='realName']").val();
        var idCard = $("input[name='idCard']").val();
        if (idCard && (idCard.length != 15 && idCard.length != 18)) {
            ccwl.showToast({
                msg: '请输入正确的身份证号码',
            })
            return false;
        }
        var params = {
            real_name: realName,
            id_card: idCard
        }
        if (idCard && realName) {
            ccwl.handleAuthRealName(params);
        }
    });
    $("input[name='realName']").blur(function () {
        var realName = $.trim($("input[name='realName']").val());
        var idCard = $.trim($("input[name='idCard']").val());
        if (idCard && (idCard.length != 15 && idCard.length != 18)) {
            ccwl.showToast({
                msg: '请输入正确的身份证号码',
            })
            return false;
        }
        var params = {
            real_name: realName,
            id_card: idCard
        }
        if (idCard && realName) {
            ccwl.handleAuthRealName(params);
        }
    });
    // 点击注册
    $('.btn-register').click(function () {
        var phone = $.trim($("input[name='phone']").val());
        var code = $("input[name='code']").val();
        var password = $.trim($("input[name='password']").val());
        var confirmPassword = $.trim($("input[name='confirmPassword']").val());
        // var realName = $("input[name='realName']").val();
        // var idCard = $("input[name='idCard']").val();
        var checked = $('.protocol .checkbox').hasClass('current');
        var regPhone = ccwl.reg.phone;
        if (!phone) {
            ccwl.showToast({
                msg: '请输入手机号码',
            })
            return false;
        } else if (phone && !regPhone.test(phone)) {
            ccwl.showToast({
                msg: '请输入正确的手机号码',
            })
            return false;
        } else if (!code) {
            ccwl.showToast({
                msg: '请输入验证码',
            })
            return false;
        } else if (!password) {
            ccwl.showToast({
                msg: '请输入密码',
            })
            return false;
        } else if (!confirmPassword) {
            ccwl.showToast({
                msg: '请再次输入密码',
            })
            return false;
        } else if (confirmPassword !== password) {
            ccwl.showToast({
                msg: '请保持两次密码一致',
            })
            return false;
        } else if (password && phone && password === phone) {
            ccwl.showToast({
                msg: '密码不可与用户名相同',
            })
            return false;
        } else if ((password && password.length < 6) || (password && password.length > 30)) {
            ccwl.showToast({
                msg: '由6-30位字母、数字或字符组成',
            })
            return false;
            // } else if (!realName) {
            //     ccwl.showToast({
            //         msg: '请输入真实姓名',
            //     })
            //     return false;
            // } else if (!idCard) {
            //     ccwl.showToast({
            //         msg: '请输入身份证号码',
            //     })
            //     return false;
            // } else if (idCard && (idCard.length != 15 && idCard.length != 18)) {
            //     ccwl.showToast({
            //         msg: '请输入正确的身份证号码',
            //     })
            //     return false;
            // } else if (!ccwl.idFlag) {
            //     ccwl.showToast({
            //         msg: '请检查身份证号和姓名是否输入正确',
            //     })
            //     return false;
        } else if (!checked) {
            ccwl.showToast({
                msg: '请勾选平台协议',
            })
            return false;
        }
        var params = {
            phone: phone,
            password: password,
            // real_name: realName,
            // id_card: idCard,
            auth_code: code
        }
        ccwl.handleRegister(params);
    });
    //  点击发送验证码
    $('.send-code').click(function () {
        var phone = $.trim($(this).parents('.form-container').find("input[name='phone']").val());
        var regPhone = ccwl.reg.phone;
        if (!phone) {
            ccwl.showToast({
                msg: '请输入手机号码',
            })
            return false;
        } else if (phone && !regPhone.test(phone)) {
            ccwl.showToast({
                msg: '请输入正确的手机号码',
            })
            return false;
        }
        var params = {
            phone: phone
        }
        ccwl.handleSendCode(params, this);
    });
    // 点击登录
    $('.btn-login').click(function () {
        var type = $(this).attr('data-type');
        var account = $("input[name='account']").val();
        var password = $.trim($("input[name='password']").val());
        var checked = $('.protocol .checkbox').hasClass('current');
        if (!account) {
            ccwl.showToast({
                msg: '请输入账号'
            })
            return false;
        } else if (!password) {
            ccwl.showToast({
                msg: '请输入密码'
            });
            return false;
        } else if (!checked && type) {
            ccwl.showToast({
                msg: '请勾选平台协议',
            })
            return false;
        }
        var params = {
            account: account,
            password: password
        }
        ccwl.handleLogin(params, type);
    });
    // 点击找回密码
    $('.btn-findPassword').click(function () {
        var phone = $.trim($("input[name='phone']").val());
        var code = $("input[name='code']").val();
        var password = $.trim($("input[name='password']").val());
        var confirmPassword = $.trim($("input[name='confirmPassword']").val());
        var regPhone = ccwl.reg.phone;
        if (!phone) {
            ccwl.showToast({
                msg: '请输入手机号码',
            })
            return false;
        } else if (phone && !regPhone.test(phone)) {
            ccwl.showToast({
                msg: '请输入正确的手机号码',
            })
            return false;
        } else if (!code) {
            ccwl.showToast({
                msg: '请输入验证码',
            })
            return false;
        } else if (!password) {
            ccwl.showToast({
                msg: '请输入密码',
            })
            return false;
        } else if (!confirmPassword) {
            ccwl.showToast({
                msg: '请再次输入密码',
            })
            return false;
        } else if (password && phone && password === phone) {
            ccwl.showToast({
                msg: '密码不可与用户名相同',
            })
            return false;
        } else if (confirmPassword !== password) {
            ccwl.showToast({
                msg: '请保持两次密码一致',
            })
            return false;
        } else if ((confirmPassword && confirmPassword.length < 6) || (confirmPassword && confirmPassword.length > 30)) {
            ccwl.showToast({
                msg: '由6-30位字母、数字或字符组成',
            })
            return false;
        }
        var params = {
            phone: phone,
            new_password: password,
            auth_code: code
        }
        ccwl.handleFindPassword(params)

    });
    $('.change-password a,.show-change-password').click(function () {
        $('.resize-password').fadeIn();
        $('.container-mb').addClass('fixed');
    });
    $(document).on('click', '.close,.close-click,.btn-close', function () {
        var type = $(this).attr('data-type');
        $('.toast-item-wrapper').remove();
        $(this).parents('.dialog').fadeOut();
        $('.container-mb').removeClass('fixed');
        if (type != 1) {
            $('.form-container input').val('');
        }
    });
    // 点击修改密码
    $('.btn-changePassword').click(function () {
        var type = $(this).attr('data-type');
        var nowPassword = $.trim($("input[name='nowPassword']").val());
        var newPassword = $.trim($("input[name='newPassword']").val());
        var confirmNewPassword = $.trim($("input[name='confirmNewPassword']").val());
        if (!nowPassword) {
            ccwl.showToast({
                msg: '请输入当前密码',
            })
            return false;
        } else if (!newPassword) {
            ccwl.showToast({
                msg: '请输入新密码',
            })
            return false;
        } else if (!confirmNewPassword) {
            ccwl.showToast({
                msg: '请再次输入新密码',
            })
            return false;
        } else if (newPassword !== confirmNewPassword) {
            ccwl.showToast({
                msg: '请保持两次新密码一致',
            })
            return false;
        } else if ((confirmNewPassword && confirmNewPassword.length < 6) || (confirmNewPassword && confirmNewPassword.length > 30)) {
            ccwl.showToast({
                msg: '由6-30位字母、数字或字符组成',
            })
            return false;
        }
        var params = {
            password: nowPassword,
            new_password: newPassword,
        }
        ccwl.handleChangePassword(params, type);
    });
    $('.back').click(function () {
        window.history.go(-1);
    });
    $('.bind-orange').click(function () {
        $('.dialog-orange').fadeIn();
    });
    // 点击绑定识别码
    var bindFlag = true;
    $('.btn-bind-orange').click(function () {
        var orangeCode = $("input[name='orangeCode']").val();
        var leftTimes = $('.leave-times span').text();
        var type = $(this).attr('data-type');
        if (!orangeCode) {
            ccwl.showToast({
                msg: '请输入识别码',
            })
            return false;
        } else if (leftTimes * 1 <= 0) {
            ccwl.showToast({
                msg: '今日错误次数达上限',
            })
            return false;
        }
        var params = {
            bind_code: orangeCode
        }
        if (bindFlag) {
            bindFlag = false;
            ccwl.handleBindOrangeCode(params, type);
            setTimeout(function () {
                bindFlag = true
            }, 3000)
        }

    });
    $('.btn-confirm').click(function () {
        $(this).parents('.dialog').fadeOut();
        location.href = '/login';
    });
    $('.expect').click(function () {
        ccwl.showToast({
            msg: '暂未开放，敬请期待'
        })
    });
    $('.btn-receive-package').click(function () {
        var type = $(this).attr('data-type');
        var receive = $(this).attr('data-receive');
        if (type === "0") {
            $('.confirm-container').show();
            $('.confirm-container .message-content p').text('今日Orange识别码输入错误次数已达上限');
            $('.confirm-container .message-content a').text('确定').addClass('close-click').attr('onclick', 'localStorage.removeItem(\'showOrange\');');
            return false;
        }
        ccwl.handleGetServer(receive);
    });
    $('.btn-receive').click(function () {
        var serverId = $('.server-select li.current').attr('data-value'),
            roleId = $('.role-select li.current').attr('data-value');
        if (!serverId || serverId == '') {
            ccwl.showToast({msg: '请选择服务器'});
            return false;
        } else if (!roleId || roleId == '') {
            ccwl.showToast({msg: '请选择角色'});
            return false;
        }
        var params = {
            serverId: serverId,
            roleId: roleId
        }
        ccwl.handleGetRoleGift(params);
    });
    $('.gift-span span').click(function () {
        $(this).addClass('current').siblings().removeClass('current');
        var index = $(this).index();
        $('.tab-content p').hide();
        $('.tab-content p').eq(index).show().siblings().hide();
    });
    $('.toggle-down').click(function () {
        $('.gift-explain-container').fadeIn();
    })
    $('.select span').click(function () {
        $('.select-option').hide();
        if ($(this).hasClass('current')) {
            $('.select span').removeClass('current');
            $(this).siblings('.select-option').stop().slideUp(100);
        } else {
            $('.select span').removeClass('current');
            $(this).addClass('current');
            $(this).siblings('.select-option').stop().slideDown(100);
        }
    });
    $(document).on('click', '.select-option li', function () {
        var text = $(this).text();
        $(this).addClass('current').siblings().removeClass('current');
        $(this).parents('.select').find('span').text(text);
        $(this).parents('.select').find('span').removeClass('current');
        $(this).parents('.select').find('.select-option').stop().slideUp(100);
    });
    $(document).on('click', '.server-select li', function () {
        var serverId = $(this).attr('data-value');
        initRoleList(serverId);
    });
    $("input[name='password']").keyup(function (e) {
        var keyCode = e.keyCode;
        if (keyCode === 13) {
            $('.btn-login').trigger('click');
        }
    });
    $("input[name='confirmNewPassword']").keyup(function (e) {
        var keyCode = e.keyCode;
        if (keyCode === 13) {
            $('.btn-changePassword').trigger('click');
        }
    });
    // if(!isWeChat()){
    //     $('.ald-container,.container').remove();
    //     $('.is-weixin').show();
    // }
});
