<template>
  <view class="notice-list-page">

    <!-- 列表区域 -->
    <scroll-view 
      class="notice-scroll" 
      scroll-y
      @scrolltolower="handleScrollToLower"
    >
      <view class="notice-container">
        <!-- 公告卡片列表 -->
        <view 
          class="notice-card" 
          v-for="notice in notices" 
          :key="notice.id"
          @click="goToNoticeDetail(notice)"
        >
          <!-- 标题和标签行 -->
          <view class="notice-header">
            <view class="notice-title-row">
              <text class="notice-title" :class="{ 'pinned': notice.top }">
                {{ notice.title }}
              </text>
              <view class="notice-tags">
                <view v-if="notice.top" class="notice-tag tag-pinned">置顶</view>
                <view v-if="notice.level === '1'" class="notice-tag tag-general">一般</view>
                <view v-if="notice.level === '2'" class="notice-tag tag-important">重要</view>
                <view v-if="notice.level === '3'" class="notice-tag tag-urgent">紧急</view>
              </view>
            </view>
          </view>
          
          <!-- 内容预览 -->
          <view class="notice-content">
            <text class="notice-content-text">{{ truncateText(notice.content, 50) }}</text>
          </view>
          
          <!-- 元信息 -->
          <view class="notice-meta">
            <view class="meta-item">
              <text class="meta-icon">👤</text>
              <text class="meta-text">{{ notice.userName || '未知' }}</text>
            </view>
            <view class="meta-item">
              <text class="meta-icon">🕐</text>
              <text class="meta-text">{{ formatTime(notice.createTime) }}</text>
            </view>
          </view>
          
          <!-- 接收信息 -->
          <view class="notice-receive" v-if="notice.receiveUserList?.length > 0 || notice.receiveDeptList?.length > 0">
            <view class="receive-item" v-if="notice.receiveUserList?.length > 0">
              <text class="receive-label">接收用户:</text>
              <view class="receive-users">
                <view 
                  class="user-avatar" 
                  v-for="(user, index) in notice.receiveUserList.slice(0, 3)" 
                  :key="user.userId"
                >
                  <image 
                    v-if="user.avatar" 
                    :src="user.avatar" 
                    class="avatar-img"
                    mode="aspectFill"
                  />
                  <text v-else class="avatar-text">{{ user.nickName?.charAt(0) || '?' }}</text>
                </view>
                <text v-if="notice.receiveUserList.length > 3" class="more-text">
                  等{{ notice.receiveUserList.length }}项
                </text>
              </view>
            </view>
            <view class="receive-item" v-if="notice.receiveDeptList?.length > 0">
              <text class="receive-label">接收部门:</text>
              <view class="receive-depts">
                <view 
                  class="dept-tag" 
                  v-for="dept in notice.receiveDeptList" 
                  :key="dept.deptId"
                >
                  {{ dept.deptName }}
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 加载状态 -->
        <view class="empty-state" v-if="loading">
          <text class="empty-text">加载中...</text>
        </view>

        <!-- 空状态 -->
        <view class="empty-state" v-else-if="isEmpty">
          <text class="empty-text">暂无公告</text>
        </view>

        <!-- 加载更多提示 -->
        <view class="load-more-tip" v-if="!isEmpty && !loading && !noMore">
          <text class="load-more-text">上拉加载更多</text>
        </view>
        <view class="load-more-tip" v-if="!isEmpty && noMore">
          <text class="load-more-text">没有更多数据了</text>
        </view>
      </view>
    </scroll-view>
    
    <!-- 新增公告悬浮球 -->
    <FabPlus v-if="isAdmin" @click="handleCreate" />
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { getNoticeList, deleteNotice } from '@/api';
import { usePagination } from '@/composables';
import { truncateText } from '@/utils/textSolve/truncateText';
import { useUserStore } from '@/store/user';
import FabPlus from '@/components/FabPlus.vue';

// 搜索表单
const searchForm = ref({
  title: '',
  userName: '',
  level: '',
  top: ''
});

// 重要程度选项
const levelOptions = [
  { label: '全部', value: '' },
  { label: '一般', value: '1' },
  { label: '重要', value: '2' },
  { label: '紧急', value: '3' }
];

const showLevelPicker = ref(false);

// 获取重要程度文本
const getLevelText = (level) => {
  const option = levelOptions.find(opt => opt.value === level);
  return option ? option.label : '';
};

// 使用分页组合式函数
const {
  list,
  loading,
  noMore,
  isEmpty,
  getList,
  loadMore,
  updateParams,
  reset
} = usePagination({
  fetchData: async (params) => {
    // 构建请求参数
    const requestParams = {
      ...params,
      orderByColumn: 'top',
      isAsc: 'descending'
    };
    
    // 添加搜索和筛选参数
    if (searchForm.value.title) {
      requestParams.title = searchForm.value.title;
    }
    if (searchForm.value.userName) {
      requestParams.userName = searchForm.value.userName;
    }
    if (searchForm.value.level) {
      requestParams.level = searchForm.value.level;
    }
    if (searchForm.value.top !== '') {
      requestParams.top = searchForm.value.top;
    }
    
    const res = await getNoticeList(requestParams);
    return res;
  },
  mode: 'loadMore',
  pageSize: 20,
  defaultParams: {}
});

// 公告列表
const notices = computed(() => list.value);

// 用户角色判断
const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);
const isAdmin = computed(() => {
  if (!userInfo.value || !Array.isArray(userInfo.value.roles)) return false;
  return userInfo.value.roles.some((role) => ['admin', 'sys_admin'].includes(role));
});

// 选择重要程度
const selectLevel = (value) => {
  searchForm.value.level = value;
};

// 搜索
const handleSearch = () => {
  reset();
  getList();
};

// 重置
const handleReset = () => {
  searchForm.value = {
    title: '',
    userName: '',
    level: '',
    top: ''
  };
  reset();
  getList();
};

// 处理滚动到底部
const handleScrollToLower = () => {
  if (!noMore.value && !loading.value) {
    loadMore();
  }
};

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return '';
  return timeStr;
};

// 跳转到公告详情
const goToNoticeDetail = (notice) => {
  uni.navigateTo({
    url: `/pages/notice/detail/index?id=${notice.id}`
  });
};

// 管理员操作占位
const showFeaturePending = (action) => {
  uni.showToast({
    title: `${action}功能待接入`,
    icon: 'none'
  });
};

const handleCreate = () => {
  uni.navigateTo({
    url: '/pages/notice/create/index'
  });
};

// 管理员视图接收对象描述
const formatReceiveInfo = (notice) => {
  const userCount = Array.isArray(notice.receiveUserList) ? notice.receiveUserList.length : 0;
  const deptCount = Array.isArray(notice.receiveDeptList) ? notice.receiveDeptList.length : 0;

  if (!userCount && !deptCount) {
    return '全部人员';
  }

  const info = [];
  if (userCount) info.push(`用户${userCount}人`);
  if (deptCount) info.push(`部门${deptCount}个`);
  return info.join(' / ');
};

const handleNoticeUpdated = () => {
  reset();
  getList();
};

onMounted(() => {
  getList();
  uni.$on('notice:updated', handleNoticeUpdated);
});

onBeforeUnmount(() => {
  uni.$off('notice:updated', handleNoticeUpdated);
});
</script>

<style lang="scss" scoped>
.notice-list-page {
  width: 100%;
  height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.search-filter-section {
  position: fixed;
  bottom: 0px;
  background: #fff;
  padding: 6px;
  margin-bottom: 8px;
}

.search-row {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
}

.search-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.search-label {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.filter-row {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 12px;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.filter-label {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.picker-trigger {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #f5f5f5;
  border-radius: 8px;
  padding: 8px 12px;

}

.picker-text {
  font-size: 14px;
  color: #333;
  
  &.placeholder {
    color: #999;
  }
}

.picker-arrow {
  font-size: 12px;
  color: #999;
}

.radio-group {
  display: flex;
  gap: 12px;
}

.radio-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border-radius: 8px;

  border: 2px solid transparent;
  
  &.active {
    background: #e3f2fd;
    border-color: #2885ff;
  }
}

.radio-text {
  padding:4px;
  font-size: 14px;
  color: #333;
}

.radio-item.active .radio-text {
  color: #2885ff;
  font-weight: 500;
}


.notice-scroll {
  flex: 1;
  width: 100%;
}

.notice-container {
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}


.notice-card {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.notice-card:active {
  transform: scale(0.98);
  opacity: 0.9;
}


.notice-header {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.notice-title-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.notice-title {
  flex: 1;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  
  &.pinned {
    color: #f56c6c;
  }
}

.notice-tags {
  display: flex;
  align-items: center;
  gap: 6px;
  flex-shrink: 0;
}

.notice-tag {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: #fff;
  white-space: nowrap;
}

.tag-pinned {
  background-color: #f56c6c;
}

.tag-general {
  background-color: #4caf50;
}

.tag-important {
  background-color: #ff9800;
}

.tag-urgent {
  background-color: #f56c6c;
}

.notice-content {
  margin-top: 4px;
}

.notice-content-text {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
}

.notice-meta {
  display: flex;
  align-items: center;
  gap: 16px;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.meta-icon {
  font-size: 14px;
}

.meta-text {
  font-size: 12px;
  color: #666;
}

.notice-receive {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

.receive-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.receive-label {
  font-size: 12px;
  color: #999;
  flex-shrink: 0;
}

.receive-users {
  display: flex;
  align-items: center;
  gap: 6px;
  flex: 1;
}

.user-avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: #e3f2fd;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  flex-shrink: 0;
}

.avatar-img {
  width: 100%;
  height: 100%;
}

.avatar-text {
  font-size: 12px;
  color: #2885ff;
}

.more-text {
  font-size: 12px;
  color: #999;
  margin-left: 4px;
}

.receive-depts {
  display: flex;
  align-items: center;
  gap: 6px;
  flex-wrap: wrap;
  flex: 1;
}

.dept-tag {
  padding: 2px 8px;
  border-radius: 12px;
  background: #f0f0f0;
  font-size: 12px;
  color: #666;
}

.empty-state {
  padding: 60px 20px;
  text-align: center;
}

.empty-text {
  font-size: 14px;
  color: #999;
}

.load-more-tip {
  padding: 20px;
  text-align: center;
}

.load-more-text {
  font-size: 12px;
  color: #999;
}

// 选择器弹窗样式
.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  align-items: flex-end;
}

.modal-content {
  width: 100%;
  background: #fff;
  border-radius: 16px 16px 0 0;
  padding: 20px;
  max-height: 60vh;
  animation: slideUp 0.3s ease;
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.modal-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  text-align: center;
  margin-bottom: 20px;
}

.picker-options {
  display: flex;
  flex-direction: column;
  gap: 0;
}

.picker-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  transition: background 0.2s;
  
  &:active {
    background: #f5f5f5;
  }
  
  &.active {
    background: #e3f2fd;
  }
}

.picker-option text:first-child {
  font-size: 16px;
  color: #333;
}

.picker-option.active text:first-child {
  color: #2885ff;
  font-weight: 500;
}

.check {
  font-size: 18px;
  color: #2885ff;
}

.modal-buttons {
  display: flex;
  gap: 12px;
  margin-top: 20px;
  padding-top: 20px;

}

.modal-btn {
  flex: 1;
  padding: 12px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  background: #f5f5f5;
  color: #333;
  
  &.primary {
    background: #2885ff;
    color: #fff;
  }
}
</style>

