$.fn.extend({
    animateCss: function (animationName, callback) {
        var animationEnd = (function (el) {
            var animations = {
                animation: 'animationend',
                OAnimation: 'oAnimationEnd',
                MozAnimation: 'mozAnimationEnd',
                WebkitAnimation: 'webkitAnimationEnd',
            };

            for (var t in animations) {
                if (el.style[t] !== undefined) {
                    return animations[t];
                }
            }
        })(document.createElement('div'));

        this.addClass('animated ' + animationName).one(animationEnd, function () {
            //$(this).removeClass('animated ' + animationName);
            callback && callback.call(this, $(this), animationName);
        });

        return this;
    },
});

var app = {
    /**
     * 请求id
     */
    id: location.search.substring(1).replace(/ID=|\&pic=1/gi, ''),
    /**
     * 切换画风id
     */
    switchId: 0,
    /**
     * 切换风景id
     */
    bgId: 0,
    /**
     * 切换风格类型
     */
    type: 1,
    /**
     * 我的相片列表
     */
    imgList: [],
    /**
     * 广告切换
     */
    adsSwiper: function () {
        var html = [];
        var $elem = $('.ads-swiper')

        __config.adsPath && __config.adsPath.forEach(function (item) {
            html.push('<div class="swiper-slide"><a href="' + (item.link || '#') + '"><img src="' + (item.image || 'static/images/adds/4dart.jpg') + '"><a></div>')
        })

        if (!html.length) {
            html.push('<div class="swiper-slide"><a href="#"><img src="static/images/adds/4dart.jpg"><a></div>')
        }

        $elem.find('.swiper-wrapper').html(html.join(''))

        new Swiper($elem[0], {
            autoplay: {
                delay: 3000,
                stopOnLastSlide: false,
                disableOnInteraction: true,
            },
            pagination: {
                el: $elem.find('.swiper-pagination')[0],
                bulletClass: 'my-bullet'
            }
        });
    },
    /**
     * 画风切换
     */
    stlSwiper: function () {
        var $elem = $('.stl-swiper')
        if (this.stlSwiper.swiper) {
            this.stlSwiper.swiper.destroy()
        }

        let html = ''

        if (this.type==2) {
            html = `<div class="swiper-wrapper">
                <div data-msg="1" class="swiper-slide style-1"></div>
                <div data-msg="2" class="swiper-slide style-2"></div>
                <div data-msg="3" class="swiper-slide style-3"></div>
                <div data-msg="4" class="swiper-slide style-4"></div>
                <div data-msg="5" class="swiper-slide style-5"></div>
            </div>`
        } else{
            html = `<div class="swiper-wrapper">
                <div data-msg="1" class="swiper-slide style-1"></div>
                <div data-msg="2" class="swiper-slide style-2"></div>
                <div data-msg="3" class="swiper-slide style-3"></div>
                <div data-msg="4" class="swiper-slide style-4"></div>
                <div data-msg="5" class="swiper-slide style-5"></div>
            </div>`
        }
        $elem.html(html)
        this.stlSwiper.swiper = new Swiper($elem[0], {
            //speed: 300,
            freeMode: true,
            slidesPerView: 3.5,
        });
        var time;
        $elem.find('.swiper-slide').on('click', function () {
            var $this = $(this);
            var msg = $this.data('msg')

            app.checkOperationTimeout()
            let tmp = ''

            if (app.type == 2) {
                if (app.bgId == msg) {
                    // 已选择的不再执行
                    return;
                }
                tmp = 'bg '
                app.bgId = msg
            }else{
                if (app.switchId == msg) {
                    // 已选择的不再执行
                    return;
                }
                tmp = 'switch '
                app.switchId = msg
                
            }

           

            if (!app.sendCheck()) {
                return;
            }

            if (time && (Date.now() - time < __config.switchInterval * 1000)) {
                app.showLoadingSwitch(function () {
                    $elem.find('.swiper-slide').removeClass('active');
                    $this.addClass('active');
                })
            } else {
                $elem.find('.swiper-slide').removeClass('active')
                $this.addClass('active')
            }

            time = Date.now();
           

            app.send(tmp + msg)
        });

        $elem.find('.swiper-slide').each(function () {
            var style = $(this).data('msg');
            if (style) {
                var img = new Image()
                img.src = (__config.staticUrl || 'static') + `/images/styles${app.type==2?'1':''}/` + style + '-active.png';
            }
        })
    },
    /**
     * 我的相片滚动
     */
    picSwiper: function () {
        if (this.picSwiper.swiper) {
            this.picSwiper.swiper.destroy()
        }
        this.picSwiper.swiper = new Swiper($('.pic-swiper')[0], {
            speed: 300,
            slidesPerView: 'auto',
            freeMode: true,
            direction: 'vertical',
            setWrapperSize: true,
            scrollbar: {
                el: '.swiper-scrollbar',
            },
        });
    },
    events: function () {
        var self = this,
            $picList = $('.my-pic-list');

        if (__config.link) {
            $('.logo').attr('href', __config.link)
        }

        $picList.find('header').on('touchstart', function (event) {
            event.preventDefault();
        });

        $picList.find('.btn-back').on('touchend', function (event) {
            event.preventDefault();
            $picList.hide()
        });

        

        $('.swt-style').on('click','a', function (event) {
            self.type = $(event.currentTarget).data('id')
            $(event.currentTarget).addClass("active").siblings().removeClass("active");
            self.stlSwiper()
            if (self.type==2) {
                $('.stl-swiper').addClass('stl-swiper1')
            }else {
                $('.stl-swiper').removeClass('stl-swiper1')
            }
            $('.swiper-wrapper').find('.swiper-slide').removeClass('active');
                    $(`.swiper-slide[data-msg=${self.type==2?self.bgId:self.switchId}]`).addClass('active');
        });

        $('.btn-pic-list').on('click', function (event) {
            app.send('close')
            $picList.show()
            self.renderPictures()
        });

        $('.btn-pic-take').on('click', function (event) {
            app.checkOperationTimeout()

            if (!app.sendCheck()) {
                return;
            }

            self.send('photo empty')
        });

        $('.app-view .close').on('click', function (event) {
            self.hideView()
        });

        $('.app-alert .btn-use').on('click', function () {
            var $alert = $('.app-alert')
            app.hideMask()
            $alert.removeClass($alert.data('class') + ' animated zoomIn')
            var text = $(this).text();
            if (text == '尝试使用' || text == '再次使用') {
                app.send('request')
            }

        })

        $('.app-alert .btn-link').on('click', function () {
            if ($(this).text() == '重新拍照') {
                var $alert = $('.app-alert')
                app.hideMask()
                $alert.removeClass($alert.data('class') + ' animated zoomIn')
                $('.btn-pic-take').click()
            }
        })
    },
    showMask: function (clazz) {
        var $elem = $('.app-mask');
        if (clazz) {
            $elem.addClass(this.showMask._clazz = clazz)
        }
        $elem.css('display', 'block')
    },
    hideMask: function () {
        var $elem = $('.app-mask');
        if (this.showMask._clazz) {
            $elem.removeClass(this.showMask._clazz)
            this.showMask._clazz = null
        }
        $elem.css('display', 'none')
    },
    showAlert: function (msg, icon) {
        this.showMask();
        var $alert = $('.app-alert');
        var $btns = $alert.find('.btns a');
        $alert.data('class', icon).addClass(icon).animateCss('zoomIn')
        $alert.find('.tips').html(msg)
        if (/error|used/.test(icon)) {
            $btns.eq(0).text('尝试使用')
        } else if (/timeout|stop/.test(icon)) {
            $btns.eq(0).text('再次使用')
        } else if (/fail/.test(icon)) {
            $btns.eq(0).text('重选画风')
        }

        if (/used|timeout|stop|error/.test(icon)) {
            $btns.eq(1).text('刷新页面').attr('href', $btns.eq(1).data('href'))
        } else if (/fail/.test(icon)) {
            $btns.eq(1).text('重新拍照').attr('href', 'javascript:;')
        }

    },
    showActionTips: function (delay, done) {
        var $elem = $('.app-action-tips');
        var flag = flag || 1;

        delay = delay || 1000;

        app.showMask('white')
        $elem.find('.content').hide()
        $elem.find('.content.face-' + flag).show()
        $elem.animateCss('zoomIn', function () {
            var timer = setInterval(() => {
                if (++flag > 4) {
                    $elem.removeClass('animated zoomIn');
                    clearInterval(timer)
                    if (!app.is_action) {
                        app.hideMask('white')
                        done && done()
                    }

                    return;
                }

                $elem.find('.content').hide()
                $elem.find('.content.face-' + flag).show()
            }, delay);
        })
    },
    showLoading: function (msg) {
        msg = msg || '相片正在生成中，请耐心等候'

        this.showMask();
        $('.app-action-tips .content').css('display', 'none');
        $('.app-action-tips .content.loading').css('display', 'block').find('.tips').html(msg);
        $('.app-action-tips').addClass('animated zoomIn') //.animateCss('zoomIn')
    },
    hideLoading: function () {
        this.hideMask();
        $('.app-action-tips .content.loading').css('display', 'none');
        $('.app-action-tips').removeClass('animated zoomIn')
    },
    showLoadingSwitch: function (done) {
        this.showMask();
        $('.app-action-tips .content').css('display', 'none');
        $('.app-action-tips .content.loading-switch').css('display', 'block')
        $('.app-action-tips .content.loading-switch .tips').html('正在切换'+(app.type==2?'风景':'画风'))
        $('.app-action-tips').animateCss('zoomIn', function ($elem, aname) {
            setTimeout(function () {
                app.hideMask();
                $elem.removeClass('animated ' + aname);
                done && done()
            }, 1000);
        })
    },
    renderPictures() {
        var html = [];
        console.log('====================================');
        console.log(this.imgList);
        console.log('====================================');
        this.imgList.forEach(function (item) {
            html.push('<div class="swiper-slide">');
            html.push('    <div class="img'+(item.vertical?' vertical':'')+'">');
            html.push('      <img src="' + item.url + '?v=' + Date.now() + '">');
            html.push('    </div>');
            html.push('    <div class="info">');
            html.push('      <div class="time">');
            html.push('        ' + item.datetime);
            html.push('      </div>');
            html.push('      <div class="style style-' + item.id + '"></div>');
            html.push('    </div>');
            html.push('</div>');
        })

        if (!html.length) {
            html.push('<div class="swiper-slide" style="color:#999;border-bottom:none">暂无相片</div>');
        }

        $('.pic-swiper .swiper-wrapper').html(html.join(''));
        $('.pic-swiper .swiper-wrapper img').click(function (e) {
            wx.previewImage({
                current: e.currentTarget.src.split('?v=')[0],
                urls: app.imgList.map(function (item) {
                    return item.url
                })
            });
        });

        this.picSwiper();
    },
    showView: function (json) {
        this.hideLoading()
        setTimeout(function () {
            // app.showMask();
            // $('.app-view').animateCss('zoomIn', function () {
            //     app.send('close')
            // }).find('.img').html('<img src="' + json.url + '?v=' + Date.now() + '">')

            var img = new Image()
            img.src = json.url + '?v=' + Date.now()
            img.onload = img.onerror = function(){
                app.showMask();
                var $view = $('.app-view')
                if(img.width<img.height){
                    json.vertical = true
                    $view.addClass('vertical')
                }
                app.imgList.unshift(json);
                $view.animateCss('zoomIn', function () {
                    app.send('close')
                }).find('.img').html('<img src="' + json.url + '?v=' + Date.now() + '">')
            }
        }, 300);

    },
    hideView: function () {
        this.hideMask();
        $('.app-view').removeClass('animated zoomIn')
    },
    connection: function () {
        console.log('正在尝试连接')
        try {
            var timer
            this.websocket = new WebSocket(__config.ws);
            this.websocket.onclose = function (e) {
                app.is_connect = false
                app.checkTimeout(true)
                app.checkOperationTimeout(true)
                console.error('连接失败', e)
                setTimeout(function () {
                    app.connection()
                }, 5000)
            }.bind(this);

            this.websocket.onopen = function (msg) {
                this.is_connect = true
                this.is_connect_ok = null
                this.send('request')
            }.bind(this);

            this.websocket.onmessage = function (msg) {
                console.log(msg.data)
                if (typeof msg.data == "string") {
                    switch (msg.data) {
                        case 'error 101':
                            console.log('发送的消息有误');
                            break;
                        case 'error 102':
                            //pop_tip('连接打印机失败<br/>请重新刷新页面');
                            break;
                        case 'error 302':
                            app.hideLoading()
                            app.showAlert('网络异常，生成失败', 'fail')
                            break;
                        case 'error 404':
                            app.switchId = 0;
                            app.showAlert('切换图片失败', 'error');
                            break;
                        case 'error 500':
                            app.is_connect_ok = false
                            if (app.is_send_msg) {
                                app.hideLoading()
                                app.showAlert('网络异常，请稍后再试', 'error');
                            }
                            break;
                        case 'error 600':
                            //console.log('未定义的消息');
                            break;
                        case 'error 707':
                            app.showAlert('二维码不正确', 'error')
                            break;
                        case 'error 808':
                            app.is_lose_used = true
                            if (app.is_send_msg) {
                                app.showAlert('当前画屏正在被使用，请稍后', 'used');
                            }
                            break;
                        case 'error 202':
                            break;
                        case 'error 909':
                            app.is_other_used = true;
                            if (app.is_send_msg) {
                                app.showAlert('当前画屏正在被使用，请稍后', 'used');
                            }
                            break;
                        case 'ok 200':
                            console.log('切换图片成功')
                            break;
                        case 'ok 201':
                            console.log('操作成功')
                            app.is_connect_ok = null
                            app.checkTimeout(true)
                            app.checkOperationTimeout(true)
                            break;
                        case 'ok 300':
                            app.hideLoading();
                            app.is_lose_used = false;
                            app.is_other_used = false;
                            app.is_connect_ok = true;
                            app.checkTimeout()
                            app.checkOperationTimeout()
                            break;
                        case 'ok 301':
                            console.log('拍照成功,开始等待照片')
                            app.is_action = false;
                            app.checkTimeout(true)
                            app.checkOperationTimeout(true)
                            app.showActionTips(1000, function () {
                                app.showLoading()
                            });
                            timer = setTimeout(function () {
                                app.send('close')
                                setTimeout(() => {
                                    app.hideLoading()
                                    app.showAlert('网络异常，生成失败', 'fail')
                                }, 500);
                            }, 20000);
                            break;
                        case 'ok 1000':
                            app.is_lose_used = false;
                            app.is_other_used = false;
                            break;
                        default:
                            try {
                                app.is_action = true;
                                timer && clearTimeout(timer)
                                var json = JSON.parse(msg.data)
                                if (json.url) {
                                    app.showView(json)
                                }
                            } catch (error) {
                                console.error(error)
                            }

                            break;
                    }
                    app.is_send_msg = false

                } else {
                    console.log("error 600");
                }
            }.bind(this);
        } catch (error) {
            console.error(error)
            setTimeout(function () {
                app.connection()
            }, 5000)
        }
    },
    send: function (msg) {
        if (msg === 'request') {
            this.websocket.send(msg + ' ' + this.id)
        } else if (msg === 'close') {
            this.websocket.send(msg + ' 0')
        } else {

            if (app.is_connect_ok == null && !app.is_other_used) {
                app.websocket.send('request ' + this.id)
            }

            setTimeout(function () {
                app.websocket.send(msg)
            }, 300);
        }
    },
    sendCheck() {

        if (!this.is_connect) {
            app.showAlert('网络异常，请稍后再试', 'error');
            return false;
        } else if (this.is_other_used) {
            app.showAlert('当前画屏正在被使用，请稍后', 'used');
            return false;
        } else if (this.is_lose_used) {
            app.showAlert('当前画屏正在被使用，请稍后', 'used');
            return false;
        } else if (this.is_connect_ok === false) {
            app.showAlert('网络异常，请稍后再试', 'error');
            return false;
        }

        this.is_send_msg = true;

        return true;
    },
    checkOperationTimeout(stop) {
        this.operationTimer && clearTimeout(this.operationTimer)

        if (stop) {
            // 暂停检测
            return
        }

        this.operationTimer = setTimeout(function () {
            if (app.is_connect_ok) {
                app.send('close')
                app.showAlert('因您长时间未使用<br>已无法操作艺术照一体机', 'timeout')
            }
        }, (__config.noOperationTimeout || 30) * 1000);
    },
    checkTimeout(stop) {
        this.timeoutTimer && clearTimeout(this.timeoutTimer)

        if (stop) {
            // 暂停检测
            return
        }
        // 强制超时结束控制 180s
        this.timeoutTimer = setTimeout(function () {
            if (app.is_connect_ok) {
                app.send('close')
                app.showAlert('抱歉，因您长时间使用<br>让下一位小伙伴体验吧', 'timeout')
            }
        }, (__config.timeout || 180) * 1000);
    },
    render: function () {
        this.connection()
        this.events()
        this.adsSwiper()
        this.stlSwiper()
        this.picSwiper()

        // this.imgList.push({
        //     "id": 7,
        //     "url": "http://ost.4dage.com/4dart/img/31913592.jpg",
        //     "datetime": "2018年10月29日 16:27:26"
        // })
    }
}
app.render()

window.onbeforeunload = function () {
    try {
        app.websocket.close();
        app.websocket = null;
    } catch (ex) {}
};

//app.showAlert('抱歉，因您长时间使用<br>让下一位小伙伴体验吧', 'timeout')
//app.showAlert('因您长时间未使用<br>已无法操作艺术照一体机', 'stop')
//app.showAlert('当前画屏正在被使用，请稍后', 'used')
//app.showAlert('网络异常，请稍后再试', 'error')
//app.showAlert('网络异常，生成失败', 'fail')
//app.showAlert('您已丢失使用权', 'used');