<template>
  <el-dialog
    v-model="dialogVisible"
    title="系统公告"
    width="800px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="true"
    class="notice-popup-dialog"
    @close="handleClose"
  >
    <div class="notice-popup-content">
      <!-- 公告列表 -->
      <div class="notice-list">
        <el-scrollbar max-height="500px">
          <div
            v-for="notice in noticeList"
            :key="notice.noticeId"
            class="notice-item"
            :class="{ 'unread': !notice.isRead, 'active': activeNoticeId === notice.noticeId }"
            @click="handleSelectNotice(notice)"
          >
            <div class="notice-item-left">
              <el-icon
                class="notice-type-icon"
                :class="getNoticeTypeClass(notice.noticeType)"
              >
                <component :is="getNoticeTypeIcon(notice.noticeType)" />
              </el-icon>
              <div class="notice-item-content">
                <div class="notice-title">
                  <el-tag 
                    :class="getPriorityClass(notice.priority)" 
                    size="small" 
                    effect="plain"
                  >
                    {{ getPriorityText(notice.priority) }}
                  </el-tag>
                  <span class="notice-title-text">{{ notice.noticeTitle }}</span>
                  <el-tag
                    v-if="!notice.isRead"
                    type="danger"
                    size="small"
                    effect="dark"
                  >
                    未读
                  </el-tag>
                </div>
                <div class="notice-meta">
                  <span class="notice-date">{{ formatDate(notice.createTime) }}</span>
                  <span class="notice-creator">{{ notice.createBy }}</span>
                </div>
              </div>
            </div>
            <el-icon
              v-if="activeNoticeId === notice.noticeId"
              class="arrow-icon"
            >
              <ArrowRight />
            </el-icon>
          </div>
        </el-scrollbar>
      </div>

      <!-- 公告详情 -->
      <div
        v-if="activeNotice"
        class="notice-detail"
      >
        <div class="notice-detail-header">
          <h3 class="notice-detail-title">
            {{ activeNotice.noticeTitle }}
          </h3>
          <div class="notice-detail-meta">
            <el-tag
              :type="getPriorityTagType(activeNotice.priority)"
              size="small"
              effect="dark"
            >
              {{ getPriorityText(activeNotice.priority) }}
            </el-tag>
            <el-tag
              :type="getNoticeTypeTagType(activeNotice.noticeType)"
              size="small"
            >
              {{ getNoticeTypeText(activeNotice.noticeType) }}
            </el-tag>
            <span class="notice-detail-date">{{ formatDate(activeNotice.createTime) }}</span>
          </div>
        </div>
        <el-divider />
        <div
          class="notice-detail-body"
          v-html="activeNotice.noticeContent"
        />
      </div>

      <!-- 空状态 -->
      <div
        v-else
        class="empty-state"
      >
        <el-empty
          description="暂无公告"
          :image-size="120"
        />
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="unreadCount > 0"
          type="info"
          @click="markAllAsRead"
        >
          全部标记为已读
        </el-button>
        <el-button
          type="primary"
          @click="handleClose"
        >
          {{ hasUnread ? '稍后再看' : '知道了' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { getUserNotices, markAsRead, markAllAsRead as markAllReadApi } from '@/api/system/notice'
import { Bell, Warning, InfoFilled, ArrowRight, CircleCheck } from '@element-plus/icons-vue'

// 监听全局触发公告弹窗事件
onMounted(() => {
  window.addEventListener('trigger-notice-popup', handleTriggerNoticePopup)
})

onUnmounted(() => {
  window.removeEventListener('trigger-notice-popup', handleTriggerNoticePopup)
})

function handleTriggerNoticePopup(event) {
  // 显示公告弹窗
  dialogVisible.value = true
  // 如果没有加载过公告，则加载
  if (noticeList.value.length === 0) {
    loadNotices()
  }
}

const dialogVisible = ref(false)
const noticeList = ref([])
const activeNoticeId = ref(null)
const readNoticeIds = ref([])

const activeNotice = computed(() => {
  return noticeList.value.find(n => n.noticeId === activeNoticeId.value)
})

const unreadCount = computed(() => {
  return noticeList.value.filter(n => !n.isRead).length
})

const hasUnread = computed(() => {
  return unreadCount.value > 0
})

// 获取公告类型图标
// noticeType: 1=通知, 2=公告
const getNoticeTypeIcon = (type) => {
  const iconMap = {
    '1': Bell,         // 通知
    '2': InfoFilled    // 公告
  }
  return iconMap[type] || InfoFilled
}

// 获取优先级样式类
const getPriorityClass = (priority) => {
  const classMap = {
    '1': 'priority-high',
    '2': 'priority-medium',
    '3': 'priority-low'
  }
  return classMap[priority] || 'priority-medium'
}

// 获取优先级文本
const getPriorityText = (priority) => {
  const textMap = {
    '1': '高',
    '2': '中',
    '3': '低'
  }
  return textMap[priority] || '中'
}

// 获取优先级标签类型
const getPriorityTagType = (priority) => {
  const typeMap = {
    '1': 'danger',   // 高优先级 - 红色
    '2': 'warning',  // 中优先级 - 橙色
    '3': 'info'      // 低优先级 - 灰色
  }
  return typeMap[priority] || 'info'
}

// 获取优先级图标
const getPriorityIcon = (priority) => {
  const iconMap = {
    '1': Warning,     // 高优先级
    '2': InfoFilled,  // 中优先级
    '3': CircleCheck  // 低优先级
  }
  return iconMap[priority] || InfoFilled
}

// 获取公告类型样式类
// noticeType: 1=通知, 2=公告
const getNoticeTypeClass = (type) => {
  const classMap = {
    '1': 'type-notice',
    '2': 'type-announcement'
  }
  return classMap[type] || 'type-announcement'
}

// 获取公告类型标签类型
// noticeType: 1=通知, 2=公告
const getNoticeTypeTagType = (type) => {
  const typeMap = {
    '1': 'primary',
    '2': 'success'
  }
  return typeMap[type] || 'info'
}

// 获取公告类型文本
// noticeType: 1=通知, 2=公告
const getNoticeTypeText = (type) => {
  const textMap = {
    '1': '通知',
    '2': '公告'
  }
  return textMap[type] || '公告'
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const now = new Date()
  const diff = now - date

  if (diff < 60000) { // 小于1分钟
    return '刚刚'
  } else if (diff < 3600000) { // 小于1小时
    return Math.floor(diff / 60000) + '分钟前'
  } else if (diff < 86400000) { // 小于1天
    return Math.floor(diff / 3600000) + '小时前'
  } else if (diff < 604800000) { // 小于1周
    return Math.floor(diff / 86400000) + '天前'
  } else {
    return dateStr.substring(0, 10)
  }
}

// 格式化完整时间
const formatFullDate = (dateStr) => {
  if (!dateStr) return ''
  return dateStr.replace('T', ' ').substring(0, 19)
}

// 加载公告列表
const loadNotices = async () => {
  try {
    const res = await getUserNotices()
    if (res.code === 200) {
      noticeList.value = (res.data || []).sort((a, b) => {
        return new Date(b.createTime) - new Date(a.createTime)
      })
      // 设置第一个未读公告为激活状态，如果没有未读则设置第一个
      const firstUnread = noticeList.value.find(n => !n.isRead)
      if (firstUnread) {
        activeNoticeId.value = firstUnread.noticeId
      } else if (noticeList.value.length > 0) {
        activeNoticeId.value = noticeList.value[0].noticeId
      }
      // 检查是否有未读公告，有未读则自动弹出
      const hasUnreadNotices = noticeList.value.some(n => !n.isRead)
      if (hasUnreadNotices) {
        // 延迟弹出，避免与登录加载冲突
        setTimeout(() => {
          dialogVisible.value = true
        }, 500)
      }
    }
  } catch (error) {
    console.error('加载公告失败:', error)
  }
}

// 选择公告
const handleSelectNotice = async (notice) => {
  activeNoticeId.value = notice.noticeId
  // 标记为已读
  if (!notice.isRead) {
    try {
      await markAsRead(notice.noticeId)
      notice.isRead = true
    } catch (error) {
      console.error('标记已读失败:', error)
    }
  }
}

// 全部标记为已读
const markAllAsRead = async () => {
  try {
    const unreadIds = noticeList.value.filter(n => !n.isRead).map(n => n.noticeId)
    if (unreadIds.length > 0) {
      await markAllReadApi(unreadIds)
      noticeList.value.forEach(n => {
        if (unreadIds.includes(n.noticeId)) {
          n.isRead = true
        }
      })
    }
  } catch (error) {
    console.error('全部标记已读失败:', error)
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 初始化
onMounted(() => {
  // 延迟加载，避免影响页面渲染
  setTimeout(() => {
    loadNotices()
  }, 1000)
})

// 暴露方法供外部调用
defineExpose({
  showNotice: () => {
    dialogVisible.value = true
    if (noticeList.value.length === 0) {
      loadNotices()
    }
  }
})
</script>

<style lang="scss" scoped>
.notice-popup-dialog {
  :deep(.el-dialog__header) {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 20px;
    
    .el-dialog__title {
      font-size: 20px;
      font-weight: 600;
    }
    
    .el-dialog__headerbtn .el-dialog__close {
      color: white;
      font-size: 20px;
      
      &:hover {
        color: rgba(255, 255, 255, 0.8);
      }
    }
  }
  
  :deep(.el-dialog__body) {
    padding: 0;
  }
  
  :deep(.el-dialog__footer) {
    padding: 15px 20px;
    background: #f5f7fa;
    border-top: 1px solid #e4e7ed;
  }
}

.notice-popup-content {
  display: flex;
  min-height: 500px;
  max-height: 600px;
  overflow: hidden;
}

.notice-list {
  width: 25%;
  min-width: 200px;
  border-right: 1px solid #e4e7ed;
  background: #fafafa;
  
  .notice-item {
    padding: 16px;
    cursor: pointer;
    border-bottom: 1px solid #e4e7ed;
    transition: all 0.3s;
    position: relative;
    
    &:hover {
      background: #f0f2f5;
    }
    
    &.active {
      background: #e6f7ff;
      border-left: 3px solid #1890ff;
    }
    
    &.unread {
      background: #fffbe6;
      
      &:hover {
        background: #fff7b8;
      }
      
      &.active {
        background: #fff7b8;
        border-left: 3px solid #faad14;
      }
    }
  }
  
  .notice-item-left {
    display: flex;
    gap: 12px;
    
    .notice-type-icon {
      flex-shrink: 0;
      width: 40px;
      height: 40px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 20px;
      
      &.type-notice {
        background: #e6f7ff;
        color: #1890ff;
      }

      &.type-announcement {
        background: #f6ffed;
        color: #52c41a;
      }
    }
    
    .notice-item-content {
      flex: 1;
      min-width: 0;
      
      .notice-title {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 6px;
        
        .notice-title-text {
          font-size: 14px;
          font-weight: 500;
          color: #333;
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
      
      // 优先级标签样式
      .priority-high {
        color: #f56c6c;
        border-color: #f56c6c;
        background: #fef0f0;
      }
      
      .priority-medium {
        color: #e6a23c;
        border-color: #e6a23c;
        background: #fdf6ec;
      }
      
      .priority-low {
        color: #909399;
        border-color: #909399;
        background: #f4f4f5;
      }
      
      .notice-meta {
        display: flex;
        gap: 12px;
        font-size: 12px;
        color: #999;
        
        .notice-date,
        .notice-creator {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
  }
  
  .arrow-icon {
    position: absolute;
    right: 16px;
    top: 50%;
    transform: translateY(-50%);
    color: #1890ff;
    font-size: 16px;
  }
}

.notice-detail {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  
  .notice-detail-header {
    padding: 20px;
    
    .notice-detail-title {
      margin: 0 0 12px 0;
      font-size: 18px;
      font-weight: 600;
      color: #333;
      line-height: 1.5;
    }
    
    .notice-detail-meta {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .notice-detail-date {
        font-size: 13px;
        color: #999;
      }
    }
  }
  
  .notice-detail-body {
    flex: 1;
    padding: 0 20px 20px 20px;
    overflow-y: auto;
    font-size: 14px;
    line-height: 1.8;
    color: #666;
    
    :deep(img) {
      max-width: 100%;
      height: auto;
      border-radius: 4px;
      margin: 10px 0;
    }
    
    :deep(p) {
      margin: 10px 0;
    }
  }
}

.empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

// 优先级样式
.priority-high {
  background: #fff1f0;
  color: #ff4d4f;
  border-color: #ffccc7;
  
  &:hover {
    background: #ffccc7;
    color: #fff;
  }
}

.priority-medium {
  background: #fff7e6;
  color: #faad14;
  border-color: #ffe58f;
  
  &:hover {
    background: #ffe58f;
    color: #fff;
  }
}

.priority-low {
  background: #f0f2f5;
  color: #909399;
  border-color: #dcdfe6;
  
  &:hover {
    background: #dcdfe6;
    color: #fff;
  }
}
</style>
