<route lang="json5" type="page">
{
  layout: 'default',
  needLogin: true,
  style: {
    navigationStyle: 'custom',
  },
}
</route>

<script lang="ts" setup>
// eslint-disable-next-line unused-imports/no-unused-imports
import { onPageScroll, onReachBottom } from '@dcloudio/uni-app'
import useZPaging from 'z-paging/components/z-paging/js/hooks/useZPaging.js'
// 必须导入需要用到的页面生命周期（即使在当前页面上没有直接使用到）

import { noticeDel, noticeList, noticeRead, readAllNotice } from '@/api/common'
import { t } from '@/locale'
import i18n from '@/locale/index'
import { goBack, toPage } from '@/utils/page'
import { toast } from '@/utils/toast'

defineOptions({
  name: 'Notifications', // 通知
})

// 获取屏幕边界到安全区域距离
const systemInfo = uni.getSystemInfoSync()
const safeAreaInsets = systemInfo.safeAreaInsets

// z-paging
const paging = ref(null)
// 类似mixins，如果是页面滚动务必要写这一行，并传入当前ref绑定的paging，注意此处是paging，而非paging.value
useZPaging(paging)

const tab = ref<string>('ALL')
const tabs = computed(() => {
  const _locale = i18n.global.locale
  void _locale
  return [
    { title: t('notifications.tabs.all'), value: 'ALL' },
    { title: t('notifications.tabs.orders'), value: 'ORDER' },
    { title: t('notifications.tabs.revenue'), value: 'REWARD' },
    { title: t('notifications.tabs.account'), value: 'MONEY' },
    { title: t('notifications.tabs.promos'), value: 'OTHER' },
  ]
})

const typeMap = {
  order: ['ORDER_GROUP_BUY_PAYMENT_SUCCESS', 'ORDER_GROUP_BUY_SUCCESS_WIN', 'ORDER_GROUP_BUY_SUCCESS_LOSE', 'ORDER_PROVIDE_SHIPPING_ADDRESS', 'ORDER_GROUP_BUY_FAIL', 'ORDER_SHIPPED_SUCCESS'],
  income: ['REWARD_REFER_FRIENDS', 'REWARD_GROUP_BUY', 'REWARD_OPEN_GROUP_BUY', 'REWARD_DIRECT_REFERRAL', 'REWARD_CHECKIN', 'REWARD_FIRST_COMMISSION', 'REWARD_SECONDARY_COMMISSION', 'ORDER_RECYCLE_REWARD'],
  wallet: ['MONEY_RECHARGE_SUCCESS', 'MONEY_WITHDRAWAL_ACCOUNT_SUCCESS', 'MONEY_WITHDRAWAL_WALLET_SUCCESS', 'MONEY_WITHDRAWAL_FAIL'],
  other: ['OTHER'],
}

const contentTypeMap = {
  ORDER_GROUP_BUY_PAYMENT_SUCCESS: {
    titleKey: 'notifications.order.paymentSuccess.title',
    contentKey: 'notifications.order.paymentSuccess.content',
    link: '/pages/myOrders/orderDetail',
  },
  ORDER_GROUP_BUY_SUCCESS_WIN: {
    titleKey: 'notifications.order.groupBuyWin.title',
    contentKey: 'notifications.order.groupBuyWin.content',
    link: '/pages/myOrders/orderDetail',
  },
  ORDER_GROUP_BUY_SUCCESS_LOSE: {
    titleKey: 'notifications.order.groupBuyLose.title',
    contentKey: 'notifications.order.groupBuyLose.content',
    link: '/pages/myOrders/orderDetail',
  },
  ORDER_PROVIDE_SHIPPING_ADDRESS: {
    titleKey: 'notifications.order.provideAddress.title',
    contentKey: 'notifications.order.provideAddress.content',
    link: '/pages/myOrders/orderDetail',
  },
  ORDER_GROUP_BUY_FAIL: {
    titleKey: 'notifications.order.groupBuyFail.title',
    contentKey: 'notifications.order.groupBuyFail.content',
    link: '/pages/myOrders/orderDetail',
  },
  ORDER_SHIPPED_SUCCESS: {
    titleKey: 'notifications.order.shipped.title',
    contentKey: 'notifications.order.shipped.content',
    link: '/pages/myOrders/orderDetail',
  },
  ORDER_RECYCLE_REWARD: {
    titleKey: 'notifications.order.recycleReward.title',
    contentKey: 'notifications.order.recycleReward.content',
    link: '/pages/income/income',
  },
  REWARD_REFER_FRIENDS: {
    titleKey: 'notifications.reward.referFriends.title',
    contentKey: 'notifications.reward.referFriends.content',
    link: '/pages/income/income',
  },
  REWARD_OPEN_GROUP_BUY: {
    titleKey: 'notifications.reward.openGroupBuy.title',
    contentKey: 'notifications.reward.openGroupBuy.content',
    link: '/pages/income/income',
  },
  REWARD_GROUP_BUY: {
    titleKey: 'notifications.reward.groupBuy.title',
    contentKey: 'notifications.reward.groupBuy.content',
    link: '/pages/income/income',
  },
  REWARD_DIRECT_REFERRAL: {
    titleKey: 'notifications.reward.directReferral.title',
    contentKey: 'notifications.reward.directReferral.content',
    link: '/pages/income/income',
  },
  REWARD_CHECKIN: {
    titleKey: 'notifications.reward.checkin.title',
    contentKey: 'notifications.reward.checkin.content',
    link: '/pages/income/income',
  },
  REWARD_FIRST_COMMISSION: {
    titleKey: 'notifications.reward.firstCommission.title',
    contentKey: 'notifications.reward.firstCommission.content',
    link: '/pages/income/income',
  },
  REWARD_SECONDARY_COMMISSION: {
    titleKey: 'notifications.reward.secondaryCommission.title',
    contentKey: 'notifications.reward.secondaryCommission.content',
    link: '/pages/income/income',
  },
  MONEY_RECHARGE_SUCCESS: {
    titleKey: 'notifications.money.rechargeSuccess.title',
    contentKey: 'notifications.money.rechargeSuccess.content',
    link: '/pages/wallet/myWallet',
  },
  MONEY_WITHDRAWAL_ACCOUNT_SUCCESS: {
    titleKey: 'notifications.money.withdrawalAccountSuccess.title',
    contentKey: 'notifications.money.withdrawalAccountSuccess.content',
    link: '/pages/wallet/withdrawRecord?params=%257B%2522type%2522%253A2%257D',
  },
  MONEY_WITHDRAWAL_WALLET_SUCCESS: {
    titleKey: 'notifications.money.withdrawalWalletSuccess.title',
    contentKey: 'notifications.money.withdrawalWalletSuccess.content',
    link: '/pages/wallet/withdrawRecord?params=%257B%2522type%2522%253A2%257D',
  },
  MONEY_WITHDRAWAL_FAIL: {
    titleKey: 'notifications.money.withdrawalFail.title',
    contentKey: 'notifications.money.withdrawalFail.content',
    link: '/pages/wallet/withdrawRecord?params=%257B%2522type%2522%253A2%257D',
  },
}

// 获取通知标题
function getNoticeTitle(item: any) {
  if (item.noticeType === 'OTHER') {
    return item.noticeTitle
  }
  const config = contentTypeMap[item.noticeType]
  if (config) {
    return t(config.titleKey)
  }
  return item.noticeTitle || ''
}

// 获取通知内容
function getNoticeContent(item: any) {
  if (item.noticeType === 'OTHER') {
    return item.noticeMessage
  }
  const config = contentTypeMap[item.noticeType]
  if (config) {
    // 如果有订单号等动态数据，从item中提取
    const dynamicData = item.noticeMessage
    return t(config.contentKey, { orderId: dynamicData })
  }
  return item.noticeMessage || ''
}

// 根据通知类型获取对应图标
function getNoticeIcon(type: string) {
  for (const [key, types] of Object.entries(typeMap)) {
    if (types.includes(type))
      return `/static/icons/msg-${key}.png`
  }
  return '/static/icons/msg-other.png'
}

const dataList = ref([])
async function queryList(pageNo: number, pageSize: number) {
  try {
    const res = await noticeList({
      page: pageNo,
      size: pageSize,
      type: tab.value === 'ALL' ? null : tab.value,
    })
    if (res.code === '200') {
      paging.value.complete(res.data.records)
    }
    else {
      paging.value.complete(false)
    }
  }
  catch {
    paging.value.complete(false)
  }
}

// 处理通知点击
function handleNoticeClick(item: any) {
  item.readFlag = true
  noticeRead(item.id)
  if (item.noticeType === 'OTHER') {
    // OTHER 类型使用 page 字段和 toPage 方法跳转
    const page = item.pages
    if (page) {
      toPage({ url: page })
    }
  }
  else {
    // 其他类型使用 contentTypeMap 中的 link 字段，也使用 toPage 方法
    const config = contentTypeMap[item.noticeType]
    const link = config?.link
    if (link) {
      toPage({ url: link, params: link === '/pages/myOrders/orderDetail' ? { orderNo: item.noticeMessage } : {} })
    }
  }
}

// 处理滑动操作
async function handleAction(action: string, item: any) {
  if (action === 'del') {
    // 删除通知
    const res = await noticeDel(item.id)
    if (res.code === '200') {
      paging.value.reload()
    }
  }
}

// 格式化时间显示
function formatNoticeTime(timeString: string) {
  const noticeDate = new Date(timeString)
  const now = new Date()

  // 设置时间为当天的开始和结束
  const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  const todayEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1)

  // 如果是当天
  if (noticeDate >= todayStart && noticeDate < todayEnd) {
    // 返回 HH:mm 格式
    return `${String(noticeDate.getHours()).padStart(2, '0')}:${String(noticeDate.getMinutes()).padStart(2, '0')}`
  }

  // 计算时间差（毫秒）
  const timeDiff = now.getTime() - noticeDate.getTime()
  const daysDiff = timeDiff / (1000 * 60 * 60 * 24)

  // 如果是近一周内
  if (daysDiff <= 7) {
    // 返回星期几
    const weekdays = [
      t('notifications.time.sunday'),
      t('notifications.time.monday'),
      t('notifications.time.tuesday'),
      t('notifications.time.wednesday'),
      t('notifications.time.thursday'),
      t('notifications.time.friday'),
      t('notifications.time.saturday'),
    ]
    return weekdays[noticeDate.getDay()]
  }

  // 7天前显示短日期年月日 格式为 yy/mm/dd
  const year = String(noticeDate.getFullYear()).slice(-2)
  const month = String(noticeDate.getMonth() + 1).padStart(2, '0')
  const day = String(noticeDate.getDate()).padStart(2, '0')
  return `${year}/${month}/${day}`
}

// 清理所有未读通知
async function clearAllNotifications() {
  try {
    const res = await readAllNotice()
    if (res.code === '200') {
      // 更新本地数据状态
      dataList.value.forEach((item) => {
        item.readFlag = true
      })
      // 刷新列表
      paging.value.reload()
      // 显示成功提示
      toast.success(t('common.operate.success'))
    }
  }
  catch (error) {
    console.error('清理通知失败:', error)
  }
}
</script>

<template>
  <z-paging ref="paging" v-model="dataList" use-page-scroll @query="queryList">
    <template #top>
      <view class="bg-white" :style="{ paddingTop: `${safeAreaInsets?.top}px` }">
        <wd-navbar :bordered="false" placeholder :title="t('notifications.title')">
          <template #left>
            <wd-icon name="thin-arrow-left" size="32rpx" @click="() => goBack()" />
          </template>
          <template #right>
            <image src="/static/icons/cl.png" class="h-40rpx w-40rpx" @click="clearAllNotifications" />
          </template>
        </wd-navbar>
        <wd-tabs
          v-model="tab" :auto-line-width="true" custom-class="bg-transparent!" slidable="always"
          @click="() => queryList(1, 20)"
        >
          <wd-tab v-for="tabItem in tabs" :key="tabItem.value" :name="tabItem.value" :title="tabItem.title" />
        </wd-tabs>
      </view>
    </template>
    <view class="py-14rpx">
      <wd-swipe-action v-for="item in dataList" :key="item.id" class="mb-20rpx">
        <view
          class="bg-white px-22rpx py-18rpx" :class="{ 'notification-read': item.readFlag }"
          @click="handleNoticeClick(item)"
        >
          <view class="mb-8rpx flex items-center justify-between">
            <view class="flex items-center">
              <image
                :src="getNoticeIcon(item.noticeType)" class="h-36rpx w-36rpx"
              />
              <text class="ml-8rpx text-24rpx font-bold">
                {{ getNoticeTitle(item) }}
              </text>
            </view>
            <view class="flex items-center">
              <text class="text-22rpx">
                {{ formatNoticeTime(item.createTime) }}
              </text>
            </view>
          </view>
          <view class="flex items-center justify-between text-22rpx">
            <view class="line-clamp-2 flex-1 break-all">
              {{ getNoticeContent(item) }}
            </view>
            <view v-if="!item.readFlag" class="ml-8rpx h-12rpx w-12rpx flex-shrink-0 rounded-full bg-#FF0000" />
          </view>
        </view>
        <template #right>
          <view class="action">
            <view class="button" style="background:var(--wot-color-theme);" @click="handleAction('del', item)">
              {{ t('addressBook.delete.button') }}
            </view>
          </view>
        </template>
      </wd-swipe-action>
    </view>
  </z-paging>
</template>

<style lang="scss" scoped>
.action {
  height: 100%;

  .button {
    display: flex;
    align-items: center;
    padding: 0 24rpx;
    height: 100%;
    color: white;
  }
}

// 已读通知样式
.notification-read {
  opacity: 0.8;
}
</style>
