define(['require', 'common', 'layer', 'cim/index'], function (require, common, layer, index) {

    // 简易观察者模式
    var Bus = {
        event: {},
        on: function (ev, callback) {
            if (this.event[ev]) {
                this.event[ev].push(callback);
            } else {
                this.event[ev] = [callback];
            }
        },
        emit: function (ev, ...param) {
            if (this.event[ev]) {
                this.event[ev].forEach(item => {
                    item(...param);
                });
            }
        },
        off: function (ev, callback) {
            this.event[ev].filter(item => item != callback);
        }
    };


    //注册事件

    Bus.on('payorder', handle); //(支付订单)
    Bus.on('isfinish', outTradeNoTimer); //支付是否完成


    //生成订单
    function generateOrder(url, param) {
        $.post(url, param, function (rs) {
            if (rs.code == 2) {
                Bus.emit('payorder', rs.order);
            }
        });
    }

    //支付订单
    function handle(order) {
        var param = {
            'order': order,
        };
        var settings = {
            auto_outTradeNoTimer: true,
        };
        param.method = 'scan';
        $.post('/finance/api/pay', {
            'attr': param
        }, function (rs) {
            if (rs.code == 1) {
                if (rs.data) {
                    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=" + rs.data + " alt=''></div>",
                        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 = "/feedback";
                                }
                            });
                        }
                    });
                    // 查询支付是否成功
                    Bus.emit('isfinish', rs.order, settings);
                } else {
                    layer.msg('支付成功');
                    setTimeout(function () {
                        layer.closeAll();
                    }, 1000);
                }
            } else if (rs.code == 0) {
                layer.msg('积分或余额不足');
            }
        });
    }

    // 查询支付是否成功
    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);
                }
            }
        });
    }

    if (sys.controller == 'index') {
        switch (sys.action) {
            case 'index':
                break;

            case 'column':
                index.redpack();
                break;

            case 'view':
                index.redpack();
                index.hits();
                common.storage('history');
                common.report();
                require(['cim/comment'], function(comment){
                    comment.init();
                });
                //查看完整电话号码
                $('.show-number').click(function () {
                    layer.open({
                        type: 1,
                        title: '查看完整电话',
                        shadeClose: true,
                        area: ['420px', '190px'],
                        content: $('#phone'),
                    });
                });

                //图片轮播预览
                if (document.querySelector('#small-img')) {
                    require(['swiper'], function (Swiper) {
                        var myswiper = new Swiper('#small-img', {
                            slidesPerView: 3,
                            lazyLoading: true,
                            loop: true,
                            onClick: function (swiper, event) {
                                $('#small-img img').removeClass('active');
                                var imgUrl = event.target.src;
                                var index = event.target.parentNode.dataset.index;
                                event.target.className = 'active';
                                $('[rel=preview]').attr('src', imgUrl);
                                $('[rel=preview]').data('index', index);
                            },
                            onSlideChangeEnd: function (swiper) {
                                $('#small-img img').removeClass('active');
                                var index = swiper.activeIndex;
                                $('#small-img img').eq(index).addClass('active');
                                var imgIndex = $('#small-img .active').parent().data('index');
                                var imgUrl = $('#small-img img').eq(index).attr('src');
                                $('[rel=preview]').attr('src', imgUrl);
                                $('[rel=preview]').data('index', imgIndex);
                            }
                        });
                        $('[rel=prev]').click(function () {
                            myswiper.slidePrev(true);
                        });
                        $('[rel=next]').click(function () {
                            myswiper.slideNext(true);
                        });

                        $('[rel=preview]').click(function () {
                            var index = $(this).data('index');
                            var swiper = new Swiper('.full-view', {
                                //paginationClickable: true,
                                observer: true,
                                observeParents: true,
                                initialSlide: index,
                                keyboardControl: true,
                                pagination: '.swiper-pagination',
                                nextButton: '.swiper-button-next',
                                prevButton: '.swiper-button-prev'
                            });
                            $('.fullscreen').fadeIn();
                            $('body').css({
                                overflow: 'hidden'
                            });
                            $('.fullscreen img').click(function () {
                                $(this).css({
                                    width: '100%',
                                    height: '100%'
                                });
                            });
                            $('.fullscreen .fullscreen-close').click(function () {
                                $('.fullscreen').fadeOut();
                                $('body').css({
                                    overflow: 'auto'
                                });
                            });
                            $(document).keydown(function (e) {
                                if (e.keyCode == 27) {
                                    $('.fullscreen').fadeOut();
                                    $('body').css({
                                        overflow: 'auto'
                                    });
                                }
                            });
                        });
                    });
                }
                break;

            case 'add':
                require(['cim/files', 'validator'], function(files) {
                    files.init();

                    $('#form').validator({
                        timely: 2,
                        stopOnError: true,
                        theme: 'yellow_right_effect',
                        fields: {
                            'name': '标题:required;length(0~50)',
                            'phone': '电话:required;mobile|tel',
                            'code': '短信验证码:required;',
                            'captcha': '验证码:required;length(3);',
                        },
                        messages: {
                            required: "请填写{0}",
                        },
                        valid: function(form){
                            $("#form :submit").attr("disabled", "disabled").attr("value", "正在发布...").text("正在发布...");
                            var datas = new FormData();
                            var fields = $("#form").serializeArray();
                            $.each(fields, function(i, field){
                                datas.append(field.name, field.value);
                            });
                            $.each(files.list, function(i){
                                datas.append("image[]", files.list[i]);
                            });
                            datas.append("key", sys.column.key);
                            $.ajax({
                                url: '/index/api/add',
                                method: 'POST',
                                data: datas,
                                async: false, 
                                cache: false,
                                contentType: false,
                                processData: false,
                                success: function(rs){
                                    if (rs.code==1) {
                                        window.location.href = '/fabu/'+sys.column.key+'/'+rs.id;
                                    }else{
                                        layer.alert(rs.msg);
                                        $("#form :submit").removeAttr("disabled", "disabled").val("重新提交").text("重新提交");
                                    }
                                },
                                error: function(error){
                                    layer.alert(error.message);
                                    $("#form :submit").removeAttr("disabled", "disabled").val("重新提交").text("重新提交");
                                    console.log(error.message);
                                }
                            });
                        }
                    });
                });
                common.editor();
                common.captcha();
                common.radio();
                common.checkbox();
                common.value();
                
                $('#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']);
                        }
                    });
                });

                break;

            case 'edit':
                require(['cim/files', 'validator'], function(files) {
                    files.init();
                    var image = [];
                    $.getJSON("/index/api/read", { "attr":{ id:sys.data.id, cid:sys.column.id } }, function(data){
                        $.each(data.image, function(i, v){
                            image.push(v.path);
                        });
                        $('[rel=image_list]').on('click', 'em', function(){
                            image.splice($(this).parent().index(), 1);
                            $(this).parent().remove();
                        });
                    });
                    $('#form').validator({
                        timely: 2,
                        stopOnError: true,
                        theme: 'yellow_right_effect',
                        fields: {
                            'name': '标题:required;length(0~50)',
                            'phone': '电话:required;mobile|tel',
                            'code': '短信验证码:required;',
                            'captcha': '验证码:required;length(3);',
                        },
                        messages: {
                            required: "请填写{0}",
                        },
                        valid: function(form){
                            $("#form :submit").attr("disabled", "disabled").attr("value", "正在发布...").text("正在发布...");
                            var datas = new FormData();
                            var fields = $("#form").serializeArray();
                            $.each(fields, function(i, field){
                                datas.append(field.name, field.value);
                            });
                            $.each(files.list, function(i){
                                datas.append("image[]", files.list[i]);
                            });
                            datas.append("key", sys.column.key);
                            if (sys.data.id) datas.append("id", sys.data.id);
                            $.each(image, function(i){
                                datas.append("image[]", image[i]);
                            });
                            $.ajax({
                                url: '/index/api/add',
                                method: 'POST',
                                data: datas,
                                async: false, 
                                cache: false,
                                contentType: false,
                                processData: false,
                                success: function(rs){
                                    if (rs.code==1) {
                                        window.location.href = '/fabu/'+sys.column.key+'/'+rs.id;
                                    }else{
                                        layer.alert(rs.msg);
                                        $("#form :submit").removeAttr("disabled", "disabled").val("重新提交").text("重新提交");
                                    }
                                },
                                error: function(error){
                                    layer.alert(error.message);
                                    $("#form :submit").removeAttr("disabled", "disabled").val("重新提交").text("重新提交");
                                }
                            });
                        }
                    });
                });
                common.editor();
                common.value();
                common.radio();
                common.checkbox();
                break;

            case 'search':
                common.storage('search');
                common.renderHistory();
                common.deleteHistory();
                break;

                // 管理
            case 'manage':
                require(['layer', 'laydate', 'axios', 'vue'], function (layer, laydate, axios, Vue) {
                    //获取搜索信息
                    new Vue({
                        el: '#manage',
                        data: {
                            infoList: [], //信息列表
                            phone: '',
                            pwd: '', //预留密码
                            sms: {
                                text: '获取验证码',
                                lock: false,
                                captcha: '',
                                code: ''
                            },
                            info: {}, //缓存信息
                            step: 1,
                            phoneImg: '', //手机图片
                            imgChange: false, //图片上传
                            infoView: {
                                info: {
                                    phone: {},
                                },
                                end_time: {},
                                image: [],
                            }, //信息详情
                            form: '', //信息提交
                        },
                        created() {
                            if (sys.data.id) {
                                this.info.id = sys.data.id;
                                this.info.cid = sys.data.cid;
                                this.step = 2;
                                this.phoneImg = '/index/api/phone_image/id/' + this.info.id;
                            }
                            // this.step = 3;
                            common.captcha();
                        },
                        mounted: function () {
                            var _this = this;
                            laydate.render({
                                elem: "#end_time",
                                type: 'datetime',
                                change: function (value, date) {
                                    _this.infoView.end_time = value;
                                }
                            });
                        },
                        methods: {
                            //信息搜索
                            search() {
                                axios.post('/index/api/manage', {
                                    'attr': {
                                        'phone': this.phone
                                    }
                                }).then(response => {
                                    if (response.data.code == 1) {
                                        this.infoList = response.data.data;
                                    } else if (response.data.code == 0) {
                                        layer.msg(response.data.msg);
                                    }
                                }).catch(response => {
                                    console.log(response);
                                });
                            },
                            //选择信息显示验证方式
                            verifyInfo(id, key) {
                                window.location.href = '/manage/'+key+'/'+id;
                            },
                            //切换图片验证码
                            changeImgCode(event) {
                                var img = event.target;
                                img.src = '/captcha?' + Math.random();
                            },
                            //显示图片验证码弹窗
                            getVerify() {
                                var _this = this;
                                if (!this.sms.captcha) {
                                    layer.msg('请填写图片验证码');
                                    return false;
                                }
                                axios.post('/index/api/manage', {
                                        'attr': {
                                            'data_id': this.info.id,
                                            'cid': this.info.cid,
                                            'captcha': this.sms.captcha,
                                        }
                                    }).then(response => {
                                        if (response.data.code == 2) {
                                            layer.msg('验证码发送成功，请注意查收');
                                            var num = 60;
                                            _this.sms.lock = true;
                                            var timer = setInterval(function () {
                                                _this.sms.text = num + 's后重新获取';
                                                num--;
                                                if (num <= 0) {
                                                    _this.sms.text = '重新获取验证码';
                                                    _this.btnLock = false;
                                                }
                                            }, 1000)
                                        }
                                    })
                                    .catch(function (error) {
                                        console.log(error);
                                    });
                            },

                            // 验证并获取信息详情
                            checkVerify() {
                                var param = {
                                    'attr': {
                                        'data_id': this.info.id,
                                        'cid': this.info.cid,
                                        'password': this.pwd,
                                        'code': this.sms.code,
                                        'captcha': this.sms.captcha,
                                    }
                                };
                                axios.post('/index/api/manage', param).then(response => {
                                        if (response.data.code == 1) {
                                            this.info.key = response.data.key;
                                            this.infoView = response.data.data;
                                            //this.step = 3;
                                            window.location.href = '/index/index/edit/key/'+sys.column.key+'/id/'+sys.data.id;
                                        } else if (response.data.code == 0) {
                                            layer.msg(response.data.msg)
                                        }
                                    })
                                    .catch(response => {
                                        console.log(response);
                                    });
                            },
                            //图片预览
                            preview(event) {
                                var _this = this;
                                var data = event.target.files;
                                var arrFile = Array.from(data);
                                _this.form = new FormData();
                                arrFile.forEach(function (item) {
                                    _this.form.append('image[]', item, item.name);
                                })
                                _this.imgChange = true;
                                if (typeof FileReader !== 'undefined') { //浏览器能力检测
                                    _this.infoView.image = [];
                                    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) {
                                            _this.infoView.image.push({
                                                'url': this.result
                                            });
                                        }
                                    }
                                }
                            },
                            //信息提交
                            onSubmit() {
                                var formData;
                                if (this.imgChange) {
                                    //如果图片修改传图片对象
                                    for (var key in this.infoView.info) {
                                        this.form.set(key, this.infoView.info[key]);
                                    }
                                    this.form.set('area_id', this.infoView['area_id']);
                                    this.form.set('name', this.infoView.name);
                                    this.form.set('key', this.info.key);
                                    this.form.set('id', this.infoView.id);
                                    this.form.set('image', new Array());
                                    this.form.set('column_id', this.infoView.column_id);
                                    formData = this.form;
                                } else {
                                    var imgArr = [];
                                    for (var key in this.infoView.image) {
                                        imgArr.push(this.infoView.image[key].path);
                                    }
                                    this.infoView.key = this.info.key;
                                    this.infoView.info.phone = this.infoView.info.phone.value;
                                    formData = this.infoView;
                                    formData.image = imgArr;
                                }
                                axios.post('/index/api/add/', formData).then(response => {
                                    if (response.data.code == 1) {
                                        layer.msg('修改成功');
                                    }
                                }).catch(function (error) {
                                    console.log(error)
                                })
                            },
                            //信息删除
                            delInfo() {
                                var param = {
                                    id: this.info.id,
                                    key: this.info.key
                                };
                                var html = '<div class="text-center mt-md">确定要删除此条信息吗？</div>';
                                layer.open({
                                    type: 1,
                                    title: '温馨提示',
                                    shadeClose: true,
                                    resize: false,
                                    area: ['260px', '160px'], //宽高
                                    content: html,
                                    btn: ['确定'],
                                    yes: function (index, layero) {
                                        axios.post('/index/api/close/', param).then(function (response) {
                                            if (response.code == 1) {
                                                window.location.href = '/index'
                                            }
                                        }).catch(function (error) {
                                            console.log(error)
                                        })
                                    }
                                });
                            },
                            //信息置顶
                            setTop() {
                                var url = '/index/index/top/' + this.info.cid + '/' + this.info.id;
                                window.location.href = url;
                            },
                            //设置红包
                            setRedPacket() {
                                var red = '/index/index/redpacket/' + this.info.cid + '/' + this.info.id;;
                                window.location.href = red;
                            }
                        }
                    });
                });
                // 信息删除
                // common.confirm();
                break;

                //置顶
            case 'top':
                require(['cim/finance'], function(finance){
                    finance.meter();
                });

                // 提交
                $('[rel=cashier]').click(function () {
                    var rs = {
                        'id': sys.data.id, //信息id
                        'cid': sys.data.cid, //栏目id
                        'num': parseInt($('[name=num]').val()),
                        'payment': parseInt($("input[name=payment]:checked").val()),
                    };
                    if (!rs.num) {
                        layer.msg('置顶天数要大于0');
                        return false;
                    } else {
                        // 生成订单
                        rs.days = rs.num;
                        generateOrder('/index/api/top', rs);
                    }
                });

                break;
                //红包
            case 'redpack':
                var info = sys.data;
                $('[rel=name]').text(info.name);
                //选择支付方式
                $(".pay_type img").on('click', function () {
                    var val = $(this).data('value');
                    if (val == 3) {
                        $(this).attr('src', '/static/img/user/alipay2.png');
                        $('[rel=weixin]').attr('src', '/static/img/user/weixin1.png');
                    } else {
                        $(this).attr('src', '/static/img/user/weixin2.png');
                        $('[rel=alipay]').attr('src', '/static/img/user/alipay1.png');
                    }
                });
                // 提交
                $('[rel=payment]').click(function () {
                    var pay_way = $("input[name='payment']:checked").val(); //支付方式
                    var type = $("input[name='type']:checked").val(); //支付方式
                    var pay_type = pay_way == 0 ? 0 : 1; //付款类型
                    var $this = $(this);
                    var money = parseFloat($('[name="money"]').val()); //置顶时间
                    var number = $("input[name='num']").val();
                    var param = {
                        'id': info.id, //信息id
                        'cid': info.cid, //栏目id
                        'money': money,
                        'payment': pay_way,
                        'num': number,
                        'type': type
                    };
                    if (!money) {
                        layer.msg('红包金额要大于0');
                        return false;
                    } else {
                        // 生成红包订单
                        generateOrder('/index/api/redpack', param);
                    }
                });
                break;
        }
    }

    if ($.inArray(sys.action, ['index']) > -1) {
        require(['swiper'], function (Swiper) {
            var mySwiper = new Swiper('#swiper', {
                // 如果需要分页器
                pagination: '.swiper-pagination',
                speed: 1000,
                autoplay: 5000,
                loop: true,
                // 如果需要前进后退按钮
                nextButton: '.swiper-button-next',
                prevButton: '.swiper-button-prev',
                paginationClickable: true,
                // 如果需要滚动条
                // scrollbar: '.swiper-scrollbar',
            });
        });
    }



    if (sys.controller == 'user') {

        require(['layer', 'axios'], function (layer, axios) {
            //清空全部消息
            $("#clear-all").click(function () {
                var param = {
                    'action': 'delete',
                };
                var html = '<div class="text-center mt-md">确定要清空全部消息吗？</div>';
                layer.open({
                    type: 1,
                    title: '温馨提示',
                    shadeClose: true,
                    resize: false,
                    area: ['260px', '160px'], //宽高
                    content: html,
                    btn: ['确定'],
                    yes: function (index, layero) {
                        axios.post('/message/api/message/', param).then(function (response) {
                            if (response.data.code == 1) {
                                window.location.reload();
                            }
                        }).catch(function (error) {
                            console.log(error);
                        });
                    }
                });
            });
            //单个删除消息
            $(".delete").click(function () {
                var dataid = $(this).data('id');
                var param = {
                    'action': 'delete',
                    'id': dataid
                };
                var html = '<div class="text-center mt-md">确定要删除该消息吗？</div>';
                layer.open({
                    type: 1,
                    title: '温馨提示',
                    shadeClose: true,
                    resize: false,
                    area: ['260px', '160px'], //宽高
                    content: html,
                    btn: ['确定'],
                    yes: function (index, layero) {
                        axios.post('/message/api/message/', param).then(function (response) {
                            if (response.data.code == 1) {
                                window.location.reload();
                            }
                        }).catch(function (error) {
                            console.log(error);
                        });
                    }
                });
            });

        });


    }


});