require('3party/question-detail.page.css');

let $ = require('yoho-jquery'),
    yoho = require('yoho-app'),
    tipDg = require('plugin/tip'),
    share = require('common/share');

let question = {
    $base: $('#qs-wrap'),
    init: function() {
        let that = this;

        this.$errTip = $('.error-tip');
        this.$mobile = $('.user-mobile > input');
        this.$item = $('.qs-item, .sub-qs-item', this.$base);
        this.startTime = Date.parse(new Date()) / 1000;

        if (this.$base.length) {
            let data = this.$base.data();

            this.shareInfo = {
                title: data.title,
                link: 'http://m.yohobuy.com/3party/questionnaire/' + data.id,
                desc: data.desc,
                imgUrl: data.img
            };

            // 设置分享信息
            share(this.shareInfo);

            // 设置app页面信息及分享信息
            if (yoho.isApp) {
                yoho.ready(function() {
                    yoho.invokeMethod('get.pageType', {
                        pageType: 'questionnaire'
                    });
                    yoho.invokeMethod('set.shareInfo', that.shareInfo);
                });
            }
        }

        this.bindEvent();
    },
    bindEvent: function() {
        let that = this;

        this.$base.on('click', '.radio-option', function() {
            let $this = $(this),
                $par = $this.parent();
            let jid = $this.data('jid');

            if (!$this.hasClass('on')) {
                $this.siblings('.on').removeClass('on');
                $this.addClass('on');

                if ($par.hasClass('qs-item')) {
                    that.setSubQuestion($par.next('.sub-qs-wrap'), jid);
                }
            }
        }).on('click', '.check-option', function() {
            let $this = $(this);

            if ($this.hasClass('on')) {
                $this.removeClass('on');
            } else {
                $this.addClass('on');
            }
        }).on('click', 'input', function(e) {
            if (e && e.stopPropagation) {
                e.stopPropagation();
            } else {
                window.event.cancelBubble = true;
            }
        });

        $('.submit-btn').click(function() {
            that.saveAnswers(that.packAnswersInfo());
        });
    },
    setSubQuestion: function($wrap, ids) {
        if (!$wrap.length) {
            return;
        }

        $wrap.slideUp();
        $wrap.children().addClass('hide');

        if (typeof ids === 'string' || typeof ids === 'number') {
            ids = [ids];
        }

        if (!Array.isArray(ids)) {
            return;
        }

        let i;

        for (i = 0; i < ids.length; i++) {
            if (ids[i]) {
                $wrap.find('.sub-' + ids[i]).removeClass('hide');
            }
        }
        $wrap.slideDown();
    },
    packAnswersInfo: function() {
        let that = this;
        let answer = [];
        let $errDom;

        this.$item.each(function() {
            let $this = $(this);

            if ($errDom || $this.hasClass('hide')) {
                return;
            }

            let data = $this.data();
            let ans = [];
            let errText = '';

            if (+data.type === 3) {
                $this.find('.text-input').each(function() {
                    let val = $.trim($(this).val());

                    if (val) {
                        ans.push({
                            questionIndex: data.index,
                            answerIndex: ans.length,
                            addon: val
                        });
                    }

                    if (val.length > 400) {
                        errText = '输入内容过长';
                    }


                });
            } else {
                $this.find('.on').each(function() {
                    let $that = $(this),
                        $input = $that.find('input'),
                        a = {
                            questionIndex: data.index,
                            answerIndex: $that.data('index')
                        };

                    if ($input && $input.length) {
                        a.addon = $input.val();
                    }

                    ans.push(a);
                });

                if (data.type === '1') {
                    ans.length = 1;
                }
            }

            if (errText || !ans.length) {
                $errDom = $this;

                if (!errText) {
                    errText = +data.type === 3 ? '请填写一条回答' : '请选择一个选项';
                }

                that.showError(errText, $errDom);
            } else {
                answer = $.merge(answer, ans);
            }
        });

        if ($errDom) {
            return [];
        } else {
            return answer;
        }
    },
    showError: function(tip, $errDom) {
        let that = this;

        this.$errTip.html(tip);

        if (this.timer) {
            clearTimeout(this.timer);
        }

        this.timer = setTimeout(function() {
            that.$errTip.empty();
        }, 5000);

        if ($errDom) {
            let offTop = $errDom.offset().top,
                errHeight = this.$errTip.outerHeight();

            $('html,body').animate({scrollTop: offTop - errHeight}, 500);
        }
    },
    saveAnswers: function(info) {
        var that = this;

        if (this.saving || !info || !info.length) {
            return;
        }

        this.saving = true;

        setTimeout(function() {
            that.saving = false;
        }, 5000);

        $.ajax({
            type: 'POST',
            url: '/3party/questionnaire/submit',
            data: {
                id: this.$base.data('id'),
                uid: this.$base.data('cid'),
                startTime: this.startTime,
                endTime: Date.parse(new Date()) / 1000,
                frontAnswers: JSON.stringify(info),
                mobile: this.$mobile.val()
            }
        }).then(function(data) {
            that.saving = false;
            if (data.code === 200 || data.code === 206) {
                let tip = '调查问卷已成功提交,感谢您的帮助!';

                if (data.code === 206 && data.message) {
                    tip = data.message;
                }

                tipDg.show(tip);

                setTimeout(function() {
                    if (yoho.isApp) {
                        yoho.invokeMethod('go.back');
                    } else {
                        window.history.go(-1);
                    }
                }, 2000);
            } else {
                tipDg.show(data.message || '网络出了点问题~');
            }
        });
    }
};

let tipDialog = {
    $base: $('#tip-dialog'),
    init: function() {
        var that = this;

        this.$base.on('click', '.close-btn', function() {
            that.hide();
        });
        this.$base.on('click', '.back-btn', function() {
            window.history.go(-1);
        });
    },
    show: function() {
        this.$base.removeClass('hide');
    },
    hide: function() {
        this.$base.addClass('hide');
    }
};

tipDialog.init();
question.init();

if (question.$base.length) {
    $('.nav-back').removeAttr('href').click(function() {
        tipDialog.show();
    });
} else if (yoho.isApp) {
    $('.qs-err a').removeAttr('href').click(function() {
        yoho.invokeMethod('go.back');
    });
}