$.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;
    },
});

const ONEDAY = 86400000



var app = {
    /**
     * 请求id
     */
    id: __utils.getUrlParam('ID'),
    /**
     * 请求时间戳
     */
    timestamp: __utils.getUrlParam('time'),
    /**
     * 切换风格id
     */
    switchId: '',



    /**
     * 事件处理
     */

    events: function () {
        var self = this,
            $picList = $(".ai_pic>li");
        var time;

        //画风切换
        $picList.on("click", function () {
            var $this = $(this);
            var msg = $this.data('msg')
            app.checkOperationTimeout()
            console.log(msg);
            if ('switch ' + app.switchId == msg) {
                // 已选择的不再执行
                return;
            }

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

            if (time && (Date.now() - time < __config.switchInterval * 1000)) {
                app.showLoadingSwitch(function () {
                    $this.addClass("active").siblings().removeClass("active");
                })
            } else {
                $this.addClass("active").siblings().removeClass("active");
            }

            time = Date.now();
            app.switchId = msg.split(' ')[1]
            console.log(app.switchId,'app.switchId');
            app.send(msg)
        });

        //跳转拍照页面
        $('.photo').on("click",function () {
            
            app.checkOperationTimeout()
            if (!app.sendCheck()) {
                return;
            }
            $(`.body > div[id="work"]`).fadeIn().siblings().fadeOut()
            $('.mask').show()
            self.send('readyphoto 1')
        })

        // 确认拍照
        $('#takePhoto').on("click",function () {
            
           
            app.checkOperationTimeout()
            if (!app.sendCheck()) {
                return;
            }
            $('#comfirmcon').fadeOut()
            $('#selectcon').css({'visibility':'visible'})
            $('.mask').hide()

            self.send('photo 1')
        })

        

        //返回
        $('#back').on("click",function () {

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

            $(`.body > div[id="app"]`).fadeIn().siblings().fadeOut()
            self.send('menu 1')
        })

        //返回拍照页面
        $('#rephoto').on("click",function () {
       
            app.checkOperationTimeout()
            if (!app.sendCheck()) {
                return;
            }

            $('#comfirmcon').fadeIn()
            $('#selectcon').css({'visibility':'hidden'})
            $('.mask').show()


            self.send('rephoto 1')
        })

        //拍照完成
        $('#useit').on("click",function () {

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

            self.send('usephoto 1')
        })

         //返回拍照
         $('#backtophoto').on("click",function () {
            window.location.reload()
        })

        $('#download').on("click",function () {
            app.showAlert('请长按图片保存', 'save');
        })

        $('#quan').on("click",function () {
            app.showAlert('请长按图片保存，分享朋友圈', 'save');
        })


        $('.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 == '再次使用'|| text == '重选画风') {
                app.send('request')
                $(`.body > div[id="app"]`).fadeIn().siblings().fadeOut()
            }
        })

        $('.app-alert .btn-link').on('click', function () {
            if ($(this).text() == '确定'||$(this).text() == '取消') {
                var $alert = $('.app-alert')
                app.hideMask()
                $alert.removeClass($alert.data('class') + ' animated zoomIn')
            }
        })
    },

    /**
     * 检验时间戳
     */
    checkTimestamp(){
        let del = (new Date()).getTime() - this.timestamp
        if (del>ONEDAY) {
            return false
        }
        return true
    },
    
  
    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('重选画风')
        } else if (/save/.test(icon)) {
            $btns.eq(0).text('确定')
        }

        

        if (/used|timeout|stop|error|fail|save/.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').animateCss('zoomIn', function ($elem, aname) {
            setTimeout(function () {
                app.hideMask();
                $elem.removeClass('animated ' + aname);
                done && done()
            }, 1000);
        })
    },

    renderPictures() {
        var html = [];
        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 () {
            wx.previewImage({
                current: this.src,
                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(){
                $('.myImg').attr('src', json.url + '?v=' + Date.now())
                $(`.body > div[id="myPhoto"]`).fadeIn().siblings().fadeOut()
                app.send('close')
                // 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('.myImg').attr('src', json.url + '?v=' + Date.now())
            }
        }, 300);

    },
    hideView: function () {
        this.hideMask();
        $('.app-view').removeClass('animated zoomIn')
    },


    connection: function () {
        if (!this.checkTimestamp()) {
             return app.showAlert('二维码超时不可用', 'save')
        }
        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) {
                if (typeof msg.data == "string") {
                    switch (msg.data) {
                        
                        case 'timeout 0':
                            app.hideLoading()
                            app.send('close')
                            app.showAlert('抱歉，因您长时间未使用<br>让下一位小伙伴体验吧', 'timeout')
                            break;
                        case 'error 101':
                            console.log('发送的消息有误');
                            break;
                        case 'error 102':
                            //pop_tip('连接打印机失败<br/>请重新刷新页面');
                            break;
                        case 'error 302':
                            app.hideLoading()
                            app.showAlert('网络异常，生成失败', 'fail')
                            break;
                        case 'error 303':
                            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 808':
                            app.is_lose_used = true;
                            app.is_other_used = true;
                        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 909':
                            app.send('close')
                            setTimeout(() => {
                                app.hideLoading()
                                app.showAlert('生成图片失败，请稍后再试', 'fail')
                            }, 500);
                            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.checkTimeout(true)
                            app.checkOperationTimeout(true)
                            // app.showLoading()
                            break;

                        case 'ok 203':
                            console.log('正在合成图片')
                            app.is_action = false;
                            app.checkTimeout(true)
                            app.checkOperationTimeout(true)
                            app.showLoading()

                            // 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('menu 1')
            this.websocket.send(msg + ' 0')
        } else {
            app.websocket.send(msg)
        }
    },
    sendCheck() {

        if (!this.is_connect) {
            app.showAlert('网络异常，请稍后再试', 'error');
            return false;
        } else if (this.is_other_used) {
            app.showAlert('当前有用户正在进行拍照换装<br/>请稍后刷新页面再次尝试', 'used');
            return false;
        } else if (this.is_lose_used) {
            app.showAlert('当前有用户正在进行拍照换装<br/>请稍后刷新页面再次尝试', '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.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) {}
};