<template>
  <el-dialog
    v-model="visible"
    title="消息详情"
    width="600px"
    destroy-on-close
    align-center
    class="reminder-detail-dialog"
  >
    <div class="reminder-detail-container" v-loading="loading">
      <h3 class="reminder-title">{{ reminder.title }}</h3>
      <div class="reminder-meta">
        <span class="meta-item">
          <el-icon><User /></el-icon>
          发送者：{{ getSenderName(reminder) }}
        </span>
        <span class="meta-item">
          <el-icon><Calendar /></el-icon>
          时间：{{ formatTime(reminder.create_time) }}
        </span>
      </div>
      <el-divider />
      <div class="reminder-content">{{ reminder.content }}</div>
    </div>
    <template #footer>
      <el-button @click="visible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { User, Calendar } from "@element-plus/icons-vue";
import { readSiteReminder } from "@/api/sitereminder";

const props = defineProps({
  modelValue: Boolean,
  reminder: {
    type: Object,
    default: () => ({})
  },
  viewOnly: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(["update:modelValue", "read-success"]);

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit("update:modelValue", val)
});

const loading = ref(false);

const getSenderName = (item: any) => {
  if (!item.sender_type) return "-";
  if (item.sender_type === "system") return "系统";
  if (item.sender_type === "platform") return `平台管理员 (ID: ${item.sender_id})`;
  if (item.sender_type === "tenant") return `租户用户 (ID: ${item.sender_id})`;
  return item.sender_type;
};

const formatTime = (timeStr: any) => {
  if (!timeStr) return "-";
  const date = new Date(timeStr);
  return date.toLocaleString();
};

watch(() => props.modelValue, async (val) => {
  if (val && props.reminder && !props.viewOnly && props.reminder.is_read === 0) {
    loading.value = true;
    try {
      const res = await readSiteReminder(props.reminder.id);
      if (res.code === 200) {
        emit("read-success", props.reminder.id);
      }
    } catch (err) {
      console.error(err);
    } finally {
      loading.value = false;
    }
  }
});
</script>

<style scoped>
.reminder-detail-container {
  padding: 10px 20px;
}
.reminder-title {
  font-size: 20px;
  font-weight: 600;
  margin: 0 0 12px 0;
  color: var(--el-text-color-primary);
  line-height: 1.4;
}
.reminder-meta {
  display: flex;
  gap: 20px;
  color: var(--el-text-color-secondary);
  font-size: 13px;
}
.meta-item {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}
.reminder-content {
  font-size: 15px;
  line-height: 1.6;
  color: var(--el-text-color-regular);
  white-space: pre-wrap;
  word-break: break-all;
  min-height: 120px;
}
</style>
