<template>
  <div :class="['interact-scroll', className]" ref="container">
    <div>
      <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
          v-for="(item, index) in msgList.filter(
            (item) =>
              (!item.replyBasic && item.isOpen !== 2) ||
              store.state.userInfo.userId === item.phone ||
              (item.replyBasic &&
                (item.replyBasic.isOpen === 1 ||
                  store.state.userInfo.userId === item.replyBasic.userId))
          )"
          :class="[`li${index}`]"
          :key="index"
        >
          <div v-if="item.type === 1 && item.replyBasic">
            <div class="reply-content">
              <div class="reply">
                <label>直播老师</label
                ><span style="color: rgba(154, 164, 182, 1)">回复</span
                ><label>{{ item.replyBasic.userName }}：</label>
                {{ item.content }}
              </div>
              <div class="reply" style="color: rgba(154, 164, 182, 1)">
                {{ item.replyBasic.userName }}：{{ item.replyBasic.content }}
              </div>
            </div>
          </div>
          <div v-if="item.type === 1 && !item.replyBasic">
            <p>
              <label
                >{{
                  item.userId
                    ? item.phone === store.state.userInfo.userId
                      ? "我"
                      : item.userName
                    : "直播老师"
                }}：</label
              >
              {{ item.content }}
            </p>
          </div>
          <div v-else-if="item.type === 2" class="product-item">
            <p>
              <label>直播老师：</label>
              分享了一个产品
            </p>
            <ProductItem
              :item="item.productBasic"
              :liveProductId="detail.id"
              :tgId="detail.advisorBasic?.id"
              :isShopCar="true"
            />
          </div>
          <div v-else-if="item.type === 3">
            <p>
              <label>{{ item.userName }}：</label>进入直播间
            </p>
          </div>
          <div v-else-if="item.type === 4">
            <p>
              <label
                >{{
                  item.phone === store.state.userInfo.userId
                    ? "我"
                    : 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="item.type === 5">
            <p>
              <label
                >{{
                  item.phone === store.state.userInfo.userId
                    ? "我"
                    : item.userName
                }}：</label
              >分享了直播间
            </p>
            <button
              class="share"
              @click="sendMsg(5)"
              v-if="item.phone !== store.state.userInfo.userId"
            >
              我也要分享
            </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>{{ item.userName }}：</label>{{ item.content }}
            </p>
          </div>
          <div v-else-if="item.type === 11" class="flex-column">
            <p>
              <label>直播老师：</label>
              发起了一个问卷任务
            </p>
            <div class="question" @click="goAnswer(item)">
              <h5>{{ item.content }}</h5>
              <span>{{
                item.questionDesc ? item.questionDesc : "暂无说明"
              }}</span>
            </div>
          </div>
        </li>
      </ul>
    </div>
    <div class="product-float" v-if="productFloatShow">
      <ProductItem
        :item="informMsgList[informMsgList.length - 1].productBasic"
        :liveProductId="detail.id"
        :tgId="detail.advisorBasic?.id"
        :isShopCar="true"
      >
        <img
          @click.stop="productFloatShow = false"
          src="@/assets/images/chat/close.png"
        />
      </ProductItem>
    </div>
  </div>
  <QuestionnairePopup ref="questionnairePopupRef" :questionId="questionId" />
</template>

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

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

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

const productFloatShow = ref(false);

const { hisMsgList, msgListRef, hasNext, bs } = useChatData(
  Object.assign({}, props.detail, { className: ".interact-scroll" })
);

const msgList = computed(() => {
  return hisMsgList.value.concat(props.informMsgList);
});

let intervalTime = null;

const replenishMsg = async () => {
  let ret = await queryLiveHisMsg({
    id: props.detail.id,
    lastId: "",
    size: 20,
    status: 1,
  });
  if (ret.code === 0) {
    // let idsArr = msgList.value.map((item) => item.id);
    let list = ret.data.list.reverse();
    emitter.emit("informMsgListPush", list);
    // list.forEach((item) => {
    //   if (!idsArr.includes(item.id)) {
    //     emitter.emit("informMsgListPush", item);
    //   }
    // });
  }
};

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) => {
  // if (props.detail.liveStatus === $liveStatusObj.FinishPlay) {
  //   return showToast("直播已结束，不能填写问卷！");
  // }
  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(["sendMsg"]);
const sendMsg = (type, params) => {
  emit("sendMsg", type, params);
};

emitter.on("uploadMsg", ({ key, item }) => {
  for (let i = 0; i < hisMsgList.value.length; i++) {
    if (key === "status" && hisMsgList.value[i].id === Number(item.data)) {
      hisMsgList.value.splice(i, 1);
    } else if (
      key === "isOpen" &&
      hisMsgList.value[i].id === Number(item.messageId)
    ) {
      hisMsgList.value[i].isOpen = item.isOpen;
    } else if (
      key === "isOpen" &&
      hisMsgList.value[i].replyBasic &&
      hisMsgList.value[i].replyBasic.id === Number(item.messageId)
    ) {
      hisMsgList.value[i].replyBasic.isOpen = item.isOpen;
    }
  }
  nextTick(() => {
    bs && bs.refresh();
  });
});

onBeforeUnmount(() => {
  emitter.off("uploadMsg");
  emitter.off("getNewMsg");
  emitter.off("cancelGetNewMsg");
});
</script>
<style scoped lang="scss">
.interact-scroll {
  position: relative;
  overflow: hidden;
  text-align: left;
  height: 100%;
  li > div {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    font-size: 24px;
    font-weight: 500;
    letter-spacing: 0;
    text-align: left;
    color: #1b2330;
    margin-bottom: 12px;
    &.flex-column {
      flex-direction: column;
      justify-content: flex-end;
      align-items: start;
    }
    label {
      color: #2e78fa;
    }
    &.product-item {
      flex-direction: column;
      align-items: flex-start;
    }
  }
  p,
  .reply-content {
    line-height: 28px;
    border-radius: 20px;
    background-color: #ebeef7;
    padding: 8px 16px;
    word-break: break-all;
  }
  .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);
    }
  }
}

.hp {
  max-height: 360px;
  width: calc(100% - 238px);
  margin-right: 20px;
  li > div {
    color: #fff;
    label {
      color: rgba(154, 191, 255, 1);
    }
  }
  p,
  .reply-content {
    background-color: rgba(0, 0, 0, 0.3);
  }
  button {
    background-color: rgba(0, 0, 0, 0.3);
  }
}

.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;
}
.question {
  width: 100%;
  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;
    }
  }
}
</style>
