var RequestComment = require("request/comment")
var Util = require("util")
var _ = require("underscore")
// var comment3Uniqid = "953879c6628884deaa1bc1b0273920d0"
var comment3Uniqid = Util.getParam('uniqid')
var commentListTmp = __inline('./commentList.tmpl')
var oneLevelCmtTmp = __inline('./oneLevelComment.tmpl')
var twoLevelCmtTmp = __inline('./twoLevelComment.tmpl')
var loadMoreRepliesTmp = __inline('./loadMoreReplies.tmpl')
var cmtUserTmp = __inline('./commentUser.tmpl')

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

class DwComment {
    constructor() {
        this.ReqComment = new RequestComment({
            domain: Util.getParam('domain').replace('cn', 'com'),
            url: Util.getParam('url')
            // domain: 'www.duowan.com',
            // url: '/news/356614433634.html'
        })
        this.$pageWrap = $('#page_wrap')//最外层容器
        this.userInfo = {}
        this.totalJson
        this.$comment = $('.common-comment')
        this.$typeNav = this.$comment.children('.comment-type-nav')
        this.$cmtListWrap = this.$comment.find('.comment-list-wrap')
        this.navIndex = 0
        this.$currentCmtWrap = this.$cmtListWrap.eq(0)
        //新增评论
        this.$artWriteComment = $('#artCommentArea')
        this.$artEmitComment = $('#articleEmitCmt')

        //回复评论
        this.$fixedCommentArea = $('.fixed-comment-area')
        this.$writeComment = this.$fixedCommentArea.children('.comment-textarea')
        this.$emitComment = this.$fixedCommentArea.children('.emit-comment')

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

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

        this.init()

        $('.article-title').text(Util.getParam('title'))
    }
    init() {

        var req = this.ReqComment
        var self = this
        this.setTypeTab()
            .setTitleHref()
            .setReplyBtn()
            .setAgreeBtn()
            .setInputFit()
            .setLoginRegister()
            .setGoBack()
            .getUserinfo()
            .loadMoreReplies()

        $.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]
                    }
                })
                self.renderCmtList(this.navIndex, cmtList)
            }
        })

        this.$comment.on('click', '.common-look-more', function (e) {
            self.loadMoreCmt($(this))
            e.preventDefault()
        })

        this.$fixedShade.on('click', () => {
            this.$fixedShade.removeClass('active')
            this.$fixedCommentArea.removeClass('show')
            this.$writeComment.val('')

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

        this.$fixedShade.on('touchmove', prevent)
    }
    getUserinfo() {
        var $userWrap = $('.toolbar-menu-wrap')

        if (Util.isLoggedIn()) {

            this.ReqComment.getLoginInfo().done((data) => {
                this.userInfo = data && data.login_info

                $userWrap.prepend(cmtUserTmp({
                    userInfo: data.login_info
                }))

                $('.to-login').remove()
                $('.to-register').remove()
            })
        } else {
            $userWrap.prepend(cmtUserTmp())
        }
        return this
    }
    //渲染评论列表
    renderCmtList(index, cmtList, type) {
        if (type == 'add') {
            var $inner = $(commentListTmp({
                cmtList: cmtList,
                isCommentPge: true
            })).eq(0).children()
            this.$cmtListWrap.eq(index).children('.comment-list').append($inner)
        } else {
            this.$cmtListWrap.eq(index).html(commentListTmp({
                cmtList: cmtList,
                isCommentPge: true
            }))
        }

    }
    //根据所选类型加载评论
    getListByType(index) {
        var type = index == 0 ? 'hot' : 'time'
        this.ReqComment.comments(comment3Uniqid, type)
            .done((cmtList) => {
                cmtList.forEach((item, index) => {
                    if (parseInt(item.comment_reply_total) > 3) {
                        var len = item.reply.length

                        item.lastR = item.reply[len - 1]
                    }
                })
                this.renderCmtList(index, cmtList)
            })
    }
    setTypeTab() {
        var self = this
        this.$typeNav.children('.comment-type').click(function () {
            if ($(this).hasClass('active')) return

            var index = self.navIndex = $(this).index()

            $(this).addClass('active').siblings().removeClass('active')

            self.$cmtListWrap.removeClass('active')
                .eq(index).addClass('active')

            self.$currentCmtWrap = self.$cmtListWrap.eq(index)

            self.getListByType(index)
        })

        return this
    }

    setAgreeBtn() {
        var self = this
        $('body').on('click', '.btn-agree', function () {
            var 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', function (e) {
            self.$fixedCommentArea.addClass('show')
            self.$fixedShade.addClass('active')
            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.replyComment.bind(this))
        this.$artEmitComment.click(this.addComment.bind(this))
        return this
    }
    //新增文章评论
    addComment() {
        var key = this.totalJson.content_key,
            content = this.$artWriteComment.val(),
            self = this

        if ($.trim(content) != '') {
            this.ReqComment.addComment(comment3Uniqid, key, content).done((data) => {
                if (data.rs) {
                    var $addComent = $(oneLevelCmtTmp({
                        cmt: data,
                        userInfo: self.userInfo
                    }))
                    this.$currentCmtWrap.children('.comment-list').prepend($addComent)
                    //让新增评论回滚到屏幕中间
                    $('html,body').animate({
                        scrollTop: `${$addComent.offset().top - $(window).height() / 2}px`
                    }, 1000)
                } else {
                    lib.showTip(data.msg)
                }
            })
        }

        this.$artWriteComment.val('')
    }
    //回复评论
    replyComment() {
        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 = $(self.$currentCmtBtn).closest('.one-level-comment').find('.other-comment')

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

                    currentCmtWrap.prepend($addComent)

                    //让新增评论回滚到屏幕中间
                    $('html,body').animate({
                        scrollTop: `${$addComent.offset().top - $(window).height() / 2}px`
                    }, 1000)
                } else {
                    lib.showTip(data.msg)
                }
            })
        } else {
            // lib.showTip('评论不能为空')
        }

        this.$fixedShade.click()
    }

    //输入框高度自适应
    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
    }
    //加载更多
    loadMoreCmt($ele) {
        var type = this.navIndex == 0 ? 'hot' : 'time'
        var num = $ele.attr('data-num')
        this.ReqComment.comments(comment3Uniqid, type, num * 1).done((data) => {
            this.renderCmtList(this.navIndex, data, 'add')
            if (data.length < 10) {
                $ele.remove()
            } else {
                $ele.attr('data-num', num * 1 + 10)
            }

        })
    }

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

    setLoginRegister() {
        var $wrap = $('.login-register'),
            $login = $wrap.children('.to-login')

        $login.attr('href', `http://www.duowan.com/mlogin/?calbackUrl=${encodeURIComponent(location.href)}`)

        return this
    }

    setGoBack() {
        $('.comment-back').click(() => {
            history.go(-1);
        })

        return this
    }

    setTitleHref() {
        $('.article-title').attr('href', `http://${Util.getParam('domain')}${Util.getParam('url')}`)
        return this
    }
}

$(function () {
    new DwComment()
})