<template>
  <van-popup v-model:show="show" position="bottom" :style="{ height: '70%' }">
    <h3 class="title">评论区<van-icon name="cross" @click="show = false" /></h3>
    <van-list
      v-model:loading="loading"
      :finished="finished"
      v-model:error="loadError"
      error-text="加载错误，请点击重新加载"
      finished-text="没有更多了"
      @load="getMsgList"
      class="msg-list"
    >
      <ul class="interact-msg">
        <li v-for="item in msgList" :class="[`li${item.id}`]" :key="item.id">
          <div class="chat-time" v-if="item.chatTime">
            {{ item.chatTime }}
          </div>
          <div :class="['flex']">
            <div class="photo">
              <img
                :src="
                  item.replyUserId
                    ? item.replyUserImgUrl
                      ? item.replyUserImgUrl
                      : tgDefaultPhoto
                    : item.userImgUrl
                    ? item.userImgUrl
                    : item.userType !== 1
                    ? tgDefaultPhoto
                    : defaultPhoto
                "
                alt=""
              />
            </div>
            <div class="news-content-wrap">
              <div class="user-info">
                <h3>
                  {{
                    !item.replyUserId
                      ? item.userName === store.state.userInfo.userId
                        ? "我"
                        : item.userName
                      : item.replyUserName
                  }}
                  <span
                    v-if="
                      item.userType === 2 ||
                      (item.replyUserId && item.replyUserType === 2)
                    "
                    >讲师</span
                  >
                  <span
                    v-else-if="
                      item.userType === 3 ||
                      (item.replyUserId && item.replyUserType === 3)
                    "
                    >助教</span
                  >
                </h3>
              </div>
              <div v-if="item.replyUserId">
                <div class="reply-content">
                  <div class="reply">
                    <span style="color: rgba(154, 164, 182, 1)">回复</span
                    ><label>{{ item.userName }}：</label>
                    {{ item.replyContent }}
                  </div>
                  <div class="reply" style="color: rgba(154, 164, 182, 1)">
                    {{ item.userName }}：{{ item.commentContent }}
                  </div>
                </div>
              </div>
              <div v-else-if="!item.replyUserId">
                <p class="text">
                  {{ item.commentContent }}
                </p>
              </div>
            </div>
          </div>
        </li>
      </ul>
    </van-list>

    <div class="input-area">
      <input
        type="text"
        maxlength="200"
        placeholder="发表评论"
        v-model.trim="text"
        @keyup.enter="sendMsg()"
      />
      <button class="send" @click="sendMsg" :disabled="disabledSend">
        发送
      </button>
    </div>
  </van-popup>
</template>

<script setup>
import { ref, defineExpose, defineProps, watch, nextTick } from "vue";
import { useRoute } from "vue-router";
import { useStore } from "vuex";
import { saveComment, queryCommentForApp } from "@//api/shortVideo";
import { formatTimer } from "@/utils/format";

const defaultPhoto = require("@/assets/images/default-photo.png");
const tgDefaultPhoto = require("@/assets/images/tg-p.webp");
const store = useStore();
const show = ref(false);
const route = useRoute();
const loadError = ref(false);

const loading = ref(false);
const finished = ref(false);

defineProps({
  commentCount: {
    type: Number,
  },
  detail: {
    type: Object,
    default: () => {},
  },
});

const msgList = ref([]);

watch(
  () => msgList.value,
  () => {
    let timeList = [];
    msgList.value.forEach((item) => {
      let chatTime = formatTimer(item.replyTime || item.commentTime);
      if (!timeList.includes(chatTime)) {
        timeList.push(chatTime);
        item.chatTime = chatTime;
      } else {
        delete item.chatTime;
      }
    });
  },
  { deep: true }
);

const text = ref();

const disabledSend = ref(false);
const sendMsg = async () => {
  if (disabledSend.value) return;
  disabledSend.value = true;
  let ret = await saveComment({
    commentContent: text.value,
    productId: route.query.id,
    productType: "35",
  }).catch(() => {
    disabledSend.value = false;
  });
  if (ret.code === 0) {
    msgList.value.unshift({
      commentContent: text.value,
      userName: store.state.userInfo.userName,
      userImgUrl: store.state.userInfo.imgUrl,
      commentTime: new Date(),
    });
    text.value = "";
  }
  disabledSend.value = false;
  nextTick(() => {
    document.querySelector(".msg-list").scrollTop = 0;
  });
};

const getMsgList = async () => {
  let ret = await queryCommentForApp({
    lastCommentTime: msgList.value.length
      ? msgList.value[msgList.value.length - 1].commentTime
      : "",
    lastWeight: msgList.value.length
      ? msgList.value[msgList.value.length - 1].weight
      : "",
    pageSize: 10,
    productId: route.query.id,
    productType: "35",
  }).catch(() => {
    loadError.value = true;
  });
  loading.value = false;
  if (ret.code === 0) {
    msgList.value = msgList.value.concat(ret.data.list);
    if (!ret.data.hasNext) {
      finished.value = true;
    }
  } else {
    loadError.value = true;
  }
};

defineExpose({
  show,
});
</script>
<style scoped lang="scss">
.title {
  position: relative;
  color: rgba(27, 35, 48, 1);
  font-weight: 500;
  font-size: 36px;
  line-height: 100px;
  ::v-deep(.van-icon) {
    position: absolute;
    right: 20px;
    top: 50%;
    transform: translateY(-50%);
    color: rgba(154, 164, 182, 1);
    font-size: 40px;
  }
}
.msg-list {
  height: calc(100% - 204px);
  background: rgba(239, 242, 245, 1);
  overflow-y: auto;
}
.interact-msg {
  padding: 20px;
  li {
    margin-bottom: 20px;
    .chat-time {
      color: #888;
      font-size: 24px;
      text-align: center;
    }
    .img {
      max-width: 100%;
      height: 200px;
    }
    .warn {
      text-align: center;
      color: #999;
      flex: 1;
      margin-bottom: 0;
    }
    .flex {
      display: flex;
    }
    .photo {
      margin-right: 20px;
      img {
        display: block;
        width: 88px;
        height: 88px;
        border-radius: 50%;
      }
    }
    .user-info {
      display: flex;
      align-items: center;
      h3 {
        display: flex;
        align-items: center;
        font-size: 28px;
        color: #1b2330;
        line-height: 28px;
        margin-bottom: 20px;
        span {
          color: #ff6f16;
          font-size: 22px;
          line-height: 22px;
          margin-left: 20px;
          border: 1px solid #ff3d36;
          padding: 6px 8px;
          border-radius: 8px;
        }
      }
    }
    .news-content-wrap {
      flex: 1;
      overflow: hidden;
      & > div {
        display: flex;
      }
      .align-center {
        align-items: center;
      }
    }
  }
  li:last-child {
    margin-bottom: 0;
  }
  .row-reverse {
    justify-content: space-between;
    flex-flow: row-reverse;
    .user-info,
    h3 {
      justify-content: space-between;
      flex-flow: row-reverse;
    }
    .photo {
      margin-right: 0;
      margin-left: 20px;
    }
    h3 {
      span {
        margin-left: 0;
        margin-right: 20px;
      }
    }
    .reply-content,
    .text {
      background: #2e78fa;
      color: #fff;
    }
    .reply-content,
    .text,
    & > img,
    .share-tip {
      border-radius: 20px 4px 20px 20px;
    }
    .news-content-wrap > div {
      flex-flow: row-reverse;
    }
  }
  li > div {
    font-size: 24px;
    font-weight: 500;
    letter-spacing: 0;
    text-align: left;
    color: #1b2330;
    margin-bottom: 12px;
    .question-item,
    .product-item {
      display: block;
      p {
        background: none;
        padding-left: 0;
        padding-top: 0;
      }
    }
    label {
      color: #2e78fa;
    }
  }
  p,
  .reply-content {
    padding: 16px 24px;
    background: #fff;
    border-radius: 4px 20px 20px 20px;
    font-size: 26px;
    color: #606877;
    text-align: justify;
    line-height: 30px;
  }
  .reply {
    line-height: 40px;
    margin-right: 10px;
  }
  button {
    height: 44px;
    line-height: 44px;
    border: none;
    border-radius: 20px;
    background-color: rgba(154, 164, 182, 0.1);
    background-repeat: no-repeat;
    background-position: left 10px center;
    background-size: 20px auto;
    padding-left: 32px;
    font-size: 24px;
    padding: 0 20px 0 30px;
    &.share {
      color: #ff3d36;
      background-image: url(../../../assets/images/share-icon2.png);
    }
    &.attention {
      color: #ff7d26;
      background-image: url(../../../assets/images/attention.png);
    }
  }
}

.input-area {
  display: flex;
  align-items: center;
  background: #fff;
  padding: 20px 20px;
  input {
    height: 64px;
    background: #9aa4b61a;
    border-radius: 32px;
    font-weight: 500;
    font-size: 24px;
    letter-spacing: 0;
    line-height: 24px;
    padding: 0 16px;
    flex: 1;
    color: #666;
    margin: 0 20px;
  }

  input::placeholder,
  input::-webkit-input-placeholder {
    color: #666; /* 设置颜色为灰色 */
  }
  button.send {
    height: 64px;
    padding: 0 20px;
    font-size: 28px;
    border-radius: 32px;
    color: #fff;
    background-image: linear-gradient(270deg, #2e78fa 0%, #45acff 100%);
    &[disabled] {
      opacity: 0.3;
    }
  }
}
</style>
