var RequestComment = require("request/comment")
var Util = require("util")
var _ = require("underscore")

var comment3Uniqid = "6e1860694c9548a9725576e7c2263429"
var commentListTmp = __inline('./commentList.tmpl')
var commentHeaderTmp = __inline('./commentHeader.tmpl')
var oneLevelCmtTmp = __inline('./oneLevelComment.tmpl')
var twoLevelCmtTmp = __inline('./twoLevelComment.tmpl')
var loadMoreRepliesTmp = __inline('./loadMoreReplies.tmpl')

var prevent = function (e) {
    e.preventDefault()
}

class DwArticle {
    constructor() {
        this.ReqComment = new RequestComment({
            // domain: location.hostname.replace('cn', 'com'),
            // url: location.pathname
            domain: 'www.duowan.com',
            url: '/news/357142680655.html'
        })
        this.$pageWrap = $('#page_wrap')//最外层容器
        this.userInfo = {} //用户信息
        this.totalJson
        this.$comment = $('.common-comment')
        this.$fixedCommentArea = $('.fixed-comment-area')
        this.$writeComment = this.$fixedCommentArea.children('.comment-textarea')
        this.$emitComment = this.$fixedCommentArea.children('.emit-comment')
        this.$commentBar = $('.fixed-comment-bar')

        this.$currentCmtBtn//保存当前的回复的按钮

        this.$fixedShade = $('.fixed-shade')

        this.init()
    }
    init() {
        let req = this.ReqComment
        let self = this

        this.lazyload()
            .setShareLink()
            .loadMoreRec()
            .setReplyBtn()
            .setAgreeBtn()
            .setShareBtn()
            .setInputFit()
            .loadMoreReplies()
            .getUserinfo()
            .setMoveEvent()


        $.when(req.totaljson(comment3Uniqid), req.comments(comment3Uniqid, "hot")).done((totalJson, cmtList) => {
            if (totalJson[1] == 'success') self.totalJson = totalJson[0].show

            if (cmtList instanceof Array) {
                cmtList.forEach((item, index) => {
                    if (parseInt(item.comment_reply_total) > 3) {
                        var len = item.reply.length

                        item.lastR = item.reply[len - 1]
                    }
                })
                cmtList = cmtList.slice(0, 3)
                self.render(self.totalJson, cmtList)
            }

        })

        this.$fixedShade.on('click', () => {
            this.$fixedShade.removeClass('active')
            this.$fixedShade[0].$curEle.removeClass('show')
            this.$writeComment.val('')
            this.$commentBar.css('display', '-webkit-box')

            this.$pageWrap.off('touchmove', prevent)
        })

        this.$fixedShade.on('touchmove', prevent)
    }

    getUserinfo() {
        if (Util.isLoggedIn()) {
            this.ReqComment.getLoginInfo().done((data) => {
                this.userInfo = data && data.login_info
            })
        }
        return this
    }

    render(totalJson, cmtList) {
        var self = this
        $('.comment-num').text(totalJson.total_num)
        this.$comment.append(commentListTmp({
            cmtList: cmtList,
            morehref: self.$commentBar.find('.comment-num').attr('href'),
            minLength: 3
        }))
    }

    setAgreeBtn() {
        var self = this
        $('body').on('click', '.btn-agree', function () {
            let cid = $(this).data('cid')
            self.ReqComment.agree(comment3Uniqid, cid)
                .done((data) => {
                    if (data.rs) {
                        if (data.vote == 1) {
                            $(this).addClass('have-agree').text($(this).text() * 1 + 1)
                            localStorage.setItem(cid, 1)
                        } else {
                            $(this).removeClass('have-agree').text($(this).text() * 1 - 1)
                            localStorage.removeItem(cid)
                        }
                    }

                })
                .fail((data) => {
                })
        })
        return this
    }

    setReplyBtn() {
        var self = this

        $('body').on('click', '.btn-reply,.towrite-comment', function (e) {
            self.$fixedCommentArea.addClass('show')
            self.$fixedShade.addClass('active')
            self.$commentBar.css('display', 'none')
            self.$fixedShade[0].$curEle = self.$fixedCommentArea
            self.$writeComment.focus()

            self.$emitComment.attr('data-cid', $(this).data('cid') ? $(this).data('cid') : '')

            self.$currentCmtBtn = $(this)

            $('#toTop').css('display', 'none')
            self.$fixedShade.css({ 'width': '100%', 'height': $(document).height() })
            self.$pageWrap.on('touchmove', prevent)
            e.preventDefault()
        })

        this.$emitComment.click(this.addComment.bind(this))

        return this
    }

    setShareBtn() {
        var self = this,
            $shareWrap = $('#fixedShareWrap')
        $('.to-share').click(function (e) {
            $shareWrap.addClass('show')
            self.$fixedShade.addClass('active')
            self.$fixedShade[0].$curEle = $shareWrap

            e.preventDefault()
        })

        $('.cancle-share').click(() => {
            this.$fixedShade.click()
        })

        return this
    }
    //新增评论
    addComment() {
        var key = this.totalJson.content_key,
            content = this.$writeComment.val(),
            parentId = this.$emitComment.data('cid') || 0

        var self = this

        if ($.trim(content) != '') {
            var level = this.$currentCmtBtn.data('cid') ? 2 : 1//一级或者2级评论
            if (level == 2) {
                var $parentCmtWrap = this.$currentCmtBtn.closest('.comment-list__item').children('.comment-wrap')

                content = `${content}//${$parentCmtWrap.find('.user-name').text()}:${$parentCmtWrap.find('.comment-content').text()}`
            }

            this.ReqComment.addComment(comment3Uniqid, key, content, parentId).done((data) => {
                if (data.rs) {

                    var currentCmtWrap = level == 2 ? $(self.$currentCmtBtn).closest('.one-level-comment').find('.other-comment') : $('#commentList')

                    var tmp = level == 2 ? twoLevelCmtTmp : oneLevelCmtTmp

                    var $addComent = $(tmp({
                        cmt: data,
                        userInfo: self.userInfo
                    }))

                    currentCmtWrap.prepend($addComent)
                    $('.no-comment').remove()
                    //评论数+1
                    $('.comment-num').each((i, item) => {
                        $(item).text(1 * $(item).text() + 1)
                    })
                    //让新增评论回滚到屏幕中间
                    $('html,body').animate({
                        scrollTop: `${$addComent.offset().top - $(window).height() / 2}px`
                    }, 1000)
                } else {
                    lib.showTip(data.msg)
                }
            })
        } else {
            // lib.showTip('评论不能为空')
        }

        this.$fixedShade.click()
    }

    //设置分享链接
    setShareLink() {
        let _img = $('img').eq(0)[0].src || ''
        let _title = document.title
        let _href = location.href
        let _desc = $.trim($('.article-text').text()).split('。')[0]
        $('.share__item[data-share]').each((index, item) => {
            let $this = $(item),
                share = $this.attr('data-share'),
                href = ''
            switch (share) {
                // case 'wx': break
                case 'sina': href = `http://service.weibo.com/share/mobile.php?appkey=1343713053&url=${_href}&title=多玩新闻：「${_desc}」&pic=${_img}&searchPic=false`
                    break
                case 'qq': href = `https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=${_href}&title=${_title}&pics=${_img}&thumbnail=90*90&desc=${_desc}`
                    break
            }
            $this.attr('href', encodeURI(href))
        })
        return this
    }
    //加载更多回复
    loadMoreReplies() {
        var self = this
        this.$comment.on('click', '.show-more-comments', function (e) {

            var $this = $(this),
                param = $this.data('morereply').split('|'),
                $cmtWrap = $this.parent().children('.other-comment')

            if ($this.hasClass('loaded')) {
                if ($this.text() == '收起回复') {
                    $($cmtWrap[0].$addEle).slideUp()
                    $this.text('查看更多')
                } else {
                    $($cmtWrap[0].$addEle).slideDown()
                    $this.text('收起回复')
                }

            } else {
                self.ReqComment.moreReplies(comment3Uniqid, param[0], param[1], param[2]).done((data) => {
                    var $addEle = $(loadMoreRepliesTmp({
                        moreReplies: data
                    }))

                    $cmtWrap[0].$addEle = $addEle//缓存
                    $cmtWrap.append($addEle)

                    $this.addClass('loaded')

                    $this.text('收起回复')
                })
            }

            e.preventDefault()
        })

        return this
    }

    //加载更多推荐
    loadMoreRec() {
        var $hot = $('.rec-hot'),
            $recList = $hot.find('.news-list__item'),
            $more = $hot.find('.common-look-more')

        $recList.each((index, ele) => {
            if (index < 15)
                $(ele).css('display', 'block')
        })

        if ($more.length) {
            $more.click(() => {
                $recList.each((index, ele) => {
                    if (index >= 15)
                        $(ele).css('display', 'block')
                })

                $more.remove()
                $(window).scroll()
            })
        }

        return this
    }
    //懒加载
    lazyload() {
        $(window).scroll(function () {
            var $imgs = $('img[data-src]:visible'),
                $win = $(this),
                offsetBottom = $win.scrollTop() + $win.height()//底部的offsetY
            if ($imgs.length == 0) {
                return
            }
            $imgs.each((index, item) => {
                var $item = $(item)
                if (offsetBottom >= $item.offset().top - 100)
                    $item.attr('src', $item.attr('data-src')).removeAttr('data-src')
            })
        })

        $(window).scroll()

        return this
    }

    //输入框高度自适应
    setInputFit() {
        var _height = this.$writeComment.height(),
            _maxHeight = parseInt(this.$writeComment.css('lineHeight').slice(0, -2)) * 5
        this.$writeComment.on('input', function () {
            var _scrollHeight = this.scrollHeight
            if (_scrollHeight > _maxHeight) {
                $(this).css('height', _height).css('height', `${_maxHeight}px`)
            } else {
                $(this).css('height', _height).css('height', `${_scrollHeight}px`)
            }

        })

        return this
    }
    /**滑动事件 下滑显示评论条，上滑隐藏评论条 */
    setMoveEvent() {
        var $page = $('body'),
            lastY,
            lastScrollTop
        var $fixed = $(`<p style="position:fixed;right:0;top:0;width:100px;background-color:#fff;color:#000;"></p>`)
        $fixed.appendTo($('body'))

        document.addEventListener('touchstart', (e) => {
            lastY = e.touches[0].clientY
        })
        document.addEventListener('touchmove', (e) => {
            var clientY = e.touches[0].clientY
            if (clientY < lastY && !this.$commentBar.hasClass('hide')) {//上滑
                this.$commentBar.addClass('hide')
            } else if (clientY > lastY && this.$commentBar.hasClass('hide')) {
                this.$commentBar.removeClass('hide')
            }
            lastY = clientY
        })
        return this
    }
}

$(function () {
    //初始化加载loading图片
    var loadingImg = new Image();
    loadingImg.src = 'http://lol.duowan.com/s/webgifloading20170810.gif' ;

    new DwArticle
    //加载图片

    $('[data-echo]').each(function (index, item) {
        //判断gif图
        if (/gif$/.test($(item).attr('data-echo'))) {
            $(item).addClass('gif-img');
            //给gif默认显示图片
            $(item).attr('src','http://lol.duowan.com/s/webgif20170809.jpg')
        }else{
            $(item).attr('src', $(item).attr('data-echo'))
        }
        
    })

    //点击加载gif图
    $('#page_wrap').on('click','.gif-img',function(){ 
        $(this).addClass('g-img-loading')   //此样式类中有important
        $(this).attr('src', loadingImg.src)
        $(this).attr('src', $(this).attr('data-echo'))
        $(this).load(function(){
            $(this).removeClass('g-img-loading')
        })
    })
})