<template>
  <div class="layout-no-cols right-list-toolbar right-list-panel-card">
    <el-toolbar align="right">
      <span v-if="!catalogId && isShow">
        <tree-select :value.sync="catalogID" placeholder="请选择栏目" @click-change="chooseContentType" clearable :items="catalogTrees">
        </tree-select>
      </span>
      <el-select clearable v-model="cType" placeholder="请选择内容类型" @change="chooseContentType" style="width:auto">
        <el-option v-for="cType in contentType" :key="cType.value" :label="cType.label" :value="cType.value">
        </el-option>
      </el-select>
      <el-select v-model="aStatus" placeholder="请选择评论审核状态" @change="chooseAuditStatus" style="width:auto">
        <el-option v-for="aStatus in auditStatus" :key="aStatus.codeValue" :label="aStatus.codeName" :value="aStatus.codeValue">
        </el-option>
      </el-select>
    </el-toolbar>
    <div class="board-message-list">
    <el-list-view @selection-change="onSelectionChange" :data="comments" :data-read-url="getData" :pageSize="10" ref="commentsListRef" selectable :multi-operates="multiOperates">
        <template slot-scope="row">
          <div class="panel-card">
            <div class="card-header">
              <el-row>
                <el-col :span="8" class="text-overflow-hidden">
                  <span><i class="fa fa-user"></i>{{row.addUser?row.addUser:'匿名网友'}}(IP：&nbsp;{{row.addUserIP}})</span>
                </el-col>
                <el-col :span="8" class="text-overflow-hidden">
                  <span><i class="fa fa-clock-o"></i>{{row.addTime | fixDateTime}}</span>
                </el-col>
                <el-col :span="8" class="text-overflow-hidden">
                  <span class="catalog">[ {{row.catalogName}} ] <em>关联ID：{{row.relaID}}</em></span>
                </el-col>
              </el-row>
            </div>
            <div class="card-content">
              <el-row class="gray f12">评论内容：</el-row>
              <el-row><span class="black"><span v-html="encodeContent(row.content)"></span></span></el-row>
              <el-row class="gray f12">回复内容：</el-row>
              <el-row v-if="!row.showReplyBox"><span class="black">{{row.adminReply}}</span></el-row>
              <el-row>
                <span v-if="row.showReplyBox">
                <el-input type="textarea" :autosize="{ minRows: 1, maxRows: 4}" v-model="row.adminReply"></el-input>
                <div class="reply-btn">
                  <el-button @click.stop="replyOkHandler(row)" type="primary" size="mini" round class="shadow-primary">回复</el-button>
                </div>
              </span>
              </el-row>
              <el-row>
                <el-col :span="5">
                  <span class="green" @click="seeOriginal(row.preLink)">查看原文</span>
                  <el-tag size="small" class="m-l-10" :type="row.verifyFlag==='Y'?'':'danger'">{{row.verifyFlagName}}</el-tag>
                </el-col>
                <el-dropdown @command="handleCommand" class="fr">
                  <el-button type="text">
                    <i class="fa fa-ellipsis-h f16" aria-hidden="true"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="{fun:'reply',param:row}" plain>
                      <i class="fa fa-commenting"></i> 回复</el-dropdown-item>
                    <el-dropdown-item :command="{fun:'pass',param:row}" plain>
                      <i class="fa fa-check-circle"></i> 通过</el-dropdown-item>
                    <el-dropdown-item :command="{fun:'reject',param:row}" plain>
                      <i class="fa fa-times-circle"></i> 不通过</el-dropdown-item>
                    <el-dropdown-item :command="{fun:'del',param:row}" plain>
                      <i class="fa fa-times"></i>删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>

                <!-- <el-col :span="19" class="tar">
                  <el-button v-if="item.replyFlag === 'N'" type="text" @click.stop="toggleReplyBox(item)" size="small"><i class="fa fa-commenting"></i>回复</el-button>
                  <el-button type="text" @click.stop="doCheck(item.ID,'Y')" size="small"><i class="fa fa-check-circle"></i>审核通过</el-button>
                  <el-button type="text" @click.stop="doCheck(item.ID,'N')" size="small"><i class="fa fa-minus-circle"></i>审核不通过</el-button>
                  <el-button type="text" @click.stop="deleteMessage(item.ID)" size="small"><i class="fa fa-remove"></i> 删除</el-button>
                </el-col> -->
              </el-row>
            </div>
          </div>
        </template>
      </el-list-view>
    </div>
  </div>
</template>

<script>
import util from '@src/common/util.js'
import TreeSelect from '@src/components/TreeSelect.vue'
export default {
  components: {
    'tree-select': TreeSelect
  },
  props: {
    catalogId: [String, Number]
  },
  filters: {
    fixDateTime(val) {
      return util.formatDate(val, 'yyyy-MM-dd HH:mm')
    }
  },
  data() {
    return {
      selectedRow: {},
      selectedRows: [],
      replyDialogShow: false,
      dataLoading: false,
      comments: [], // 评论列表，用来加载Comment.js中的数据
      contentType: [], // 栏目类型下拉菜单定义 lxc
      auditStatus: [], // 评论审核状态下拉菜单定义 lxc
      cType: '', // 栏目类型 lxc
      aStatus: 'All', // 评论审核状态 lxc
      codeType: 'CommentStatus', // 评论审核状态代码类别
      checked: false,
      catalogTrees: [],
      catalogID: '',
      multiOperates: [
        {
          label: '审核通过',
          value: 'pass',
          fn: rows => {
            this.checkComments(rows, 'Y')
          }
        },
        {
          label: '审核不通过',
          value: 'unpass',
          fn: rows => {
            this.checkComments(rows, 'N')
          }
        },
        {
          label: '删除',
          value: 'delete',
          fn: rows => {
            this.deleteComments(rows)
          }
        }
      ]
    }
  },

  watch: {
    // 如果栏目id 发生改变，这个函数就会运行
    catalogId() {
      this.catalogID = this.catalogId
      this.$refs.commentsListRef.getData()
    },
    comments() {
      this.comments.forEach(o => {
        Vue.set(o, 'showReplyBox', false)
      })
    }
  },
  computed: {
    isShow() {
      let isPlugin = this.$route.path.indexOf('/plugins') > -1
      return isPlugin || !!this.catalogId
    }
  },
  methods: {
    // 批量删除
    async deleteComments(rows) {
      this.$confirm(`确认删除选择的<span class='icon-danger'>${rows.length}条</span>评论吗 ？`, {
        title: '提示',
        dangerouslyUseHTMLString: true,
        type: 'warning'
      })
        .then(async r => {
          let IDs = _.map(rows, 'ID').join()
          let res = await axios.delete(`/ui/comments/${IDs}`)
          util.showResponseMessage(res.data)
          res.data.status === 1 && this.$refs.commentsListRef.getData()
        })
        .catch(err => { console.error(err) })
    },

    // 批量审核
    async checkComments(rows, status) {
      this.$confirm(`确认审核${status === 'Y' ? '通过' : '不通过'}选择的<span class='icon-danger'>${rows.length}条</span>评论吗 ？`, {
        title: '提示',
        dangerouslyUseHTMLString: true,
        type: 'warning'
      })
        .then(async r => {
          let IDs = _.map(rows, 'ID').join()
          let res = await axios.put(`/ui/comments/${IDs}`, { type: status })
          util.showResponseMessage(res.data)
          res.data.status === 1 && this.$refs.commentsListRef.getData()
        })
        .catch(err => { console.error(err) })
    },

    handleCommand(obj) {
      if (obj) {
        var fun = obj.fun
        var param = obj.param
        typeof this[fun] === 'function' && this[fun](param)
      } else {
        console.warn(`未找到改菜单对应的方法:${fun}`)
      }
    },

    // 查看原文
    seeOriginal(url) {
      window.open(url)
    },

    // 当勾选项改变
    onSelectionChange(selection) {
      this.selectedRows = selection
      this.selectedRow = selection[0]
    },

    // 回复
    reply(item) {
      item.showReplyBox = !item.showReplyBox
      item.editMode = !item.editMode
    },
    async replyOkHandler(item) {
      if (!item.adminReply) {
        util.showResponseMessage({message: '回复不能为空'})
        return
      }
      if (util.getLengthEx(item.adminReply, true) > 500) {
        util.showResponseMessage({message: '回复不能大于166个汉字或500字符'})
        return
      }
      let res = await axios.put(`/ui/comments/reply/${item.ID}`, { replyContent: item.adminReply })
      util.showResponseMessage(res.data)
      if (res.data.status === 1) {
        item.showReplyBox = !item.showReplyBox
      }
    },

    // 评论审核通过
    pass(item) {
      this.update('Y', item)
    },
    // 评论审核未通过
    reject(item) {
      this.update('N', item)
    },
    async update(verifyFlag, item) {
      let ids = await this.getIDs(item)
      let res = await axios.put(`/ui/comments/${ids}`, { type: verifyFlag })
      util.showResponseMessage(res.data)
      if (res) {
        if (res.data.status === 1) {
          // 先判断点击事件是来自工具条还是评论项
          if (item) {
            item.verifyFlag = verifyFlag
            item.verifyFlagName = verifyFlag === 'Y' ? '审核通过' : '审核未通过'
          } else {
            this.selectedRows.forEach(function(row) {
              row.verifyFlag = verifyFlag
              row.verifyFlagName = verifyFlag === 'Y' ? '审核通过' : '审核未通过'
            })
          }
        }
      }
    },

    getIDs(item) {
      //  先判断点击事件是来自工具条还是评论项获取相应的IDs
      if (item) {
        return item.ID
      } else {
        return this.selectedRows
          .map(row => {
            return row.ID
          })
          .join(',')
      }
    },

    // 评论删除
    async del(item) {
      let ids = await this.getIDs(item)
      try {
        await this.$confirm('确定删除吗，删除后无法恢复。是否继续删除？', '删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        return
      }
      let res = await axios.delete(`/ui/comments/${ids}`)
      util.showResponseMessage(res.data)
      if (res.data.status === 1) {
        this.$refs.commentsListRef.getData()
      }
    },

    getData() {
      return [
        '/ui/comments',
        {
          params: {
            catalogID: this.catalogID || this.catalogId,
            catalogType: this.cType,
            auditStatus: this.aStatus
          }
        }
      ]
    },

    // 栏目树数据加载
    async getCatalogsTree() {
      let res = await axios.get('/ui/catalog')
      this.catalogTrees = res.data.data
    },

    // 栏目类型数据加载lxc
    async getCatalogTypes() {
      let res = await axios.get('/ui/contentcore/contenttypes')
      this.contentType = res.data.data
    },

    // 评论审核状态数据加载lxc
    async getCommentAuditStatus() {
      let res = await axios.get(`/ui/codes/${this.codeType}/items`)
      this.auditStatus = res.data.data
    },

    // 栏目类型搜索事件lxc
    chooseContentType() {
      this.$refs.commentsListRef.getData()
    },

    // 评论审核状态搜索事件lxc
    chooseAuditStatus() {
      this.$refs.commentsListRef.getData()
    },
    encodeContent(val) {
      let cont = util.string.htmlEncode(val)
      if (cont.indexOf('_zving_h_') > 0) {
        cont = cont.split('_zving_h_').join('<span style="background-color:yellow;">').split('_zving_f_').join('</span>')
      }
      return cont
    }
  },
  created() {
    // 栏目树数据加载
    this.getCatalogsTree()

    // 栏目类型数据加载lxc
    this.getCatalogTypes()

    // 评论审核状态数据加载lxc
    this.getCommentAuditStatus()
  }
}
</script>

<style scoped>
.board-message-list .box-card .el-card__header {
  background: #f5f5f5;
}
.board-message-list .el-card {
  border: 1px solid #dfdfdf;
  background-color: #fff;
  box-shadow: 0 0 0 #fff;
  color: #2d2f33;
}
.board-message-list .el-card .el-button + .el-button {
  margin-left: 0px;
}
.board-message-list .catalog {
  font-weight: bold;
}
.board-message-list .catalog em {
  font-weight: normal;
}

.board-message-list {
  position: relative;
}

.board-message-list .box-card {
  font-size: 14px;
  margin-bottom: 10px;
}
.board-message-list .card-content p {
  margin-bottom: 20px;
  word-wrap: break-word;
}
.board-message-list .card-content .button_wrap {
  margin-bottom: 10px;
  float: right;
}
.board-message-list .card-content .content-title {
  font-size: 16px;
  color: gray;
  font-style: italic;
  margin-bottom: 10px;
}
.board-message-list .card-content .content-reply {
  display: -webkit-box;
  display: -moz-box;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 4;
}
.board-message-list .card-content .content-operate {
  text-align: right;
  position: absolute;
  right: 0px;
  bottom: 0px;
}
.m-l-10 {
  margin-left: 10px;
}
.p-l-0 {
  padding-left: 0px;
}
.green {
  color: #28b06e;
  cursor: pointer;
}

.board-name {
  margin: auto;
  font-weight: 600;
}

.panel-card {
  padding: 0px;
  margin: 10px auto 20px;
}

.panel-card .card-header {
  background-color: #f9f9f9;
  padding: 10px 15px;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
}

.card-content {
  padding: 10px 15px;
}

.split-line {
  border-top: 1px solid #eee;
  padding-bottom: 10px;
  margin-top: 10px;
}

.black {
  color: #484848;
}
.text-overflow-hidden {
  text-overflow: ellipsis;
  overflow: hidden;
  word-break: normal;
  white-space: nowrap;
}
.reply-btn {
  float: right;
  margin-top: 5px;
}
.el-toolbar-body > span, .el-toolbar-body > .el-button:last-child, .el-toolbar-body > .el-toolbar-btn:last-child {margin:0;}
.right-list-toolbar .el-select {margin-left: 5px;}
</style>
