<template>
<div>
  <div class="con-title">问题详情</div>
  <div class="con-box">
    <div class='discuss-detail-scroll'>
      <div class='ques'>
        <div class='title'>{{discussQues.title}}</div>
        <div class='text' v-html="discussQues.text"></div>
        <div class='user'>
          <div class='name'>{{discussQues.user.name}}</div>
          <div class='time'>{{discussQues.user.time}}</div>
          <template v-if='discussQues.mine'><div class='right-txt' @click='deleteDiscuss'>删除</div></template>
          <div class='right-txt' @click='callbackComment' :data-sid='discussQues.sid' :data-qid='discussQues.qid' :data-quesid='discussQues.qid'>回复</div>
          <div class='right-txt' @click='openOrcloseDis' data-key='disQus'>讨论({{discussQues.comCnt}})</div>
          <div class='right-txt' @click='btnlike' :data-quesid='discussQues.qid' :data-sid='discussQues.sid' :data-tagid='discussQues.tag_id'>
            <!-- <image class='img' src='{{discussQues.has_tag ? "./icons/like-on.png" : "./icons/like.png"}}'></image> -->
            点赞({{discussQues.likeCnt}})</div>
        </div>
        <template v-if='disQus.isShowComment'>
          <div class='ask'>
            <template v-for='(item, index) in discussQues.comments'>
              <div v-bind:key="index" class='item-list' :data-id='item.id'>
                <div class='user'>
                  <div class='name'>{{item.user.name}}</div>
                  <div class='time'>{{item.user.time}}</div>
                  <template v-if='item.mine'><div class='right-txt' @click='deleteComment' :data-cid='item.cid'>删除</div></template>
                  <div class='right-txt' @click='callbackComment' :data-sid='discussQues.sid' :data-qid='discussQues.qid' :data-quesid='discussQues.qid' :data-to='item.user.name'>回复</div>
                </div>
                <div class='text'>{{item.text}}</div>
              </div>
            </template>
          </div>
        </template>
      </div>
      <div class='result'>{{discussQues.askCnt}} 回答<div style='display: inline-block; width: 0.2rem;'></div>{{discussQues.TouCnt}} 投票</div>
      <template v-for='(item, index) in answersList'>
        <div v-bind:key="index" class='ask'>
          <div class='user-1'>
            <template v-if="item.user.url">
              <img class='img-1' :src='item.user.url' />
            </template>
            <template v-else>
              <img class='img-1' src='../../assets/images/person-default.jpg' />
            </template>
            <div class='right-1'>
              <div class='name-1'>{{item.user.name}}</div>
              <div class='time-1'>{{item.user.time}}</div>
            </div>
          </div>
          <div class='text' v-html="item.text"></div>
          <div class='user'>
            <template v-if='item.mine'><div class='right-txt' @click='deleteAnswer' :data-aid='item.aid'>删除</div></template>
            <div class='right-txt' @click='callbackComment' :data-sid='discussQues.sid' :data-qid='discussQues.qid' :data-ansid='item.aid'>回复</div>
            <div class='right-txt' @click='openOrcloseDis' :data-key='answers' :data-index='index'>讨论({{item.comCnt}})</div>
            <div class='right-txt' @click='btnlike' :data-sid='discussQues.sid' :data-quesid='discussQues.qid' :data-ansid='item.aid' :data-tagid='item.tag_id'>
              <!-- <image class='img' src='{{item.has_tag ? "./icons/like-on.png" : "./icons/like.png"}}'></image> -->
              点赞({{item.likeCnt}})</div>
          </div>
          <template v-if='answers[index].isShowComment'>
            <template v-for='(item1, index) in item.comments'>
              <div v-bind:key='index' class='item-list' :data-id='item1.id'>
                <div class='user'>
                  <div class='name'>{{item1.user.name}}</div>
                  <div class='time'>{{item1.user.time}}</div>
                  <template v-if='item1.mine'><div class='right-txt' @click='deleteComment' :data-cid='item1.cid'>删除</div></template>
                  <div class='right-txt' @click='callbackComment' :data-sid='discussQues.sid' :data-qid='discussQues.qid' :data-ansid='item.aid' :data-to='item.user.name'>回复</div>
                </div>
                <div class='text' v-html="item1.text"></div>
              </div>
            </template>
          </template>
          <template v-if='(!item.comments.length || !answers[index].isShowComment)'><div style='width: 100%; height: 0.2rem;'></div></template>
        </div>
      </template>
      <template v-if='!answersList.length'>
        <div class='no-data'>暂无回答</div>
      </template>
      <div style='width: 750rpx; height: 200rpx;'></div>
    </div>
  </div>
  <div style="width: 100%; height: 1.7rem;"></div>
  <div class='input-publish'>
    <textarea id="editor"></textarea>
    <!-- <div class='ask'> -->
      <!-- <image class='img' src='./icons/ask.png' mode='aspectFill'></image> -->
      <!-- <input type='text' class="txt" placeholder='{{inputStatus.placeholder}}' focus='{{inputStatus.canFocus}}' bindblur='blurInput' confirm-type='send' bindconfirm='publishContent' value='{{inputStatus.input}}' cursor-spacing='20'/> -->
    <!-- </div> -->
    <el-button type="primary" @click="publishContent">发送</el-button><em class="send">({{inputStatus.placeholder}})</em>
  </div>
</div>
</template>

<script>
import cAction from '@action'

import CKEDITOR from 'CKEDITOR'

export default {
  props: {
    sid: { type: String, require: false },
    cid: { type: String, require: false },
    id: { type: String, require: false } // 章节id
  },
  data () {
    return {
      ckeditor: null,
      courseTitle: '课程问题',
      discussQues: {
        qid: '', user: { url: './icons/default.jpg', name: '用户名000', time: '2018-2-12 15:28:47' }, // eslint-disable-line
        title: '这是一个一句话问题这是一个一句话问题这是一个一句话问题标题这是一个一句话问题', // eslint-disable-line
        text: '<p>王家有三兄弟甲、乙、丙，丙幼年时送给胡某作养子，丙结婚时，胡某为其盖了新房，后因失火致使该房屋被烧毁。丙的生父母就将自己<p>', // eslint-disable-line
        askCnt: 20, TouCnt: 100, likeCnt: 100, comCnt: 100, mine: true, isShowComment: false, has_tag: false, tag_id: null, // eslint-disable-line
        comments: [ // eslint-disable-line
          { cid: '', user: { url: '', name: '用户名000', time: '2018-2-12 15:28:47' }, text: '在线学习课程', mine: true }, // eslint-disable-line
          { cid: '', user: { url: '', name: '用户名000', time: '2018-2-12 15:28:47' }, text: '在线学习课程', mine: false } // eslint-disable-line
        ] // eslint-disable-line
      },
      answersList: [
        // {
        //   aid: '', user: { url: '', name: '用户名000', time: '2018-2-12 15:28:47' }, // eslint-disable-line
        //   text: '<p>王家有三兄弟甲、乙、丙，丙幼年时送给胡某作养子，丙结婚时，胡某为其盖了新房，后因失火致使该房屋被烧毁。丙的生父母就将自己<p>', // eslint-disable-line
        //   likeCnt: 100, comCnt: 100, mine: true, isShowComment: false, has_tag: false, tag_id: null, // eslint-disable-line
        //   comments: [ // eslint-disable-line
        //     { cid: '', user: { url: '', name: '用户名000', time: '2018-2-12 15:28:47' }, text: '在线学习课程', mine: true } // eslint-disable-line
        //   ] // eslint-disable-line
        // }
      ],
      /* 存储状态值 的对象, 记录上次用户操作 */
      disQus: {
        isShowComment: false
      },
      answers: [ // 数组 跟 上面 answerList数组对应, 存储某些状态值，目前存储讨论打开关闭状态
        { aid: '', isShowComment: false } // eslint-disable-line
      ],
      inputStatus: {
        canFocus: false,
        placeholder: '回答问题 ...',
        input: ''
      },
      qid: '6447416971762860032',
      /* 回复内容状态 */
      call: {}
    }
  },
  mounted () {
    this.call = { questionId: this.id, semester_id: '', contents: '', question_id: this.id, answer: true }
    const loading = this.$loading({ lock: true, text: '', spinner: '', background: 'rgba(255, 255, 255, 0.9)' })
    cAction.Discuss.getDiscussDetail(this.id).then(json => {
      this.discussQues = json.ques
      this.call.semester_id = this.discussQues.sid
      this.disQus.isShowComment = json.ques.isShowComment
      const answers = []
      for (let i = 0; i < json.answer.length; i++) {
        answers.push({
          aid: json.answer[i].aid,
          isShowComment: json.answer[i].isShowComment
        })
      }
      this.answersList = json.answer
      this.answers = answers
    }).catch(e => { this.$message.error(e.message) }).finally(() => { loading.close() })
    // this.initckeditor()
    $('#editor').on('blur', () => {
      this.blurInput()
    })
  },
  destroyed () {
    /* 清空 ckeditor 需要调用方法删除 并 在DOM结构中也移除 */
    this.ckeditor && this.ckeditor.destroy(true)
    this.ckeditor = null
    $('#editor').off('blur')
  },
  methods: {
    /**
     * 打开或关闭 讨论
     */
    openOrcloseDis (e) {
      const key = e.currentTarget.dataset.key
      if (key === 'disQus') {
        this.disQus.isShowComment = !this.disQus.isShowComment
      } else {
        const index = e.currentTarget.dataset.index
        this.answers[index].isShowComment = !this.answers[index].isShowComment
      }
    },
    /**
     * 删除评论
     */
    deleteComment (e) {
      const cid = e.currentTarget.dataset.cid
      const loading = this.$loading({ lock: true, text: '', spinner: '', background: 'rgba(255, 255, 255, 0.9)' })
      cAction.Discuss.deleteComment(cid).then(json => {
        this.updateList()
        this.$message({ type: 'success', message: '删除成功' })
      }).catch(e => { this.$message.error(e.message) }).finally(() => { loading.close() })
    },
    /**
     * 删除回答
     */
    deleteAnswer (e) {
      const aid = e.currentTarget.dataset.aid
      const loading = this.$loading({ lock: true, text: '', spinner: '', background: 'rgba(255, 255, 255, 0.9)' })
      cAction.Discuss.deleteAnswer(aid).then(json => {
        this.updateList()
        this.$message({ type: 'success', message: '删除成功' })
      }).catch(e => { this.$message.error(e.message) }).finally(() => { loading.close() })
    },
    /**
     * 点赞 或 取消点赞 操作
     */
    btnlike (e) {
      const _data = e.currentTarget.dataset
      const quesid = _data.quesid
      const ansid = _data.ansid
      const tagid = _data.tagid
      const sid = _data.sid
      if (tagid) { // 取消 点赞操作
        // wx.showLoading({ title: '操作中...', mask: true })
        const loading = this.$loading({ lock: true, text: '', spinner: '', background: 'rgba(255, 255, 255, 0.9)' })
        cAction.Discuss.unlike(tagid).then(json => {
          this.updateList()
        }).catch(e => { this.$message.error(e.message) }).finally(() => { loading.close() })
      } else { // 点赞操作
        const param = {}
        if (quesid) { param.question_id = quesid }
        if (ansid) { param.answer_id = ansid }
        if (sid) { param.semester_id = sid }
        // wx.showLoading({ title: '操作中...', mask: true })
        const loading = this.$loading({ lock: true, text: '', spinner: '', background: 'rgba(255, 255, 255, 0.9)' })
        cAction.Discuss.like(param).then(json => {
          this.updateList()
        }).catch(e => { this.$message.error(e.message) }).finally(() => { loading.close() })
      }
    },
    /**
     * 删除问题
     */
    deleteDiscuss () {
      const loading = this.$loading({ lock: true, text: '', spinner: '', background: 'rgba(255, 255, 255, 0.9)' })
      cAction.Discuss.deleteDiscuss(this.id).then(json => {
        this.$message({ type: 'success', message: '删除成功' })
        /* 返回上一级 菜单 */
        setTimeout(() => {
          // wx.navigateBack({ delta: 1 })
          this.$router.go(-1)
        }, 1000)
      }).catch(e => { this.$message.error(e.message) }).finally(() => { loading.close() })
    },
    /**
     * 点击回复 调起输入框
     */
    callbackComment (e) {
      // /* 如果，输入框中，本身已经存在输入内容，那么再点击其他回复时，不给提示，直接清空 */
      this.inputStatus.input = '' // 这里如果想判断，不能使用 inputStatus.input这个 在blur时存储

      const _data = e.currentTarget.dataset
      const qid = _data.qid
      const quesid = _data.quesid
      const ansid = _data.ansid
      const to = _data.to
      const sid = _data.sid
      const json = {}
      if (qid) { json.questionId = qid }
      if (to) { json.to = to }
      if (quesid) { json.question_id = quesid }
      if (ansid) { json.answer_id = ansid }
      if (sid) { json.semester_id = sid }
      this.call = json
      if (to) {
        this.inputStatus.placeholder = '回复' + to + '：'
      } else {
        this.inputStatus.placeholder = '回复：'
      }
      this.inputStatus.canFocus = true
      $('#editor').focus()
    },
    /**
     * 取消 聚焦状态, 使用 ckeditor 进行 聚焦监听
     */
    blurInput (e) {
      this.inputStatus.canFocus = false
      if ($('#editor').val()) {
        // 输入框中存在内容则不做处理 - 这里不能做任何处理，否则会产生 输入框中内容遗留问题
      } else {
        this.inputStatus.placeholder = '回答问题 ...'
        this.inputStatus.input = ''
        // 回答问题 方式
        this.call = {
          questionId: this.discussQues.qid,
          semester_id: this.discussQues.sid,
          contents: '',
          question_id: this.discussQues.qid,
          answer: true
        }
      }
    },
    /**
     * 点击 键盘发送按钮时
     */
    publishContent (e) {
      const val = $('#editor').val()
      if (this.call.to) {
        this.call.comments = '回复' + this.call.to + '：' + val
      } else {
        this.call.comments = val
      }
      if (this.call.answer) { // 回答问题
        // wx.showLoading({ title: '操作中...', mask: true })
        this.call.contents = this.call.comments
        const loading = this.$loading({ lock: true, text: '', spinner: '', background: 'rgba(255, 255, 255, 0.9)' })
        cAction.Discuss.answerQues(this.call).then(json => {
          this.updateList()
          // this.ckeditor.setData('')
          $('#editor').val('')
        }).catch(e => { this.$message.error(e.message) }).finally(() => { loading.close() })
      } else { // 回复评论
        // wx.showLoading({ title: '操作中...', mask: true })
        const loading = this.$loading({ lock: true, text: '', spinner: '', background: 'rgba(255, 255, 255, 0.9)' })
        cAction.Discuss.callbackComment(this.call).then(json => {
          this.updateList()
          // this.ckeditor.setData('')
          $('#editor').val('')
        }).catch(e => { this.$message.error(e.message) }).finally(() => { loading.close() })
      }
      // this.blurInput()
    },
    /* 刷新页面 全部状态 - 目前没有分页可以这么操作，如果存在分页，可能要重写 */
    updateList () {
      const loading = this.$loading({ lock: true, text: '', spinner: '', background: 'rgba(255, 255, 255, 0.9)' })
      cAction.Discuss.getDiscussDetail(this.id).then(json => {
        this.discussQues = json.ques
        const _answers = this.answers
        for (let i = 0; i < _answers.length; i++) {
          for (let j = 0; j < json.answer.length; j++) {
            if (_answers[i].aid === json.answer[j].aid) {
              json.answer[j].isShowComment = _answers[i].isShowComment
              break
            }
          }
        }
        const answers = []
        for (let i = 0; i < json.answer.length; i++) {
          answers.push({
            aid: json.answer[i].aid,
            isShowComment: json.answer[i].isShowComment
          })
        }
        this.answersList = json.answer
        this.answers = answers
      }).catch(e => { this.$message.error(e.message) }).finally(() => { loading.close() })
    },
    /* 初始化 ckeditor */
    initckeditor () {
      !this.ckeditor && (this.ckeditor = CKEDITOR.replace('editor', {
        height: 100,
        uiColor: '#eeeeee',
        filebrowserImageUploadUrl: '/api/ckeditor/img/upload',
        // resize_enabled: typeof this.props.resizable === 'boolean' ? this.props.resizable : true,
        toolbar: [
          // { name: 'document', items: [ 'Source', '-', 'Save', 'NewPage', 'Preview' ] },
          { name: 'styles', items: "[ 'Styles', 'Format', 'Font', 'FontSize' ]" },
          { name: 'colors', items: "[ 'TextColor', 'BGColor' ]" },
          { name: 'tools', items: "[ 'Maximize', 'ShowBlocks' ]" },
          // { name: 'clipboard', items: [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ] },
          { name: 'editing', items: "[ 'Find', 'Replace' ]" },
          // { name: 'forms', items: [ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField' ] },
          '/',
          { name: 'basicstyles', items: "[ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ]" },
          { name: 'paragraph', items: "[ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl' ]" },
          { name: 'links', items: "[ 'Link', 'Unlink', 'Anchor' ]" },
          { name: 'insert', items: "[ 'Image', 'Table', 'HorizontalRule' ]" }
        ]
      }))
    }
  }
}
</script>

<style lang="scss" scoped>
// .discuss-detail-scroll { }
.discuss-detail-scroll .ques { padding: 0.3rem 0.26rem; padding-top: 0; margin-bottom: 0.2rem; background: #fff; box-shadow: 0 2px 4px rgba(10, 4, 6, 0.1); overflow: hidden; }
/* 显示标题、描述、讨论、人等 */
.discuss-detail-scroll .user { margin-top: 0.15rem; overflow: hidden; }
.discuss-detail-scroll .user .name { float: left; font-size: 0.16rem; color: #313131; line-height: 0.2rem; }
.discuss-detail-scroll .user .time { float: left; margin-left: 0.4rem; font-size: 0.14rem; color: #a0a0a0; line-height: 0.2rem; }
.discuss-detail-scroll .user .right-txt { float: right; margin-left: 0.2rem; font-size: 0.14rem; color: #a27c1b; cursor: pointer; }
.discuss-detail-scroll .user .right-txt .img { display: inline-block; margin-top: 1px; width: 0.22rem; height: 0.2rem; }
.discuss-detail-scroll .title { margin: 0.15rem 0; font-size: 0.24rem; color: #313131; line-height: 1.5; text-align: justify; }
.discuss-detail-scroll .text { font-size: 0.18rem; color: #535353; line-height: 1.5; text-align: justify; }
/* 显示回答和投票 */
.discuss-detail-scroll .result { margin-left: 0.26rem; margin-top: 0.15rem; font-size: 0.14rem; color: #313131; }

.discuss-detail-scroll .ask { position: relative; margin-top: 0.2rem; padding: 0 0.26rem; background: #fff; overflow: hidden; }
/* 显示回答 和 讨论 */
.discuss-detail-scroll .ask .user-1 { position: relative; overflow: hidden; margin-top: 0.25rem; margin-bottom: 0.15rem; }
.discuss-detail-scroll .ask .user-1 .img-1 { float: left; width: 0.6rem; height: 0.6rem; border-radius: 50%; }
.discuss-detail-scroll .ask .user-1 .right-1 { position: absolute; left: 0.72rem; top: 50%; -webkit-transform: translateY(-50%); transform: translateY(-50%); }
.discuss-detail-scroll .ask .user-1 .right-1 .name-1 { font-size: 0.14rem; color: #313131; text-overflow: ellipsis; overflow: hidden; word-break:break-all; }
.discuss-detail-scroll .ask .user-1 .right-1 .time-1 { margin-top: 5px; font-size: 0.14rem; color: #a0a0a0; }
.discuss-detail-scroll .item-list { position: relative; padding: 0.3rem 0; border-bottom: 1px solid #c9c9c9; }
.discuss-detail-scroll .item-list:last-child { border-bottom: none; }
.discuss-detail-scroll .item-list .user { margin-top: 0; overflow: hidden; }
.discuss-detail-scroll .item-list .user .name { float: left; font-size: 0.16rem; color: #313131; line-height: 0.2rem; }
.discuss-detail-scroll .item-list .user .time { float: left; margin-left: 0.4rem; font-size: 0.14rem; color: #a0a0a0; line-height: 0.2rem; }
.discuss-detail-scroll .item-list .user .right-txt { float: right; margin-left: 0.2rem; font-size: 0.14rem; color: #a27c1b;  }
.discuss-detail-scroll .item-list .text { margin-top: 0.15rem; font-size: 0.16rem; color: #535353; }
.discuss-detail-scroll .item-list .text.on { color: #2263d9; }
.discuss-detail-scroll .no-data { padding: 1rem 0; font-size: 0.24rem; color: #c9c9c9; text-align: center; }
.input-publish { position: fixed; z-index: 2; height: 1.5rem; left: 200px; right: 15px; bottom: 0; padding: 0.2rem; background: #fff; box-sizing: border-box; }
.input-publish #editor { width: 100%; height: 0.7rem; font-size: 18px; line-height: 1.5; outline: none; }
.input-publish .send { font-size: 14px; color: #ddd; margin-left: 10px; }
.input-publish .ask { position: relative; margin: 12px auto; width: 90%; height: 56px; border: 1px solid #dcdcdc; box-sizing: border-box; -webkit-box-sizing: border-box; }
.input-publish .ask .img { position: absolute; left: 24px; top: 13px; width: 28px; height: 0.26rem; }
.input-publish .ask .txt { position: absolute; left: 63px; top: 0; height: 54px; width: 100%; border: none; line-height: 2; font-size: 0.18rem; color: #313131; }
</style>
