<script setup lang="ts">
import "moment/dist/locale/th";
import moment from "moment";
import { useSupportStore } from "@/modules/00_support/store/Main";

const store = useSupportStore();

function dateChat(timestamp: string) {
  const parsedTimestamp = moment(timestamp);
  const diff = moment().diff(parsedTimestamp);

  if (diff < 86400000) {
    const formattedDate = parsedTimestamp.format("HH:mm") + " น.";
    return formattedDate;
  } else {
    const beYear = parsedTimestamp.year() + 543;
    const formattedDate = parsedTimestamp.clone().year(beYear).format("DD MMM");
    return formattedDate;
  }
}
</script>

<template>
  <div class="col-grow q-pt-md q-pb-sm">
    <div v-for="(item, index) in store.message?.result.message">
      <q-item-label>
        <q-chat-message
          ref="myElement"
          :key="index"
          :id="item.id"
          :text="[item.content]"
          :bg-color="item.fromUserId === store.userId ? 'teal' : 'white'"
          :text-color="item.fromUserId === store.userId ? 'white' : 'black'"
          :sent="item.fromUserId === store.userId"
        >
          <template v-slot:stamp>
            <span> {{ dateChat(item.createdAt) }} </span>
          </template>
          <template v-slot:avatar>
            <q-img
              v-if="item.fromUserId === store.userId"
              src="@/assets/avatar_user.jpg"
              class="q-ml-sm"
              spinner-color="white"
              style="height: 42px; max-width: 42px; border-radius: 50%"
            />

            <div
              v-else
              class="q-mr-sm"
              style="border-radius: 50%; border: 1px solid teal"
            >
              <q-avatar color="teal-1" text-color="white" size="42px">
                <q-icon :name="store.icon" size="24px" color="teal" />
              </q-avatar>
            </div>
          </template>
        </q-chat-message>
      </q-item-label>

      <q-item-label
        v-if="item.fromUserId === store.userId"
        class="flex"
        caption
      >
        <q-space />
        <div
          v-if="
            store.messageStatus?.result.some((v) => {
              return (
                new Date(v.lastAccessDate).getTime() >=
                  new Date(item.createdAt).getTime() &&
                v.fromUserId !== store.userId &&
                index + 1 === store.message?.result.message.length
              );
            })
          "
          class="q-mr-xl"
        >
          <q-icon name="mdi-check-all" size="xs" />
          <span class="text-caption q-ml-sm">อ่านแล้ว</span>
        </div>
      </q-item-label>
    </div>
  </div>
</template>
