<template>
  <el-drawer :model-value="visible" title="聊天记录" size="70%" style="--el-drawer-padding-primary: 0" @close="close()">
    <my-layout class="bg-[#f2f3f4]">
      <layout-main v-loading="loading" class="bg-white">
        <div class="p-36px">
          <empty-data v-if="messageList.length === 0" :title="loading ? '正在获取数据...':'暂无聊天记录'" padding="0 0 15px"
            text-top="10px"></empty-data>

          <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">
              {{formatTime(i.EventTime) }}
            </div>
            <div v-for="item in i.MsgBody">
              <system-message v-if="item.MsgType === 'TIMCustomElem'"
                :messageItem="transformCustomMessage(item.MsgContent)"></system-message>
              <div v-if="item.MsgType === 'TIMTextElem'">
                <message-me v-if="i.From_Account == doctorCode" :name="doctorName" :text="item.MsgContent.Text" />
                <message-other v-else :text="item.MsgContent.Text" :name="patientName" />
              </div>
            </div>
          </template>
        </div>
      </layout-main>

      <layout-item>
        <div class="text-center py-12px bg-white relative z-1" common-shadow--r>
          <el-button plain class="w-100px" type="primary" @click="close()">关闭</el-button>
        </div>
      </layout-item>
    </my-layout>
  </el-drawer>

</template>
<script setup>
import { computed, nextTick, ref, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from "dayjs";
import { getChatRecord } from "@/api/hlw";
import EmptyData from "@/components/empty-data.vue";

import MyLayout, { LayoutMain, LayoutItem } from "@/components/layout";
import systemMessage from './system-message.vue'
import messageMe from "./message-me.vue";
import messageOther from "./message-other.vue";
const emits = defineEmits(["close"]);
const props = defineProps({
  orderId: {
    type: String,
    default: '',
  },
  doctorCode: {
    type: String,
    default: () => sessionStorage.getItem("doctorNo"),
  },
  doctorName: {
    type: String,
    default: '',
  },
  patientName: {
    type: String,
    default: '',
  },
  visible: {
    type: Boolean,
    default: false,
  },
});
const messageList = ref([]);
const lastDisplayedDate = ref(null);
const loading = ref(false)
const doctorCode = computed(() => props.doctorCode || sessionStorage.getItem("doctorNo"));

// 过滤掉没有 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 () => {
  messageList.value = [];
  loading.value = true;
  const { data, success } = await getChatRecord({
    doctorNo: props.doctorCode,
    orderId: props.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 || [];
    }
    // messageList.value.sort((a,b)=> a.MsgTime - b.MsgTime);

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

};

const formatTime = (time) => {
  const now = dayjs();
  const messageTime = dayjs(time);

  if (now.isSame(messageTime, "day")) {
    return messageTime.format("HH:mm:ss");
  } else if (now.isSame(messageTime, "year")) {
    return messageTime.format("MM-DD HH:mm:ss");
  } else {
    return messageTime.format("YYYY-MM-DD HH:mm:ss");
  }
};

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,
    },
  };
}

function close() {
  emits("close");
}

watch(() => props.visible, n => {
  if (n) {
    getHistoryChatRecord();
  }
})
</script>
<style lang="scss" scoped></style>
