<template>
  <view class="list">
    <text class="list-title">一周内的消息通知</text>
    <view v-for="item in msgList" :key="item.id" v-if="msgList.length != 0">
      <view class="list-item" @tap="moveToDetail(item.messageID, item.id)">
        <view class="content">
          <div class="new-icon" v-if="item.readCount === 0">新消息</div>
          <div class="old-icon" v-else>已查看</div>
          <div class="title">{{ item.title }}</div>
        </view>
        <div class="create-time">{{ timeFormatHMS(item.createdAt) }}</div>
      </view>
    </view>
    <jx-empty title="暂无消息通知" v-else />
  </view>

  <!-- 公共组件 -->
  <jx-loading />
</template>

<script lang="ts" setup>
import { getStorage } from '@/utils/storage'
import toast from '@/utils/toast'
import { timeFormatD, timeFormatHMS } from '@/utils/tools'
import { onShow } from '@dcloudio/uni-app'
import { ref } from 'vue'
import merchant from '@/api/https/merchant'

/**
 * 获取信息列表
 */
interface MsgListType {
  id: number
  messageID: number
  title: string
  createdAt: string
  readCount: number
}
const msgList = ref<Array<MsgListType>>([
  {
    id: 0,
    messageID: 0,
    title: '',
    createdAt: '',
    readCount: 0,
  },
])
onShow(async () => {
  await getMessageData()
})
async function getMessageData() {
  let data = {
    storeIDs: JSON.stringify([+getStorage('storeID')]),
    offset: 0,
    pageSize: -1,
    fromTime: timeFormatD(+new Date() - 7 * 24 * 60 * 60 * 1000) + ' 00:00:00',
    toTime: timeFormatD(+new Date()) + ' 23:59:59',
  }
  let msgRes = await merchant.Get_store_message_statuses(data)
  if (msgRes.code == 0) {
    if (msgRes.data.totalCount != 0) {
      // 对信息按照时间进行排序
      msgList.value = msgRes.data.data.sort(
        (n1: MsgListType, n2: MsgListType) => {
          return +new Date(n2.createdAt) - +new Date(n1.createdAt)
        }
      )
    } else {
      msgList.value = []
    }
  } else {
    toast('消息数据异常')
  }
}

/**
 * 查看详情
 */
function moveToDetail(messageID: number, id: number) {
  uni.navigateTo({
    url: `/subPages/merchantChild/messageDetail/messageDetail?messageID=${messageID}&id=${id}`,
  })
}
</script>

<style lang="scss" scoped>
@import './message.scss';
</style>