<template>
  <div class="side-nav">
    <!-- 顶部 Logo -->
    <div class="side-nav__header">

      <!-- 侧边栏Logo图片 -->
      <img src="@/assets/images/logo.png" alt="Offer派" class="side-nav__logo-img" />
    </div>

    <!-- 主导航 -->
    <nav class="side-nav__menu">
      <a
        v-for="item in mainMenus"
        :key="item.name"
        href="javascript:void(0)"
        class="side-nav__item"
        :class="{ 'side-nav__item--active': isActive(item.name) }"
        @click="handleNav(item)"
      >
        <img class="side-nav__item-icon" :src="item.iconImg" :alt="item.label" />
        <span class="side-nav__item-label">{{ item.label }}</span>
        <span v-if="item.badge" class="side-nav__badge">{{ item.badge }}</span>
      </a>
    </nav>

    <!-- 底部菜单 -->
    <div class="side-nav__footer">
      <div class="side-nav__item" v-for="item in footerMenus" :key="item.label" @click="item.action?.()">
        <img class="side-nav__item-icon" :src="item.iconImg" :alt="item.label" />
        <span class="side-nav__item-label">{{ item.label }}</span>
        <span v-if="item.badge" class="side-nav__badge">{{ item.badge }}</span>
      </div>
    </div>

    <!-- 消息通知弹窗 -->
    <Teleport to="body">
      <div v-if="showMessageDialog" class="side-nav__dialog-overlay" @click="showMessageDialog = false">
        <div class="side-nav__message-dialog" @click.stop>
          <!-- 弹窗头部 -->
          <div class="side-nav__message-dialog-header">
            <span>消息通知</span>
            <span class="side-nav__dialog-close" @click="showMessageDialog = false">✕</span>
          </div>
          <!-- 弹窗内容区：左列表 + 右详情 -->
          <div class="side-nav__message-dialog-content">
            <!-- 左侧消息列表 -->
            <div class="side-nav__message-list" @scroll="handleMessageListScroll">
              <div
                v-for="(msg, idx) in messageList"
                :key="msg.id"
                class="side-nav__message-list-item"
                :class="{ 'side-nav__message-list-item--active': selectedMessageIdx === idx }"
                @click="selectedMessageIdx = idx"
              >
                <span class="side-nav__message-list-title">{{ msg.title }}</span>
                <span v-if="!msg.read" class="side-nav__message-unread-dot"></span>
              </div>
              <!-- 加载中提示 -->
              <div v-if="messageLoading" class="side-nav__message-list-loading">加载中...</div>
              <!-- 无消息提示 -->
              <div v-if="!messageLoading && messageList.length === 0" class="side-nav__message-list-empty">暂无消息</div>
            </div>
            <!-- 右侧消息详情 -->
            <div class="side-nav__message-detail">
              <template v-if="currentMessage">
                <div class="side-nav__message-detail-title">{{ currentMessage.title }}</div>
                <div class="side-nav__message-detail-content">{{ currentMessage.content }}</div>
              </template>
              <div v-else class="side-nav__message-detail-empty">请选择一条消息查看</div>
            </div>
          </div>
        </div>
      </div>
    </Teleport>

    <!-- 反馈弹窗 -->
    <Teleport to="body">
      <div v-if="showFeedbackDialog" class="side-nav__dialog-overlay" @click="showFeedbackDialog = false">
        <div class="side-nav__dialog feedback-dialog" @click.stop>
          <div class="feedback-dialog__title">反馈与帮助</div>

          <div class="feedback-dialog__section">
            <div class="feedback-dialog__label">*你想向我们反馈什么问题？</div>
            <div class="feedback-dialog__options">
              <div
                v-for="(opt,index) in feedbackOptions"
                :key="index"
                class="feedback-dialog__option"
                :class="{ 'feedback-dialog__option--active': feedbackType === opt }"
                @click="feedbackType = opt, feedbackTypeIndex = index+1"
              >
                {{ opt }}
              </div>
            </div>
          </div>

          <div class="feedback-dialog__section">
            <div class="feedback-dialog__label">*能否提供更多细节？</div>
            <textarea
              v-model="feedbackDetail"
              class="feedback-dialog__textarea"
              placeholder="请描述你的使用体验或分享您的想法。描述越具体，我们越能更好地处理您的反馈。"
              rows="5"
            ></textarea>
          </div>

          <div class="feedback-dialog__actions">
            <button class="feedback-dialog__btn feedback-dialog__btn--cancel" @click="showFeedbackDialog = false">取消</button>
            <button class="feedback-dialog__btn feedback-dialog__btn--submit" @click="handleFeedbackSubmit">确认提交</button>
          </div>
        </div>
      </div>
    </Teleport>
    <!-- 设置弹窗 -->
    <SettingsDialog v-model="showSettingsDialog" :initial-tab="store.state.settingsTab" />
    <!-- 邀请注册送会员弹窗 -->
    <SettingsInviteDialog v-model="showShareDialog" />
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import SettingsDialog from '@/components/SettingsDialog.vue'
import { checkLogin } from '@/api/auth'
import { fetchMessageList, fetchUnreadCount, markMessageRead } from '@/api/message'
import {userFeedback} from '@/api/setting'
import type { MessageDto } from '@/api/message'
import navJobsIcon from '@/assets/images/nav/nav-jobs-icon.png'
import navResumeIcon from '@/assets/images/nav/nav-resume-icon.png'
import navProfileIcon from '@/assets/images/nav/nav-profile-icon.png'
import navAgentIcon from '@/assets/images/nav/nav-agent-icon.png'
import navMessageIcon from '@/assets/images/nav/nav-message-icon.png'
import navSettingIcon from '@/assets/images/nav/nav-setting-icon.png'
import navFeedbackIcon from '@/assets/images/nav/nav-feedback-icon.png'
import navShareIcon from '@/assets/images/nav/nav-share-icon.png'

const route = useRoute()
const router = useRouter()
const store = useStore()

interface MenuItem {
  name: string
  path: string
  iconImg: string
  label: string
  badge?: string
}

/**
 * 图标映射表
 * 后端 meta.icon 返回的是字符串 key，这里映射到实际的图片资源
 * 【新增图标时】在这里加一条即可
 */
const iconMap: Record<string, string> = {
  'nav-jobs-icon':    navJobsIcon,
  'nav-resume-icon':  navResumeIcon,
  'nav-profile-icon': navProfileIcon,
  'nav-agent-icon':   navAgentIcon,
  'nav-setting-icon': navSettingIcon,
}

/**
 * 静态菜单 — 不需要登录就能看到的导航项（比如"职位"）
 * 这些菜单始终显示，不依赖后端返回
 */
const staticMenus: MenuItem[] = [
  { name: 'Jobs', path: '/jobs', iconImg: navJobsIcon, label: '职位' },
]

/**
 * 动态菜单 — 从 store.state.dynamicMenus（后端返回的数据）转换而来
 * 登录后才会有数据，登出后自动清空
 * 过滤掉 position === 'footer' 的项（如"设置"），它们显示在底部区域
 */
const dynamicMenuItems = computed<MenuItem[]>(() => {
  return store.state.dynamicMenus
    .filter((item: any) => item.meta?.position !== 'footer')
    .map((item: any) => ({
      name: item.name,
      path: item.path,
      iconImg: iconMap[item.meta?.icon] || '',
      label: item.meta?.label || item.name,
      badge: item.meta?.badge,
    }))
})

/**
 * 最终渲染的主菜单 = 静态菜单 + 动态菜单
 */
const mainMenus = computed<MenuItem[]>(() => {
  return [...staticMenus, ...dynamicMenuItems.value]
})

const showShareDialog = ref(false)
const showMessageDialog = ref(false)
const showFeedbackDialog = ref(false)
const showSettingsDialog = computed({
  get: () => store.state.showSettings,
  set: (val: boolean) => store.commit('SET_SHOW_SETTINGS', val),
})
const feedbackType = ref('')
const feedbackTypeIndex = ref(0)
const feedbackDetail = ref('')
import { ElMessage } from 'element-plus'
import SettingsInviteDialog from "@/components/SettingsInviteDialog.vue";

// ==================== 站内信相关 ====================
/** 未读消息数量 */
const unreadCount = ref(0)
/** 消息列表数据 */
const messageList = ref<MessageDto[]>([])
/** 当前选中的消息索引 */
const selectedMessageIdx = ref(0)
/** 当前页码 */
const messagePageNum = ref(1)
/** 是否还有更多数据 */
const messageHasMore = ref(true)
/** 加载状态 */
const messageLoading = ref(false)

/** 当前选中的消息对象 */
const currentMessage = computed(() => {
  return messageList.value[selectedMessageIdx.value] || null
})

/**
 * 获取未读消息数量
 */
async function loadUnreadCount() {
  try {
    const res = await fetchUnreadCount()
    // 接口返回结构: { code, data: number }
    unreadCount.value = res.data ?? 0
  } catch (e) {
    console.error('获取未读消息数量失败', e)
  }
}

// 组件挂载时获取未读消息数量
onMounted(() => {
  loadUnreadCount()
})

/**
 * 加载消息列表（分页追加）
 */
async function loadMessages() {
  if (messageLoading.value || !messageHasMore.value) return
  messageLoading.value = true
  try {
    const res = await fetchMessageList({ pageNum: messagePageNum.value, pageSize: 20 })
    // 接口返回结构: { code, msg, data: { pageNum, pageSize, total, list } }
    const pageData = res.data
    if (pageData && pageData.list && pageData.list.length > 0) {
      messageList.value.push(...pageData.list)
      // 判断是否还有更多
      messageHasMore.value = messageList.value.length < pageData.total
      messagePageNum.value++
    } else {
      messageHasMore.value = false
    }
  } catch (e) {
    console.error('加载消息失败', e)
  } finally {
    messageLoading.value = false
  }
}

/**
 * 消息列表滚动到底部时加载下一页
 */
function handleMessageListScroll(e: Event) {
  const el = e.target as HTMLElement
  if (el.scrollTop + el.clientHeight >= el.scrollHeight - 10) {
    loadMessages()
  }
}

/**
 * 刷新消息列表数据（保持当前选中的消息不变）
 */
async function refreshMessageList(keepMessageId: number | string) {
  try {
    // 重新请求已加载的所有页数据
    const totalLoaded = messageList.value.length
    const res = await fetchMessageList({ pageNum: 1, pageSize: totalLoaded })
    const pageData = res.data
    if (pageData && pageData.list) {
      messageList.value = pageData.list
      // 根据之前选中的消息ID恢复选中状态
      const idx = messageList.value.findIndex((m: MessageDto) => String(m.id) === String(keepMessageId))
      selectedMessageIdx.value = idx >= 0 ? idx : 0
    }
  } catch (e) {
    console.error('刷新消息列表失败', e)
  }
}

/**
 * 上报消息已读：当右侧显示某条消息时，如果该消息未读则标记已读
 * 标记成功后刷新列表数据和未读数量
 */
async function handleMarkRead(msg: MessageDto) {
  if (msg.read) return
  try {
    await markMessageRead(msg.id)
    // 刷新列表状态，保持当前选中
    await refreshMessageList(msg.id)
    // 更新未读数量
    loadUnreadCount()
  } catch (e) {
    console.error('标记已读失败', e)
  }
}

/**
 * 监听当前选中消息变化，触发已读上报
 */
watch(currentMessage, (msg) => {
  if (msg && !msg.read) {
    handleMarkRead(msg)
  }
})

/**
 * 监听弹窗打开，重置并加载第一页消息
 */
watch(showMessageDialog, (val) => {
  if (val) {
    messageList.value = []
    messagePageNum.value = 1
    messageHasMore.value = true
    selectedMessageIdx.value = 0
    loadMessages()
  }
})

const feedbackOptions = ['Bug反馈', '功能建议', '使用体验', '订阅及会员权益相关问题', '其它']


/**
 * 提交反馈
 */
async function handleFeedbackSubmit() {

  console.log('反馈类型:', feedbackType.value,'类型index：', feedbackTypeIndex.value, '详情:', feedbackDetail.value)
  if(feedbackTypeIndex.value<1||feedbackDetail.value.trim()==''){
    ElMessage.warning('请选择问题并填写反馈内容')
  }else{

    //反馈接口
    await userFeedback({
      type: feedbackTypeIndex.value,
      content: feedbackDetail.value
    })
    ElMessage.success('提交成功')
    feedbackType.value = ''
    feedbackDetail.value = ''
    feedbackTypeIndex.value = 0
    showFeedbackDialog.value = false
  }


}

/**
 * 底部"设置"按钮 — 从动态菜单中取 position === 'footer' 的项
 * 未登录时使用默认图标和文字
 */
const settingsMenu = computed(() => {
  const item = store.state.dynamicMenus.find((m: any) => m.meta?.position === 'footer')
  if (item) {
    return {
      iconImg: iconMap[item.meta?.icon] || navSettingIcon,
      label: item.meta?.label || '设置',
      path: item.path,
    }
  }
  return { iconImg: navSettingIcon, label: '设置', path: '/settings' }
})

const footerMenus = computed(() => [
  { iconImg: navShareIcon, label: '分享送会员',  action: () => { showShareDialog.value = true } },
  { iconImg: navMessageIcon, label: '消息通知', badge: unreadCount.value > 0 ? 'NEW' : '', action: () => { showMessageDialog.value = true } },
  { iconImg: settingsMenu.value.iconImg, label: settingsMenu.value.label, action: () => { handleSettingsNav() } },
  { iconImg: navFeedbackIcon, label: '反馈', action: () => { showFeedbackDialog.value = true } },
])

/**
 * 设置弹窗：需要登录，通过 checkLogin 接口验证
 */
async function handleSettingsNav() {
  try {
    const res = await checkLogin()
    if (res.code === '0' && res.data === true) {
      store.commit('SET_AUTHENTICATED', true)
      store.commit('SET_SETTINGS_TAB', 'account')
      showSettingsDialog.value = true
    } else {
      store.commit('SET_AUTHENTICATED', false)
      store.dispatch('openLogin')
    }
  } catch {
    store.commit('SET_AUTHENTICATED', false)
    store.dispatch('openLogin')
  }
}

/**
 * 导航点击处理：
 * - 静态页面（Jobs）直接跳转
 * - 动态页面通过 checkLogin 接口验证，未登录则弹登录框
 */
const staticNames = staticMenus.map(m => m.name)

async function handleNav(item: MenuItem) {
  if (staticNames.includes(item.name)) {
    router.push(item.path)
    return
  }
  try {
    const res = await checkLogin()
    if (res.code === '0' && res.data === true) {
      store.commit('SET_AUTHENTICATED', true)
      router.push(item.path)
    } else {
      store.commit('SET_AUTHENTICATED', false)
      store.dispatch('openLogin', item.path)
    }
  } catch {
    store.commit('SET_AUTHENTICATED', false)
    store.dispatch('openLogin', item.path)
  }
}

function isActive(name: string) {
  return route.name === name
}
</script>
