define(['require', 'common'], function (require, common) {

    /*
     *登录注册
     */
    if (sys.controller == 'index') {
        switch (sys.action) {
            case 'login':
                require(['validator'], function() {
                    $('#login_form').validator({
                        timely: 3,
                        stopOnError: true,
                        theme: 'yellow_right_effect',
                        fields: {
                            username: "用户名:required;length(4~20);",
                            password: "密码:required;",
                            captcha: "验证码:required;length(3)",
                        }
                    });
                });
                var codeTimer = {};
                var index = 0;
                $("#mini_login_btn").click(function () {
                    require(['layer'], function (layer) {
                        $.ajax({
                            type: "POST",
                            url: "/wechat/apps/qrcode",
                            beforeSend: function () {
                                layer.closeAll();
                                layer.msg('加载中', {
                                    icon: 16,
                                    shade: 0.01
                                });
                            },
                            success: function (data) {
                                if (data.code == 1) {
                                    var key = data.data.key;
                                    var url = data.data.url;
                                    $('#mini_login_content img').attr('src', url);
                                    layer.closeAll();
                                    layer.open({
                                        type: 1,
                                        skin: 'layui-layer-demo', //样式类名
                                        closeBtn: 1, //不显示关闭按钮
                                        anim: 2,
                                        shadeClose: true, //开启遮罩关闭
                                        content: $('#mini_login_content').html(),
                                        cancel: function () {
                                            window.clearInterval(codeTimer);
                                            codeTimer = {};
                                            index = 0;
                                        },
                                        end: function () {
                                            window.clearInterval(codeTimer);
                                            codeTimer = {};
                                            index = 0;
                                        }
                                    });

                                    codeTimer = window.setInterval(function () {
                                        oauthLogin(key,'mini');
                                    }, 3000);

                                } else {
                                    layer.msg(data.msg);
                                }
                            }
                        });
                    });
                });
                function oauth_login(key, type){
                    var request;
                    if(type=='mini'){
                        request = {
                            'key': key,
                        };
                    }
                    if(type=='mp'){
                        request = {
                            'ticket': key,
                        };
                    }
                    $.ajax({
                        type: 'POST',
                        url: '/user/api/qrcode_user',
                        datatype: "json",
                        data:request,
                        success: function (data) {
                            if (data.code == 1) {
                                window.clearInterval(codeTimer);
                                codeTimer = '';
                                window.location.reload();
                            }
                        }
                    });
                    index++;
                    if (index >= 20) {
                        index = 0;
                        window.clearInterval(codeTimer);
                        codeTimer = '';
                        require(['layer'], function (layer) {
                            layer.closeAll();
                        });
                    }
                }
                common.captcha();
                $('#forget').click(function () {
                    require(['layer'], function (layer) {
                        var $mobile = $('#forget-mobile').html();
                        var $email = $('#forget-email').html();
                        layer.tab({
                            area: ['600px', '400px'],
                            tab: [{
                                title: '手机',
                                content: $mobile,
                            }, {
                                title: '邮箱',
                                content: $email
                            }]
                        });
                    });
                });
                $('[rel=oauth_login]').click(function(){
                    var type = $(this).data('type');
                    var url = type=='mp'? "/wechat/index/qrcode" : "/wechat/apps/qrcode";
                    require(['layer'], function (layer) {
                        $.ajax({
                            type: "GET",
                            url: url,
                            beforeSend: function () {
                                layer.closeAll();
                                layer.msg('加载中', {
                                    icon: 16,
                                    shade: 0.01
                                });
                            },
                            success: function (data) {
                                if (data.code == 1) {
                                    var key = data.data.ticket || data.data.key;
                                    $('[rel=oauth_login_wrap] img').attr('src', data.data.url);
                                    layer.closeAll();
                                    layer.open({
                                        type: 1,
                                        skin: 'layui-layer-demo', //样式类名
                                        closeBtn: 1, //不显示关闭按钮
                                        anim: 2,
                                        shadeClose: true, //开启遮罩关闭
                                        content: $('[rel=oauth_login_wrap]').html(),
                                        cancel: function () {
                                            window.clearInterval(codeTimer);
                                            codeTimer = {};
                                            index = 0;
                                        },
                                        end: function () {
                                            window.clearInterval(codeTimer);
                                            codeTimer = {};
                                            index = 0;
                                        }
                                    });
                                    codeTimer = window.setInterval(function () {
                                        oauthLogin(key, type);
                                    }, 3000);
                                } else {
                                    layer.msg(data.msg);
                                }
                            }
                        });
                    });
                });
                break;
            case 'register':
                common.captcha();
                require(['validator'], function() {
                    $('#register_form').validator({
                        timely: 2,
                        stopOnError: true,
                        theme: 'yellow_right_effect',
                        fields: {
                            name: "用户名: required;length(4~20);remote(/user/api/check_name)",
                            email: "邮箱: required;email;remote(/user/api/check_email)",
                            pwd: "密码: required;password;",
                            repwd: "确认密码: match(pwd);",
                            captcha: "验证码:required;length(3)",
                            phone:'手机号：required;mobile;length(11);remote(/user/api/check_phone)',
                            verify:'验证码: required;number;'
                        }
                    });
                });
                require(['layer'], function () {
                    $('#get_verify').click(function () {
                        var phone = $("#phone").val();
                        var verify = $("#reg-captcha").val();
                        if (!phone) {
                            layer.msg('未找到手机号，无法发送短信验证码');
                            return false;
                        }
                        if (!verify) {
                            layer.msg('请先输入图片验证码');
                            return false;
                        }
                        $.get('/user/api/send_sms', {
                            'phone': phone,
                            'verify': verify,
                            'type': 'SMS_1'
                        }, function (data) {
                            var obj = $('#get_verify');
                            if (data['code'] == 1) {
                                obj.attr('disabled', true);
                                layer.msg(data.msg);
                                $('#get_verify').val('60');
                                var cc = setInterval(function () {
                                    var num = obj.val();
                                    if (num > 0) {
                                        obj.val(num - 1);
                                    } else {
                                        obj.val('点击重新发送');
                                        obj.attr('disabled', false);
                                        clearInterval(cc);
                                    }
                                }, 1000);
                            } else {
                                layer.msg(data['msg']);
                            }
                        });
                    });
                });
                $('a.agreement').unbind('click').bind('click', function () {
                    require(['layer'], function () {
                        $.ajax({
                            type: "GET",
                            url: "/user/api/get_agreement",
                            datatype: "json",
                            success: function (data) {
                                layer.open({
                                    type: 1,
                                    title: '隐私协议',
                                    skin: 'layui-layer-rim',
                                    area: ['600px', '700px'],
                                    content: data,
                                });
                            }
                        });
                    });
                });
                break;
            case 'forget':
                common.captcha();
                require(['validator']);
                require(['layer'], function () {
                    $('#get_verify').click(function () {
                        var phone = $("#phone").val();
                        var verify = $("#reg-captcha").val();
                        if (!phone) {
                            layer.msg('未找到手机号，无法发送短信验证码');
                            return false;
                        }
                        if (!verify) {
                            layer.msg('请先输入图片验证码');
                            return false;
                        }
                        $.get('/user/api/send_sms', {
                            'phone': phone,
                            'verify': verify,
                            'type': 'SMS_2'
                        }, function (data) {
                            var obj = $('#get_verify');
                            if (data['code'] == 1) {
                                obj.attr('disabled', true);
                                layer.msg(data.msg);
                                $('#get_verify').val('60');
                                var cc = setInterval(function () {
                                    var num = obj.val();
                                    if (num > 0) {
                                        obj.val(num - 1);
                                    } else {
                                        obj.val('点击重新发送');
                                        obj.attr('disabled', false);
                                        clearInterval(cc);
                                    }
                                }, 1000);
                            } else {
                                layer.msg(data['msg']);
                            }
                        });
                    });
                })
                break;
        }
    }

    /*
     *会员中心
     */
    if (sys.controller == 'user') {
        /**
         * 左侧菜单选中初始化
         */
        $("#sidebar li").removeClass("active").filter(function() {
            return $(this).children('a').attr('href') == window.location.pathname;
        }).addClass("active");

        common.confirm();
        common.moment();

        // 上传头像
        $('[data-target="#myModal"]').click(function () {
            require(['cropper', 'layer'], function (Cropper, layer) {
                var image = document.getElementById('avatar');
                var $cropper = new Cropper(image, {
                    preview: '.preview',
                    aspectRatio: 1,
                    minContainerWidth: 300,
                    minContainerHeight: 200,
                    crop: function (event) {},
                    ready: function () {},
                });
                // 更换图片
                var URL = window.URL || window.webkitURL;
                var $inputImage = $('#inputImage');
                var uploadedImageURL;
                var file;
                if (URL) {
                    $inputImage.change(function () {
                        var files = this.files;
                        if (files && files.length) {
                            file = files[0];
                            if (/^image\/\w+$/.test(file.type)) {
                                if (uploadedImageURL) {
                                    URL.revokeObjectURL(uploadedImageURL);
                                }
                                uploadedImageURL = URL.createObjectURL(file);
                                $cropper.replace(uploadedImageURL, false);
                                $inputImage.val('');
                            } else {
                                layer.msg('请选择图片格式');
                            }
                        }
                    });
                } else {
                    $inputImage.prop('disabled', true).parent().addClass('disabled');
                }

                //上传图片
                $('[rel=onSubmit]').click(function () {

                    if ($cropper.getCroppedCanvas) {
                        $cropper.getCroppedCanvas().toBlob(function (blob) {
                            var formData = new FormData();
                            formData.append('file', blob, file.name);
                            // Use `jQuery.ajax` method
                            $.ajax('/files/api/upload/module/user/file/file/field/avatar', {
                                method: "POST",
                                data: formData,
                                processData: false,
                                contentType: false,
                                success: function (rs) {
                                    $('#user-avatar').attr('src', rs.data.url + '?' + (new Date().getTime()));
                                    layer.msg('修改成功');
                                    setTimeout(function () {
                                        $('.modal .close').click();
                                    }, 500);
                                },
                                error: function () {
                                    layer.msg('修改失败，请重试');
                                }
                            });
                        });
                    }
                });
            });
        });

        switch (sys.action) {
            case 'index':
                require(['layer'], function (layer) {
                    // 刷新
                    $('[rel=refresh]').on('click', function () {
                        var money = $(this).data('money');
                        var credit = $(this).data('credit');
                        var $this = $(this);
                        var html = '<p class="mt-lg" style="padding-left:80px;">刷新需要扣除<br>';
                        html = html + '余额: <span class="text-danger">' + money + '</span> 元<br>';
                        html = html + '积分: <span class="text-danger">' + credit + '</span> 积分</p>';
                        layer.open({
                            type: 1,
                            title: '温馨提示',
                            shadeClose: true,
                            resize: false,
                            area: ['260px', '200px'], //宽高
                            content: html,
                            btn: ['确定'],
                            yes: function (index, layero) {
                                window.location = $this.data('href');
                            }
                        });
                    });
                    // 置顶
                    $('[rel=top]').on('click', function () {
                        var money = $(this).data('money');
                        var credit = $(this).data('credit');
                        var $this = $(this);
                        var html = '<p class="mt-md mb-sm" style="padding-left:80px;">置顶每天需要扣除<br>';
                        html = html + '余额：<span class="text-danger">' + money + '</span> 元<br>';
                        html = html + '积分：<span class="text-danger">' + credit + '</span> 积分</p>';
                        html = html + "<div class='pl-lg pr-lg input-group'><input type='number' class='form-control'><span class='input-group-addon'> 天</span></div>";
                        layer.open({
                            type: 1,
                            title: '信息置顶',
                            shadeClose: true,
                            resize: false,
                            area: ['260px', '240px'], //宽高
                            content: html,
                            btn: ['确定'],
                            yes: function () {
                                var day = parseInt($("[type='number']").val());
                                var url = $this.data('href') + '?days=' + day;
                                window.location = url;
                            }
                        });
                    });
                });
                require(['moment'], function (moment) {
                    $("[rel=moment]").each(function () {
                        var datatime = $(this).data('time');
                        $(this).html(moment(datatime, "YYYY-MM-DD hh:mm:ss").fromNow());
                    });
                });

                break;
            case 'auth':
                require(['validator'], function (validator) {
                    $('#auth_form').validator({
                        stopOnError: true,
                        theme: 'yellow_right_effect',
                        fields: {
                            name: "姓名:required ;",
                            id_card: "身份证号码:required;length(18);",
                        }
                    });
                })
                var $obj = $('[rel=preview]');
                $obj.change(function () {
                    var $this = $(this);
                    var render_dom = $this.data('render');
                    render($this, render_dom);

                })

                function render(data, render_dom) {
                    if (typeof FileReader !== 'undefined') { //浏览器能力检测
                        var arrFile = data[0].files;
                        console.log(arrFile);
                        $(render_dom).html(''); //清空之前上传的dom
                        for (var i = 0; i < arrFile.length; i++) {
                            if (!/image\/\w+/.test(arrFile[i].type)) {
                                require(['layer'], function (layer) {
                                    layer.msg('请上传图片格式')
                                })
                                return false;
                            }
                            var reader = new FileReader();
                            //将文件以Data URL形式读入页面  
                            reader.readAsDataURL(arrFile[i]);
                            reader.onload = function (e) {
                                //显示文件 
                                var result = this.result;
                                // console.log(result)
                                var html = $(render_dom).html();
                                // console.log(html)
                                html += '<div class="item"><img src="' + result + '" alt="" /></div>'
                                $(render_dom).html(html);
                            }
                        }
                    }
                }
                $(".submit").click(function () {
                    var idcard = $("#auth_form #card").val();
                    var name = $("#auth_form #name").val();
                    require(['layer'], function (layer) {
                        if (idcard.length != 18) {
                            layer.msg("请输入正确的身份证号")
                            return
                        }
                        if (name.length == 0) {
                            layer.msg("请输入姓名")
                            return
                        }
                        var formData = new FormData($("#auth_form")[0]);

                        var xhr = new XMLHttpRequest;
                        xhr.onreadystatechange = function () {
                            if (xhr.status == 200) {
                                var back = JSON.parse(xhr.responseText);
                                layer.msg(back.msg)
                                if (back.code == 1) {
                                    window.location.reload()
                                }
                            }
                        };
                        xhr.open('post', '/user/user/auth');
                        xhr.send(formData);
                    });
                })
                break;
            case 'service_form': 
                common.preview();
                common.radio();
                common.value();
                break;
            case 'shop':
                common.preview();
                common.value();
                break;
            case 'recharge':
                require(['validator'], function (validator) {
                    $('#recharge_form').validator({
                        stopOnError: true,
                        theme: 'yellow_right_effect',
                        fields: {
                            amount: "金额: required;",
                        }
                    });
                });
                $('*[rel=amount]').click(function () {
                    $('input[name=money]').val($(this).data('amount'));
                });

                $(".payment img").on('click', function () {
                    var method = $(this).data('value');
                    $('input[name="method"]').val(method);
                });
                require(['layer'], function (layer) {
                    $('[rel="recharge"]').on('click', function (e) {
                        // e.preventDefault();
                        var form = $('#recharge_form');
                        var payment = $("input[name='payment']:checked").val();
                        if (!$('input[name="money"]').val()) {
                            layer.msg('请输入金额');
                            return false;
                        }
                        var data = {
                            attr: {
                                payment: $("input[name='payment']:checked").val(),
                                method: $("input[name='method']").val(),
                                money: $('input[name="money"]').val()
                            }
                        };
                        var settings = {
                            auto_outTradeNoTimer: true,
                        };
                        // debugger
                        if (payment == 3) {
                            //执行支付宝支付
                            form.submit();
                        } else if (payment == 2) {
                            //执行微信支付
                            data.attr.method = 'scan';
                            $.ajax({
                                type: "POST",
                                url: "/finance/api/recharge",
                                data: data,
                                beforeSend: function () {
                                    layer.closeAll();
                                    layer.msg('加载中', {
                                        icon: 16,
                                        shade: 0.01
                                    });
                                },
                                success: function (data) {
                                    if (data.code == 1) {
                                        layer.closeAll();
                                        select_payment(data, settings);
                                    } else {
                                        layer.msg(data.msg);
                                    }
                                }
                            });
                        }
                    });
                    // 扫码支付
                    function select_payment(data, settings) {
                        layer.open({
                            type: 1,
                            title: '微信扫码支付',
                            area: ['360px', '400px'], //宽高
                            btn: ['已完成', '未完成'],
                            btnAlign: 'c',
                            content: "<div class='text-center' style='margin-top:40px'><img style='width:60%' src=/finance/api/qrcode?text=" + data.data + " alt=''></div>",
                            cancel: function (index, layero) {
                                settings.auto_outTradeNoTimer = false;
                                window.parent.location.reload();
                                layer.closeAll();
                            },
                            yes: function (index, layero) {
                                settings.auto_outTradeNoTimer = false;
                                window.parent.location.reload();
                                layer.closeAll();
                            },
                            btn2: function () {
                                layer.open({
                                    type: 1,
                                    title: '请选择',
                                    btn: ['继续支付', '支付有问题'],
                                    yes: function () {
                                        layer.closeAll();
                                    },
                                    btn2: function () {
                                        window.location.href = "/help/index/index";
                                    }
                                });
                            }
                        });
                        // 轮询查询支付是否成功
                        outTradeNoTimer(data.order, settings);
                    }

                    function outTradeNoTimer(out_trade_no, settings) {
                        $.ajax({
                            url: '/finance/api/read',
                            method: 'post',
                            data: {
                                'attr': {
                                    id: out_trade_no,
                                }
                            },
                            cache: false,
                            dataType: 'json',
                            success: function (data) {
                                if (data.status == 1) {
                                    layer.closeAll();
                                    layer.open({
                                        title: '信息提示',
                                        btnAlign: 'c',
                                        content: '<p class="text-center">支付成功</p>',
                                        btn: ['确定']
                                    });
                                } else {
                                    setTimeout(function () {
                                        if (settings.auto_outTradeNoTimer) {
                                            outTradeNoTimer(out_trade_no, settings);
                                        }
                                    }, 3000);
                                }
                            }
                        });
                    }
                });
                break;
            case 'modify':
                require(['validator'], function (validator) {
                    $('#modify_form').validator({
                        stopOnError: true,
                        theme: 'yellow_right_effect',
                        fields: {
                            email: "邮箱:required(from, .form-control);email;",
                            phone: "电话:required(from, .form-control);mobile|tel;",
                            qq: "qq:required(from, .form-control);length(~20);",
                        }
                    });
                });
                common.value();
                common.checkbox();
                common.radio();
                break;
            case 'safe':
                var sms_time = 60;
                var timer;
                var chk = /^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
                $("#get_verify").click(function () {
                    var phone = $('#phone_num').val();
                    require(['layer'], function (layer) {
                        if (phone.length != 11 && !chk.test(phone)) {
                            layer.msg("请填写正确的手机号");
                            return false;
                        }
                        common.captcha();
                        layer.open({
                            type: 1,
                            skin: 'layui-layer-demo', //样式类名
                            btn: ['确定', '取消'],
                            yes: function (index, layero) {
                                var verify = $("#verify").val();
                                if (!verify) {
                                    layer.msg("请输入图片验证码");
                                    return false;
                                }
                                getMsg(phone, verify);
                            },
                            btn2: function (index, layero) {

                            },
                            shadeClose: true, //开启遮罩关闭
                            content: $('.verifyModel')
                        });
                    });
                });

                function getMsg(phone, verify) {
                    if (phone.length == 11 && chk.test(phone) && ($('#get_verify').val() == "获取验证码" || $('#get_verify').val() == "重新获取验证码")) {
                        $.ajax({
                            type: "post",
                            url: "/user/api/send_sms",
                            data: {
                                'phone': phone,
                                'verify': verify,
                                'type': 'SMS_1'
                            },
                            dataType: "json",
                            success: function (data) {
                                require(['layer'], function (layer) {
                                    $('#phone_num').attr('readonly', true);
                                    switch (data.code) {
                                        case 1:
                                            layer.msg(data.msg);
                                            setTimeout(function () {
                                                layer.closeAll();
                                            }, 500)
                                            $('#get_verify').addClass('on');
                                            $("#get_verify").attr("readonly", true).css("cursor", "wait");
                                            timer = setInterval(_waiting, 1000);
                                            break;
                                        case -4:
                                            layer.msg(data.msg);
                                            return false;
                                            break;
                                        default:
                                            layer.msg(data.msg);
                                            return false;
                                    }
                                })
                            }
                        })
                    }
                }

                function _waiting() {
                    sms_time = sms_time - 1;
                    $("#get_verify").val(sms_time + '秒后可重发');
                    if (sms_time <= 0) {
                        $('#phone').removeAttr('readonly');
                        $("#get_verify").removeAttr("readonly").css("cursor", "pointer").attr("value", "重新获取验证码");
                        clearInterval(timer);
                    }
                }

                $('[name=send_mail]').click(function () {
                    var email = $('input[name=email]').val();
                    if (email) {
                        var data = {
                            email: email
                        };
                        if ($(this).data('type') != 'unbind') {
                            var url = '/user/api/send_email';
                            data.type = 'url';
                        } else {
                            var url = '/user/api/unbind_email';
                        }
                        $.post(url, {
                            attr: data
                        }, function (data) {
                            require(['layer'], function (layer) {
                                layer.open({
                                    title: '提示信息',
                                    content: data.msg
                                });
                            })
                        });
                    } else {
                        return false;
                    }
                });
                break;

            case 'pwd':
                require(['validator'], function() {
                    $('#pwd_form').validator({
                        stopOnError: true,
                        theme: 'yellow_right_effect',
                        fields: {
                            pwd: "旧密码: required;password;",
                            newpwd: "新密码: required;password;",
                            re_newpwd: "match(newpwd);",
                        }
                    });
                });
                break;
        }
    }
});