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

// var comment3Uniqid = md5(location.host + location.pathname)
var articleCommentTpl = __inline('./articleComment.tmpl')
var articleCommentNumTpl = __inline('./articleCommentNum.tmpl')
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 _css_ = __inline('../../sass/articleComment.scss')

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

class DwArticleComment {
    constructor() {
        this.ReqComment = new RequestComment({
            domain: location.hostname.replace('cn', 'com'),
            url: location.pathname
            // domain: 'www.duowan.com',
            // url: '/news/357142680655.html'
        })

        this.userInfo = {} //用户信息
        this.totalJson
        this.$comment = $('.common-comment')
        this.$currentCmtBtn//保存当前的回复的按钮
        this.ts = '#uniq_article_title'

        var self = this
        this.renderComment(() => {
            this.$fixedCommentArea = $('.fixed-comment-area')
            this.$writeComment = this.$fixedCommentArea.children('.comment-textarea')
            this.$emitComment = this.$fixedCommentArea.children('.emit-comment')
            this.$fixedShade = $('.fixed-shade')

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

        this.setReplyBtn()
            .setAgreeBtn()
            .setInputFit()
            .loadMoreReplies()
            .getUserinfo()

        $.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('')

            $('body').off('touchmove', prevent)
        })

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

    //渲染评论组件
    renderComment(callback) {
        var css = $('<style>')
        css.html(_css_).appendTo(this.$comment)

        this.$comment.append($(articleCommentNumTpl())).append($(articleCommentTpl()))


        setTimeout(function () {
            callback && callback()
        }, 200);
        return this
    }
    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: `http://www.duowan.com/mComment/index.html?domain=www.duowan.com&url=${location.pathname}&uniqid=${comment3Uniqid}&title=${$(self.ts).eq(0).text()}`,
            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.$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() })
            $('body').on('touchmove', prevent)
            e.preventDefault()
        })

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

        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()
    }

    //加载更多回复
    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
    }

    //输入框高度自适应
    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
    }
}


$(function () {
    new DwArticleComment
})