<template>
  <div class="padding-top-bottom">
    <el-row>
      <el-col :span="10">
        <div size="medium">
          <span>留言板分类：</span>
          <el-select v-model="searchBoardID" @change="searchMessage">
            <el-option key="" label="全部" value=""></el-option>
            <el-option v-for="item in this.boardTypes" :key="item.ID" :label="item.name" :value="item.ID">
            </el-option>
          </el-select>
        </div>
      </el-col>
      <el-col :span="14">
        <div class="search-bar-algin-toolbar tar">
          <span>回复状态：</span>
          <el-select v-model="searchreplyFlagName" placeholder="回复状态" @change="searchMessage">
            <el-option v-for="item in this.replyFlagValue" :key="item.value" :label="item.name" :value="item.value">
            </el-option>
          </el-select>
          <span>审核状态：</span>
          <el-select v-model="searchverifyFlagName" placeholder="审核状态" @change="searchMessage">
            <el-option v-for="item in this.verifyFlagValue" :key="item.value" :label="item.name" :value="item.value">
            </el-option>
          </el-select>
        </div>
      </el-col>
    </el-row>
    <div class="board-message-list">
      <el-list-view ref="messageList" :data="messageList" :data-read-url="getMessageListURL" :pageSize="10" @selection-change="onSelectionChange" selectable :multi-operates="multiOperates">
        <template slot-scope="item">
          <div class="panel-card">
            <div class="card-header">
              <el-row>
                <el-col :span="6">
                  <span><i class="fa fa-user"></i>{{item.addUser}}{{item.addUser === '匿名网友' && item.ID ? ' ( IP ' + item.IP + ' )' : ''}}</span>
                </el-col>
                <el-col :span="6">
                  <span><i class="fa fa-clock-o"></i>{{item.addTime | fixDateTime}}</span>
                </el-col>
                <el-col :span="12">
                  <span>所属留言板：<em>{{item.boardName}}</em></span>
                </el-col>
              </el-row>
            </div>
          <div class="card-content">
            <el-row class="gray f12">留言内容：</el-row>
            <el-row><span class="black">{{item.content}}</span></el-row>
            <el-row>
              <el-col :span="5">
                <span class="green">热点留言：{{item.isRecommendedName}}</span>
                <el-tag size="small" class="m-l-10" v-show="item.ID">{{item.verifyFlagName}}</el-tag>
              </el-col>
              <el-col :span="19" class="tar">
                <el-button v-if="item.replyFlag === 'N'" type="text" @click.stop="toggleReplyBox(item)" size="small" :priv="'com.zving.cms.MessageBoard.Reply.'+ item.boardID">
                  <i class="fa fa-commenting"></i>回复</el-button>
                <el-button type="text" @click.stop="hotMark(item.boardID,item.ID,'Y')" size="small" :priv="'com.zving.cms.MessageBoard.Mark.'+ item.boardID">
                  <i class="fa fa-bookmark"></i>标记为热点</el-button>
                <el-button type="text" @click.stop="hotMark(item.boardID,item.ID,'N')" size="small" :priv="'com.zving.cms.MessageBoard.CancelMark.'+ item.boardID">
                  <i class="fa fa-minus-circle"></i>取消标记热点</el-button>
                <el-button type="text" @click.stop="doCheck(item.boardID,item.ID,'Y')" size="small" :priv="'com.zving.cms.MessageBoard.Check.'+ item.boardID">
                  <i class="fa fa-check-circle"></i>审核通过</el-button>
                <el-button type="text" @click.stop="doCheck(item.boardID,item.ID,'N')" size="small" :priv="'com.zving.cms.MessageBoard.Check.'+ item.boardID">
                  <i class="fa fa-exclamation-triangle text-danger"></i>审核不通过</el-button>
                <el-button type="text" @click.stop="deleteMessage(item.boardID,item.ID)" size="small" :priv="'com.zving.cms.MessageBoard.Delete.'+ item.boardID">
                  <i class="fa fa-remove"></i> 删除</el-button>
              </el-col>
            </el-row>

            <template v-if="(item.replyContent || item.showReplyBox) && item.ID">
              <div class="split-line"></div>
              <el-row class="green f12">回复内容：</el-row>
            </template>
            <el-row v-if="item.ID">
              <span v-if="!item.editMode" class="content-reply black">{{item.replyContent}}</span>
              <span v-if="item.editMode && item.showReplyBox">
                <el-input type="textarea" :autosize="{ minRows: 1, maxRows: 4}" v-model="item.replyContent"></el-input>
                <div class="reply-btn">
                  <el-button @click.stop="replyMessageHandler(item)" type="primary" size="mini" round class="shadow-primary">回复</el-button>
                </div>
              </span>
            </el-row>
            <el-row>
              <el-col :span="24" v-if="!item.editMode && item.ID">
                <el-button type="text" @click.stop="editReply(item)" size="small" class="p-l-0" :priv="'com.zving.cms.MessageBoard.Edit.'+item.boardID">
                  <i class="fa fa-edit"></i>编辑</el-button>
                <el-button type="text" size="small" @click.stop="deleteReply(item.boardID,item.ID)" :priv="'com.zving.cms.MessageBoard.Delete.'+item.boardID">
                    <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 Privilege from '@src/common/privilege.js'
export default {
  filters: {
    fixDateTime: function(val) {
      return util.formatDate(val, 'yyyy-MM-dd HH:mm')
    }
  },
  data() {
    return {
      searchBoardID: '',
      // 搜索回复状态留言名称
      searchreplyFlagName: '',
      // 搜搜审核状态留言名称
      searchverifyFlagName: '',
      // 验证状态名称
      verifyFlagValue: [
        {
          name: '全部',
          value: ''
        },
        {
          name: '审核通过',
          value: 'Y'
        },
        {
          name: '未审核',
          value: 'unaudited'
        },
        {
          name: '审核未通过',
          value: 'N'
        }
      ],
      // 回复状态名称
      replyFlagValue: [
        {
          name: '全部',
          value: ''
        },
        {
          name: '已回复',
          value: 'Y'
        },
        {
          name: '未回复',
          value: 'N'
        }
      ],
      // 留言板分类
      boardTypes: [],
      // 留言列表
      messageList: [],
      multiOperates: [
        {
          label: '审核通过',
          value: 'pass',
          fn: rows => {
            this.checkMessages(rows, 'Y')
          }
        },
        {
          label: '审核不通过',
          value: 'unpass',
          fn: rows => {
            this.checkMessages(rows, 'N')
          }
        },
        {
          label: '删除',
          value: 'delete',
          fn: rows => {
            this.deleteMessages(rows)
          }
        }
      ]
    }
  },

  watch: {
    messageList() {
      this.messageList.forEach(o => {
        if (o.replyFlag === 'N' && !o.replyContent && o.ID !== 0) {
          Vue.set(o, 'editMode', true)
        } else {
          Vue.set(o, 'editMode', false)
        }
        Vue.set(o, 'showReplyBox', false)
      })
    }
  },
  created() {
    this.loadBoardTypes()
  },
  methods: {
    // 批量审核
    async checkMessages(rows, status) {
      this.$confirm(`确认审核${status === 'Y' ? '通过' : '不通过'}选择的<span class='icon-danger'>${rows.length}条</span>留言吗 ？`, {
        title: '提示',
        dangerouslyUseHTMLString: true,
        type: 'warning'
      })
        .then(async r => {
          let data = {}
          rows.forEach(item => {
            if (Privilege.hasPriv(`com.zving.cms.MessageBoard.Check.${item.boardID}`)) {
              if (data[item.boardID] && Array.isArray(data[item.boardID])) {
                data[item.boardID].push(item.ID)
              } else {
                data[item.boardID] = [item.ID]
              }
            }
          })

          console.log('待审核的ID值:', data)

          let res = await axios.put(`/ui/messageboard/verify`, {
            data: data,
            verifyFlag: `${status}`
          })
          if (res.data.status === 1) {
            this.$refs.messageList.getData()
          }
          util.showResponseMessage(res.data)
        })
        .catch(err => { console.error(err) })
    },

    // 批量删除
    async deleteMessages(rows) {
      this.$confirm(`确认删除选择的<span class='icon-danger'>${rows.length}条</span>留言吗 ？`, {
        title: '提示',
        dangerouslyUseHTMLString: true,
        type: 'warning'
      })
        .then(async r => {
          let data = {}
          rows.forEach(item => {
            if (Privilege.hasPriv(`com.zving.cms.MessageBoard.Delete.${item.boardID}`)) {
              if (data[item.boardID] && Array.isArray(data[item.boardID])) {
                data[item.boardID].push(item.ID)
              } else {
                data[item.boardID] = [item.ID]
              }
            }
          })
          let res = await axios.delete(`/ui/messageboard/delmessages`, {
            params: {
              data: data
            }
          })
          if (res.data.status === 1) {
            this.$refs.messageList.getData()
          }
          util.showResponseMessage(res.data)
        })
        .catch(err => { console.error(err) })
    },

    async loadBoardTypes() {
      let res = await axios.get('/ui/messageboard/getmessageboardtypes')
      this.boardTypes = res.data.data
    },

    getMessageListURL() {
      return [
        '/ui/messageboard/messagedata',
        {
          params: {
            replyFlag: this.searchreplyFlagName,
            verifyFlag: this.searchverifyFlagName,
            boardID: this.searchBoardID
          }
        }
      ]
    },
    // 搜索留言
    searchMessage() {
      this.$refs.messageList.getData()
    },
    onSelectionChange(selection) {
      let ids = []
      selection.forEach(e => {
        ids.push(e.ID)
      })
      this.selectedIds = ids
    },

    // 编辑回复
    editReply(item) {
      item.editMode = true
      item.showReplyBox = true
    },

    // 删除回复
    async deleteReply(boardID, id) {
      try {
        await this.$confirm('确定删除回复吗，删除后无法恢复。是否继续删除？', '删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        return
      }
      let data = await axios.delete(`/ui/messageboard/${boardID}/delreply`, {
        params: { msgid: `${id}` }
      })
      if (data.data.status === 1) {
        this.$refs.messageList.getData()
      }
      util.showResponseMessage(data.data)
    },

    // 回复
    async replyMessageHandler(data) {
      if (data.replyContent.trim().length === 0) {
        util.showError('回复内容不能为空!')
        return
      }
      if (data.replyContent.length >= 2000) {
        util.showError('回复内容不能超过2000个字符!')
        return
      }
      let res = await axios.put(`/ui/messageboard/${data.boardID}/savereply`, {
        msgID: data.ID,
        replyContent: data.replyContent
      })
      util.showResponseMessage(res.data)
      if (res.data.status === 1) {
        data.editMode = false
        data.replyFlag = 'Y'
      }
    },

    // 热点标记  flag=Y为标记为热点，flag=N为取消标记热点
    async hotMark(boardID, id, flag) {
      let data = await axios.put(`/ui/messageboard/${boardID}/hotmark`, {
        strIDs: id,
        markFlag: flag
      })
      util.showResponseMessage(data.data)
      if (data.data.status === 1) {
        this.$refs.messageList.getData()
      }
    },

    // 审核
    async doCheck(boardID, id, status) {
      let data = await axios.put(`/ui/messageboard/${boardID}/verify`, {
        strIDs: id,
        verifyFlag: `${status}`
      })
      if (data.data.status === 1) {
        this.$refs.messageList.getData() // 选择行展示留言列表
      }
      util.showResponseMessage(data.data)
    },

    // 删除留言
    async deleteMessage(boardID, id) {
      try {
        await this.$confirm('确定删除吗，删除后无法恢复。是否继续删除？', '删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        return
      }
      let data = await axios.delete(`/ui/messageboard/${boardID}/delmessages`, {
        params: {
          strIDs: `${id}`
        }
      })
      if (data.data.status === 1) {
        this.$refs.messageList.getData()
      }
      util.showResponseMessage(data.data)
    },

    // 切换显示隐藏回复输入框
    toggleReplyBox(item) {
      item.showReplyBox = !item.showReplyBox
    }
  }
}
</script>
<style>
.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;
}
</style>
<style scoped>
.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;
}

.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;
}

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

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

.black {
  color: #484848;
}

.reply-btn {
  float: right;
  margin-top: 5px;
}
</style>
