<template>
  <div :class="['interact-scroll', scrollClassName]" ref="container">
    <div class="p20">
      <div class="pulldown-wrapper">
        <div v-if="hasNext">
          <span>加载中...</span>
        </div>
        <div class="top-tip" v-else-if="!hasNext">
          <span class="refresh-hook">暂无更多互动消息</span>
        </div>
      </div>
      <!-- isOpen 2: 不公开 1：公开 -->
      <ul class="interact-msg" ref="msgListRef">
        <li>
          <div class="flex">
            <div class="photo">
              <img
                alt=""
                :src="
                  detail.advisorBasic && detail.advisorBasic.avatar
                    ? detail.advisorBasic.avatar
                    : defaultPhoto
                "
              />
            </div>
            <div class="news-content-wrap">
              <div class="user-info">
                <h3>{{ detail.advisorBasic?.showName }} <span>讲师</span></h3>
              </div>
              <div>
                <p class="text">
                  欢迎进入直播间：<br />
                  1、请自行调节手机音量至合适的状态。<br />
                  2、直播界面显示讲师发布的内容，听众发言可以在讨论区或以弹幕的形式查看。
                </p>
              </div>
              <div class="license">
                {{ detail.advisorBasic.name
                }}<i v-if="detail.advisorBasic.license"
                  >（{{ detail.advisorBasic.license }}）</i
                >
              </div>
            </div>
          </div>
        </li>
        <li
          v-for="item in informMsgList"
          :class="[
            `li${item.id}`,
            item.phone === store.state.userInfo.userId ? 'row-reverse' : '',
          ]"
          :key="item.id"
        >
          <div v-if="item.show">
            <!-- <div v-if="item.type === 3" class="warn">
              {{ item.userName }}：进入直播间
            </div> -->
            <div
              class="chat-time"
              v-if="(isTg && item.tgChatTime) || (!isTg && item.chatTime)"
            >
              {{ isTg ? item.tgChatTime : item.chatTime }}
            </div>
            <div v-if="item.type === 5" class="warn">
              {{
                item.phone === store.state.userInfo.userId
                  ? "我"
                  : detail.showNickname === 2
                  ? maskUserName(item.userName)
                  : item.userName
              }}：分享了直播间
              <button
                class="share"
                @click="sendMsg(5)"
                v-if="item.phone !== store.state.userInfo.userId"
              >
                我也要分享
              </button>
            </div>
            <div
              v-else
              :class="[
                'flex',
                item.phone === store.state.userInfo.userId ? 'row-reverse' : '',
              ]"
            >
              <div class="photo">
                <img
                  :src="
                    item.advisorId
                      ? item.advisorBasic && item.advisorBasic.avatar
                        ? item.advisorBasic.avatar
                        : defaultPhoto
                      : item.userId
                      ? item.imgUrl
                      : tgDefaultPhoto
                  "
                  alt=""
                />
              </div>
              <div class="news-content-wrap">
                <div class="user-info">
                  <h3>
                    {{
                      item.userId
                        ? item.phone === store.state.userInfo.userId
                          ? "我"
                          : detail.showNickname === 2
                          ? maskUserName(item.userName)
                          : item.userName
                        : item.createUserVO
                        ? item.createUserVO.name
                        : item.advisorBasic?.showName
                    }}
                    <span v-if="item.advisorId">讲师</span>
                    <span v-else-if="item.createUserVO">助教</span>
                  </h3>
                </div>
                <div v-if="item.type === 1 && item.replyBasic">
                  <div>
                    <div class="reply-content">
                      <div class="reply">
                        <span style="color: rgba(154, 164, 182, 1)">回复</span
                        ><label
                          >{{
                            item.replyBasic.userId ===
                            store.state.userInfo.userId
                              ? "我"
                              : detail.showNickname === 2
                              ? maskUserName(item.replyBasic.userName)
                              : item.replyBasic.userName
                          }}：</label
                        >
                        {{ item.content }}
                      </div>
                      <div class="reply" style="color: rgba(154, 164, 182, 1)">
                        {{
                          item.replyBasic.userId === store.state.userInfo.userId
                            ? "我"
                            : detail.showNickname === 2
                            ? maskUserName(item.replyBasic.userName)
                            : item.replyBasic.userName
                        }}：{{ item.replyBasic.content }}
                      </div>
                    </div>
                    <div class="license">
                      {{ item.advisorBasic?.name
                      }}<i v-if="detail.advisorBasic.license"
                        >（{{ item.advisorBasic?.license }}）</i
                      >
                    </div>
                  </div>
                </div>
                <div v-else-if="item.type === 1 && !item.replyBasic">
                  <div>
                    <p class="text" v-if="!item.content.includes('upImg')">
                      {{ item.content }}
                    </p>
                    <img
                      v-else
                      class="img"
                      @click="imagePreview(item.content.split('upImg-')[1])"
                      :src="item.content.split('upImg-')[1]"
                    />
                    <div v-if="item.advisorId" class="license">
                      {{ detail.advisorBasic.name
                      }}<i v-if="detail.advisorBasic.license"
                        >（{{ detail.advisorBasic.license }}）</i
                      >
                    </div>
                  </div>
                </div>
                <div v-else-if="item.type === 2" class="product-item">
                  <p>分享了一个产品</p>
                  <ProductItem
                    :item="item.productBasic"
                    :liveProductId="detail.id"
                    :tgId="detail.advisorBasic?.id"
                    :isShopCar="true"
                  />
                </div>
                <div v-else-if="item.type === 4">
                  <p>
                    <label
                      >{{
                        item.phone === store.state.userInfo.userId
                          ? "我"
                          : detail.showNickname === 2
                          ? maskUserName(item.userName)
                          : item.userName
                      }}：</label
                    >关注了老师
                  </p>
                  <button
                    class="attention"
                    @click="subAdvisor"
                    v-if="
                      item.phone !== store.state.userInfo.userId &&
                      detail.isSubAdvisor !== 1
                    "
                  >
                    我也关注
                  </button>
                </div>
                <div
                  v-else-if="[6, 7, 9, 10].includes(item.type)"
                  style="color: #f46946"
                >
                  <p>{{ item.content }}</p>
                </div>
                <div v-else-if="item.type === 8" style="color: #f46946">
                  <p>
                    <label
                      >{{
                        detail.showNickname === 2
                          ? maskUserName(item.userName)
                          : item.userName
                      }}：</label
                    >{{ item.content }}
                  </p>
                </div>
                <div v-else-if="item.type === 11" class="question-item">
                  <p>发起了一个问卷任务</p>
                  <div class="question" @click="goAnswer(item)">
                    <h5>{{ item.content }}</h5>
                    <span>{{
                      item.questionDesc ? item.questionDesc : "暂无说明"
                    }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </li>
      </ul>
    </div>
    <div class="new-msg-tip" @click="lookNewMsg" v-if="newMsgNum">
      您有{{ newMsgNum }}条新的消息
    </div>
    <!-- <div class="product-float" v-if="productFloatShow">
      <ProductItem
        :item="informMsgList[informMsgList.length - 1].productBasic"
        :liveProductId="detail.id"
        :tgId="detail.advisorBasic?.id"
      >
        <img
          @click.stop="productFloatShow = false"
          src="@/assets/images/chat/close.png"
        />
      </ProductItem>
    </div> -->
  </div>
  <QuestionnairePopup ref="questionnairePopupRef" :questionId="questionId" />
</template>

<script setup>
import {
  ref,
  defineProps,
  onBeforeUnmount,
  defineExpose,
  watch,
  nextTick,
  onMounted,
  computed,
  defineEmits,
} from "vue";
import { useStore } from "vuex";
import { showToast, showImagePreview } from "vant";
import {
  sendFollowMessage,
  queryQuestionCheck,
  queryLiveTgHisMsg,
  queryLiveHisMsg,
} from "@/api/video";
import QuestionnairePopup from "../components/QuestionnairePopup.vue";
import useChatData from "@/hooks/useChatData";
import useGetLiveStatusObj from "@/hooks/useGetLiveStatusObj";
import ProductItem from "../components/ProductItem.vue";
import { attentionTg } from "@/api/index";
import emitter from "@/utils/emitter";
// import dayjs from "dayjs";

const store = useStore();
const $liveStatusObj = useGetLiveStatusObj();

const props = defineProps({
  className: {
    type: String,
  },
  detail: {
    // 视频详情
    type: Object,
    default: () => ({}),
  },
  informMsgList: {
    // 聊天互动信息
    type: Array,
    default: () => [],
  },
  isTg: {
    type: Boolean,
    default: false,
  },
});

const defaultPhoto = require("@/assets/images/default-photo.png");
const tgDefaultPhoto = require("@/assets/images/tg-p.webp");
// const productFloatShow = ref(false);
const scrollClassName = ref(`interact-scroll-${new Date().getTime()}`);

const { msgListRef, bs } = useChatData(
  Object.assign({ isTg: props.isTg }, props.detail, {
    className: `.${scrollClassName.value}`,
  })
);

const hasNext = computed(() => {
  return props.isTg
    ? store.state.interactMsgObj.tgHasHisMsg
    : store.state.interactMsgObj.hasHisMsg;
});

watch(hasNext, (value) => {
  if (value) bs.value && bs.value.openPullDown();
});

watch(
  () => props.informMsgList,
  () => {
    nextTick(() => {
      bs.value && bs.value.refresh();
      if (
        (props.isTg && store.state.interactMsgObj.isTgScrollToBottom) ||
        (!props.isTg && store.state.interactMsgObj.isScrollToBottom)
      ) {
        nextTick(() => {
          bs.value && bs.value.scrollTo(0, bs.value.maxScrollY, 0);
        });
      }
    });
  },
  { deep: true }
);

let intervalTime = null;

const replenishMsg = async () => {
  let fn = props.isTg ? queryLiveTgHisMsg : queryLiveHisMsg;
  let ret = await fn({
    id: props.detail.id,
    lastId: "",
    size: 20,
    status: 1,
  });
  if (ret.code === 0) {
    let list = ret.data.list.reverse();
    emitter.emit("informMsgListPush", list);
  }
};

let getNewMsg = (once) => {
  if (once) {
    replenishMsg();
  } else {
    clearInterval(intervalTime);
    intervalTime = setInterval(replenishMsg, 1000 * 30);
  }
};

emitter.on("getNewMsg", getNewMsg);
emitter.on("cancelGetNewMsg", () => {
  clearInterval(intervalTime);
});

async function subAdvisor() {
  let ret = await attentionTg({
    advisorId: props.detail.advisorBasic?.id,
    channel: 2,
    option: props.detail.isSubAdvisor === 1 ? 2 : 1,
    videoId: props.detail.id,
  });
  if (ret.code === 0) {
    emitter.emit("updateVideoDetail", {
      isSubAdvisor: props.detail.isSubAdvisor === 1 ? 2 : 1,
    });
    props.detail.isSubAdvisor === 1 &&
      [
        $liveStatusObj.InLive,
        $liveStatusObj.PausePlay,
        $liveStatusObj.FinishPlay,
      ].includes(props.detail.liveStatus) &&
      sendFollowMessage({
        id: props.detail.id,
        option: props.detail.isSubAdvisor === 1 ? 2 : 1,
      });
  }
}

const questionnairePopupRef = ref();
const questionId = ref();
const goAnswer = async (item) => {
  let ret = await queryQuestionCheck({ questionId: item.questionId });
  if (ret.code === 0) {
    if (ret.data.result) {
      questionId.value = item.questionId;
      questionnairePopupRef.value.showPopup = true;
    } else if (ret.data.type === 1) {
      return showToast("您已完成问卷任务，无须重复填写！");
    } else if (ret.data.type === 2) {
      return showToast("问卷已删除！");
    }
  }
};
const emit = defineEmits(["optShare"]);
const sendMsg = (type, params) => {
  if (type === 5) {
    emit("optShare");
  }
  emitter.emit("emSendMsg", {
    type,
    params,
  });
};

onBeforeUnmount(() => {
  emitter.off("getNewMsg");
  emitter.off("cancelGetNewMsg");
});

const imagePreview = (url) => {
  showImagePreview({
    images: [url],
    closeable: true,
  });
};

const newMsgNum = computed(() => {
  return props.isTg
    ? store.state.interactMsgObj.temTgInteractShowNum
    : store.state.interactMsgObj.temUserInteractShowNum;
});

onMounted(() => {
  bs.value.on("scrollEnd", () => {
    let isBottom = bs.value.maxScrollY + 20 >= bs.value.y;
    store.commit("setIsScrollToBottom", {
      isTg: props.isTg,
      data: isBottom,
    });
    if (isBottom) resetData();
  });
});

const lookNewMsg = () => {
  resetData();
};

const resetData = () => {
  store.commit("interactMsgMerge", { isTg: props.isTg });
  nextTick(() => {
    bs.value && bs.value.refresh();
    nextTick(() => {
      bs.value && bs.value.scrollTo(0, bs.value.maxScrollY, 0);
    });
  });
};

const maskUserName = (value) => {
  return value.charAt(0) + "**";
};

defineExpose({
  bs,
});
</script>
<style scoped lang="scss">
.interact-scroll {
  position: relative;
  overflow: hidden;
  text-align: left;
  height: 100%;
  box-sizing: border-box;
  .p20 {
    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;
  }
  .license {
    padding: 0;
    color: #c6c7c9;
    line-height: 24px;
    font-size: 24px;
    border-radius: 0 20px 0 20px;
    margin: 12px 0 1px 1px;
  }
  .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);
    }
  }
}

.pulldown-wrapper {
  position: absolute;
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
  transform: translateY(-100%) translateZ(0);
  text-align: center;
  color: #999;
  font-size: 24px;
}
.product-item {
  .item-wrap {
    width: 600px;
  }
}
.question {
  width: 600px;
  background: #fff;
  border-radius: 8px;
  color: #000;
  padding: 16px;
  box-sizing: border-box;
  background: url(../../../assets/images/chat/question-bg.png) no-repeat center;
  background-size: 100% 100%;
  height: 174px;
  box-sizing: border-box;
  h5 {
    font-size: 28px;
    margin-bottom: 20px;
    color: #1e3566;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  span {
    color: #8ea4b6;
    font-size: 24px;
    line-height: 36px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: block;
  }
}
.hp {
  ::v-deep .item-wrap,
  .question {
    height: 140px;
  }
  .question {
    h5 {
      margin-bottom: 8px;
    }
  }
  ::v-deep .item-wrap {
    padding: 16px;
    h4 {
      margin-bottom: 0;
    }
    .intro {
      line-height: 1.2em;
    }
  }
}
.product-float {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 470px;
  height: 180px;
  ::v-deep .item-wrap {
    background: url(../../../assets/images/chat/product-float-bg.png) no-repeat
      center;
    background-size: 100% 100%;
  }
  img {
    display: block;
    position: absolute;
    width: 24px;
    height: 24px;
    right: 20px;
    top: 20px;
  }
}
@media screen and (min-width: 480px) {
  .interact-scroll .question {
    height: 230px !important;
    padding: 20px 30px;
    h5 {
      line-height: 50px !important;
    }
  }
  .hp .question {
    height: 200px !important;
    padding: 20px 20px;
  }
  .interact-scroll h4 {
    line-height: 48px !important;
  }
  .hp ::v-deep .item-wrap {
    height: 170px !important;
    h4,
    p {
      line-height: 50px;
    }
  }
}
.new-msg-tip {
  position: absolute;
  left: 0;
  bottom: 0px;
  color: #2e78fa;
  background: #fff;
  border: 1px solid rgba(204, 204, 204, 0.2);
  font-size: 24px;
  padding: 8px 12px;
  border-radius: 20px;
}
</style>
