<!-- 评论 -->
<template>
  <div style="position: relative; min-width: 400px">
    <div
      class="block"
      :style="{
        height: height ? height : '',
        'max-height': maxHeight ? maxHeight : ''
      }"
      :class="inputPosition"
    >
      <div
        v-if="inputPosition == 'top' && likeUsers.length > 0"
        class="like-list"
      >
        <i class="fa fa-thumbs-o-up" aria-hidden="true"></i>
        <span v-if="likeUsers.length < 11">{{ getLikeUserName(likeUsers) }}</span>
        <span v-else>
          {{ getLikeUserName(likeUsers.splice(0, 10)) }}
          等{{ likeUsers.legnth }}人点赞
        </span>
      </div>

      <!-- 评论列表 -->
      <div v-for="item in comments" :key="item.Id" class="common">
        <!-- 头像 -->
        <el-avatar size="small" :src="item.AvatarUrl"></el-avatar>
        <!-- 评论人、评论内容 -->
        <div class="author">{{ item.UserName }}：</div>
        <div class="content">{{ item.Content }}</div>
        <div class="reply" v-if="item.RefId && item.ReplyComment">
          <span class="author">@{{ item.ReplyComment.UserName }}:</span>
          {{ item.ReplyComment.Content }}
        </div>
        <div
          class="reply"
          v-if="item.RefId && !item.ReplyComment"
          style="text-align: center"
        >该评论已删除</div>

        <!-- 评论时间 -->
        <div class="date">{{ item.Created | currentdate }}</div>
        <!-- 删除按钮 -->
        <el-link
          type="primary"
          class="delete-button"
          :underline="false"
          @click="remove(item)"
          v-if="userId == item.UserId && userType == item.UserType"
        >
          <i class="fa fa-trash-o" aria-hidden="true"></i>
        </el-link>
        <!-- 回复按钮 -->
        <el-link
          type="primary"
          class="reply-button"
          :underline="false"
          @click="setReply(item)"
        >
          <i class="fa fa-commenting-o" aria-hidden="true"></i>
        </el-link>
      </div>
      <!-- 下部分页标签 -->
      <cs-table-pagination
        layout="total, prev, pager, next, ->, sizes"
        :currentPage="currentPage"
        :pageSizes="pageSizes"
        :pageSize="pageSize"
        :total="total"
        @change="handlePageOrSizeChange"
      ></cs-table-pagination>

      <div
        v-if="inputPosition == 'bottom' && likeUsers.length > 0"
        class="like-list"
      >
        <i class="fa fa-thumbs-o-up" aria-hidden="true"></i>
        <span v-if="likeUsers.length < 11">{{ getLikeUserName(likeUsers) }}</span>
        <span v-else>
          {{ getLikeUserName(likeUsers.splice(0, 10)) }}
          等{{ likeUsers.legnth }}人点赞
        </span>
      </div>

      <!-- 暂无评论 -->
      <div v-if="comments.length == 0" class="no-comment">暂无评论</div>

      <!-- 输入框 -->
      <div class="sendText" :class="inputPosition">
        <el-input :placeholder="placeholder" v-model="commentText">
          <template slot="append">
            <el-button
              @click="sendComment"
              icon="el-icon-s-promotion"
              :disabled="!commentText"
            >发送</el-button>
          </template>
        </el-input>

        <el-link
          class="like"
          :underline="false"
          @click="setLike(!currentLike.IsLiked)"
        >
          <i
            class="fa fa-thumbs-up"
            style="color: #f56c6c"
            aria-hidden="true"
            v-if="currentLike.IsLiked"
          ></i>
          <i class="fa fa-thumbs-o-up" aria-hidden="true" v-else></i>
        </el-link>
      </div>
    </div>

    <!-- 回复评论弹出框 -->
    <el-dialog
      :visible="visible"
      :title="'回复评论'"
      :close-on-click-modal="false"
      :show-close="false"
      width="30%"
      append-to-body
    >
      <el-input :placeholder="'@' + replyName" v-model="commentReplyText" />
      <span slot="footer" class="dialog-footer">
        <cs-button @click="visible = false">取消</cs-button>
        <cs-button-save @click="sendComment()" :disabled="!commentReplyText">确定</cs-button-save>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import Request from "../../../lib/utils/request";

export default {
  name: "CsCommon",
  props: {
    // 租户编号
    tenantId: {
      type: Number,
      default: null,
    },
    // 当前用户编号
    userId: {
      type: Number,
      default: null,
    },
    // 引用对象类型名称
    objectTypeName: {
      type: String,
      default: null,
    },
    // 引用对象编号
    itemId: {
      type: Number,
      default: 0,
    },
    // 引用对象标题
    itemTitle: {
      type: String,
      default: null,
    },
    // 评论区域高度
    height: {
      type: String,
      default: "",
    },
    // 评论区域高度
    maxHeight: {
      type: String,
      default: "400px",
    },
    // 输入框位置
    inputPosition: {
      type: String,
      default: "top",
    },
    // 评论输入框占位文字
    placeholder: {
      type: String,
      default: "请输入...",
    },
  },
  components: {},
  data() {
    return {
      type: 1, // 评论类型：1 企业内部评论、2 公共评论
      userType: 1, // 用户类型：1 普通租户成员、2 家长用户、3 微信用户

      items: [],
      comments: [],
      likeUsers: [],
      currentLike: {},

      currentPage: 1,
      pageSizes: [10, 20, 50],
      pageSize: 20,
      total: 0,

      visible: false,
      replyName: "",
      commentText: "",
      commentReplyText: "",
      refId: 0,
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  filters: {},
  //方法集合
  methods: {
    getLikeUserName(items) {
      let likeNames = [];
      // 点赞人
      for (let i = 0; i < items.length; i++) {
        const item = items[i];

        if (!item.IsLiked) {
          continue;
        }

        likeNames.push(item.MemberDisplayName);
      }
      return likeNames.join(",");
    },

    /** 发送评论 */
    sendComment() {
      var content = "";
      if (this.refId) {
        content = this.commentReplyText;
      } else {
        content = this.commentText;
      }
      if (!content) {
        return;
      }

      let item = {
        UserType: this.userType,
        UserId: this.userId,
        Content: content,
        RefId: this.refId,
      };
      let params = {
        objectTypeName: this.objectTypeName,
        type: this.type,
        itemId: this.itemId,
        itemTitle: this.itemTitle,
      };
      Request({
        url: "/api/Comment/{0}".format(this.tenantId),
        params: params,
        data: JSON.stringify(item),
        method: "post",
      }).then((res) => {
        this.comments.unshift(res);
        this.commentText = "";
        this.commentReplyText = "";
        this.refId = 0;
        this.visible = false;
        this.$util.info("添加评论成功");
      });
    },

    /** 删除评论 */
    remove(item) {
      this.$confirm("是否删除该条评论", this.$t("common.tips"), {
        confirmButtonText: this.$t("common.ok"),
        cancelButtonText: this.$t("common.cancel"),
        type: "warning",
      })
        .then(() => {
          Request({
            url: "/api/Comment/{0}/{1}".format(item.TenantId, item.Id),
            params: { type: this.type },
            method: "delete",
          }).then((res) => {
            this.comments.splice(this.comments.indexOf(item), 1);
            this.$util.info("删除评论成功");
          });
        })
        .catch(() => {});
    },

    /** 回复 */
    setReply(item) {
      this.visible = true;
      this.refId = item.Id;
      this.replyName = item.UserName;
    },

    /** 点赞 */
    setLike(isLiked) {
      let params = {
        objectTypeName: this.objectTypeName,
        type: this.type,
        userType: this.userType,
        userId: this.userId,
        itemId: this.itemId,
        itemTitle: this.itemTitle,
      };
      Request({
        url: "/api/Comment/{0}/ObjectLike/{1}".format(this.tenantId, isLiked),
        params: params,
        method: "patch",
      }).then((res) => {
        this.currentLike = res;

        var isExecute = false;
        for (let i = 0; i < this.likeUsers.length; i++) {
          const likeUser = this.likeUsers[i];

          if (likeUser.Id == res.Id) {
            likeUser.IsLiked = res.IsLiked;
            isExecute = true;
            break;
          }
        }
        if (!isExecute) {
          this.likeUsers.push(res);
        }
      });
    },

    /* 当前页面或者页面显示数据个数变动 */
    handlePageOrSizeChange({ currentPage, pageSize }) {
      this.currentPage = currentPage;
      this.pageSize = pageSize;
      this.initData();
    },

    /* 构造数据 */
    initData() {
      // 生成表格数据
      let tableData = [];
      let i = (this.currentPage - 1) * this.pageSize;
      for (i; i < this.items.length; i++) {
        const item = this.$util.copy(this.items[i]);

        if (i >= this.currentPage * this.pageSize) {
          break;
        }
        tableData.push(item);
      }
      this.comments = tableData;
    },

    init() {
      let params = {
        objectTypeName: this.objectTypeName,
        type: this.type,
        userType: this.userType,
        userId: this.userId,
        itemId: this.itemId,
      };
      Request({
        url: "/api/Comment/{0}".format(this.tenantId),
        params: params,
        method: "get",
      }).then((res) => {
        this.items = this.$util.copy(res.Comments);
        this.total = this.items.length;
        this.likeUsers = res.LikeUsers;
        this.currentLike = res.CurrentLike;
        this.initData();
      });
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    if (this.tenantId === null) {
      this.$util.warning("请配置租户编号");
      return;
    }
    if (!this.userId) {
      this.$util.warning("请配置当前用户编号");
      return;
    }
    if (!this.objectTypeName) {
      this.$util.warning("请配置引用对象类型");
      return;
    }
    if (!this.itemId) {
      this.$util.warning("请配置引用对象编号");
      return;
    }

    this.init();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='scss' scoped>
.block {
  padding: 10px;
  overflow: auto;

  // 评论
  .common {
    line-height: 1.5;
    margin-bottom: 10px;
    padding: 0 0 30px 30px;
    position: relative;
    border-bottom: 1px solid #f0f0f0;
    font-size: 15px;

    // 头像
    .el-avatar {
      position: absolute;
      top: 0;
      left: 0;
    }

    // 评论人
    .author {
      margin-left: 5px;
      color: #0c73c2;
      line-height: 30px;
      display: inline-block;
    }

    // 评论内容
    .content {
      display: inline;
      word-break: break-all;
    }

    // 回复内容
    .reply {
      display: block;
      background-color: #f5f5f5;
      word-break: break-all;
      padding: 5px 10px;
      color: #626262;
    }

    // 日期时间
    .date {
      position: absolute;
      left: 34px;
      bottom: 3px;
      color: #909399;
    }

    // 删除按钮
    .delete-button {
      position: absolute;
      right: 45px;
      bottom: 1px;
      color: #909399;
      font-size: 18px;
    }

    // 删除按钮
    .reply-button {
      position: absolute;
      right: 10px;
      bottom: 3px;
      color: #909399;
      font-size: 18px;
    }
  }

  // 输入框
  .sendText {
    width: 100%;
    height: 40px;
    z-index: 10;

    // 点赞
    .like {
      position: absolute;
      right: 100px;
      top: 7px;
      font-size: 22px;
    }
  }

  // 点赞列表
  .like-list {
    background-color: #f5f5f5;
    color: #409eff;
    padding: 7px;
    margin-bottom: 7px;
  }

  .sendText.top {
    position: absolute;
    top: 0;
    left: 0;
  }
  .sendText.bottom {
    position: absolute;
    bottom: 0;
    left: 0;
  }

  // 暂无评论
  .no-comment {
    line-height: 1.5;
    padding: 20px 0;
    text-align: center;
    color: #909399;
  }
}

.block.top {
  padding-top: 50px;
}

.block.bottom {
  padding-bottom: 50px;
}
</style>