<template>
  <div class="flex-grow">
    <div class="flex justify-between h-60px p-10px">
      <div v-if="selectHistoryUser" class="flex items-center">
        <div> {{ selectHistoryUser?.name }}/{{ selectHistoryUser?.sex }}/{{ selectHistoryUser?.age }}</div>
        <el-tag v-if="selectHistoryUser.consultType ==='onlineMedicinePurchase'" class="ml-2"
          type="warning">在线配药</el-tag>
      </div>
      <div class="flex items-center">
        <template v-if="isShowIllnessSummary">
          <div
            class="flex-shrink-0 border border-blue-500 rounded px-10px py-4px flex-shrink-0 cursor-pointer text-blue-500 text-14px"
            @click="showIllnessSummary()">本次病情概要</div>
          <div
            class="flex-shrink-0 ml-5px border border-blue-500 rounded px-10px py-4px flex-shrink-0 cursor-pointer text-blue-500 text-14px"
            @click="showArchive()">病历档案</div>
        </template>
        <div v-if="diagnosisExist"
          class="ml-5px flex-shrink-0 border border-blue-500 rounded px-10px py-4px flex-shrink-0 cursor-pointer text-blue-500 text-14px"
          @click="showDiagnosisDrawer()">预览本次医嘱</div>
      </div>
    </div>
    <div style="height: calc(100% - 80px);">
      <el-scrollbar height="100%" class="bg-white">
        <empty-data v-if="messageList.length === 0" title="暂无聊天记录" padding="0 0 15px" text-top="10px" />
        <div class="p-36px">
          <template v-for="i in messageList" :key="i._id">
            <div class="text-gray-400 text-12px leading-4 py-10px text-center mx-auto w-4/5" v-if="showTime(i)">{{
              formatTime(i.EventTime) }}</div>
            <div v-for="item in i.MsgBody">
              <customeMessageCustom v-if="item.MsgType === 'TIMCustomElem'"
                :messageItem="transformCustomMessage(item.MsgContent)"></customeMessageCustom>
              <div v-if="item.MsgType === 'TIMTextElem'">
                <message-me v-if="i.From_Account === doctorCode" :name="selectHistoryUser.doctorName"
                  :text="item.MsgContent.Text" />
                <message-other v-else :text="item.MsgContent.Text" :name="selectHistoryUser.name" />
              </div>
            </div>
          </template>
        </div>
      </el-scrollbar>
    </div>
  </div>
  <archive-drawer :patient="selectHistoryUser || {}" :visible="archiveVisible" @close="archiveVisible = false" />
  <illness-summary :order="selectHistoryUser" :visible="summaryVisible" @close="summaryVisible = false" />
  <diagnosis-drawer :canEdit="false" :order="selectHistoryUser" :visible="visible" @close="visible = false" />
</template>
<script setup>
import { onMounted, ref, watch, inject, computed } from "vue";
import customeMessageCustom from "../../../TUIKit/customComponents/custome-message-custom/index.vue";
import illnessSummary from "../chat-home/illness-summary/illness-summary.vue";
import diagnosisDrawer from "../chat-home/diagnosis-drawer/diagnosis-drawer.vue";
import archiveDrawer from "@/components/archive-drawer/archive-drawer.vue";
import EmptyData from "@/components/empty-data.vue";

import dayjs from "dayjs";
import messageMe from "./message-me.vue";
import messageOther from "./message-other.vue";
import { getChatRecord, orderHasDiagnosis } from "@/api/hlw";
const doctorCode = sessionStorage.getItem("doctorNo");
const summaryVisible = ref(false);
const visible = ref(false);
const archiveVisible = ref(false);

function showIllnessSummary() {
  summaryVisible.value = true;
}

function showDiagnosisDrawer() {
  visible.value = true;
}
const formatTime = (time) => {
  const now = dayjs();
  const messageTime = dayjs(time);

  if (now.isSame(messageTime, "day")) {
    return messageTime.format("HH:mm");
  } else if (now.isSame(messageTime, "year")) {
    return messageTime.format("MM-DD");
  } else {
    return messageTime.format("YYYY-MM-DD");
  }
};
const props = defineProps({
  selectHistoryUser: {
    type: Object,
    default: null,
  },
});
const messageList = ref([]);
const isShowIllnessSummary = computed(() => props.selectHistoryUser && props.selectHistoryUser._id);

// 添加变量跟踪上一次显示的日期
const lastDisplayedDate = ref(null);

function showTime(item) {
  const msg = item.MsgBody[0];
  if ((msg.MsgType === "TIMCustomElem" && msg.MsgContent.Ext) || (msg.MsgType === "TIMTextElem" && msg.MsgContent.Text)) {
    // 检查当前消息日期是否与最后显示的日期相同
    const currentDate = dayjs(item.EventTime).format('YYYY-MM-DD');

    if (currentDate !== lastDisplayedDate.value) {
      // 更新最后显示的日期并显示时间
      lastDisplayedDate.value = currentDate;
      return true;
    }
    return false;
  }
  return true;
}

// 转换消息类型
function transformCustomMessage(message) {
  return {
    payload: {
      data: message.Data,
      extension: message.Ext,
    },
  };
}

const diagnosisExist = ref(false);

async function queryDiagnosisExist() {
  if (props.selectHistoryUser.orderId && props.selectHistoryUser.patientId) {
    const res = await orderHasDiagnosis({
      orderId: props.selectHistoryUser.orderId,
      patientId: props.selectHistoryUser.patientId,
    });
    diagnosisExist.value = res.data && typeof res.data.exist === "boolean" ? res.data.exist : false;
  } else {
    diagnosisExist.value = true;
  }
}

// 过滤掉没有 extension 内容的视频问诊信令消息
function shouldFilterMessage(msg) {
  if (!msg.MsgBody || !Array.isArray(msg.MsgBody)) return false;

  // 检查消息体中是否全部都是空的视频信令
  const hasValidContent = msg.MsgBody.some(item => {
    if (item.MsgType === "TIMCustomElem") {
      const content = item.MsgContent || {};
      // 如果是视频问诊信令
      if (content.Desc === "VIDEO_CONSULT") {
        // 检查是否有扩展内容
        const ext = typeof content.Ext === "string" ? content.Ext.trim() : "";
        return !!ext; // 有内容才保留
      }
      // 其他自定义消息保留
      return true;
    }
    // 文本消息等其他类型保留
    return true;
  });

  return !hasValidContent; // 如果没有有效内容，返回 true 表示需要过滤
}

// 获取历史聊天记录
const getHistoryChatRecord = async () => {
  const { data, success } = await getChatRecord({
    doctorNo: sessionStorage.getItem("doctorNo"),
    orderId: props.selectHistoryUser?.orderId,
  });
  if (success) {
    // 过滤掉相同MsgId的数据和空的视频信令消息
    const uniqueMessages = [];
    const msgIdSet = new Set();

    if (data.data && Array.isArray(data.data)) {
      data.data.forEach(msg => {
        // 过滤掉重复的消息和空的视频信令消息
        if (!msgIdSet.has(msg.MsgId) && !shouldFilterMessage(msg)) {
          msgIdSet.add(msg.MsgId);
          uniqueMessages.push(msg);
        }
      });
      messageList.value = uniqueMessages;
    } else {
      messageList.value = data.data || [];
    }

    // 重置最后显示的日期
    lastDisplayedDate.value = null;
  }
};

function showArchive() {
  archiveVisible.value = true
}

watch(
  () => props.selectHistoryUser,
  (value) => {
    if (value) {
      getHistoryChatRecord();
      queryDiagnosisExist();
    }
  },
  { deep: true, immediate: true }
);
</script>
<style lang="scss" scoped></style>
