<script setup>
import { onLoad, onReachBottom } from '@dcloudio/uni-app'
import { queryList } from '@/api/apis'

const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const reportList = ref([])
const loadingState = ref('loading')
const num = ref(0)
const max = ref(60)

// 初始加载数据
function fetchData() {
  queryList({ page: page.value, page_size: pageSize.value }).then((res) => {
    if (res.code === 200) {
      total.value = res.data.total
      if (res.data.list && res.data.list.length > 0) {
        reportList.value.push(...res.data.list)
        page.value += 1
      }
      if (reportList.value.length >= total.value) {
        loadingState.value = 'finished'
      }
      else {
        loadingState.value = 'loading'
      }
    }
  })
}

// 初始加载
onLoad(() => {
  fetchData()
})

// 下拉触底加载更多
onReachBottom(() => {
  if (loadingState.value !== 'finished') {
    if (num.value >= max.value) {
      loadingState.value = 'finished'
    }
    else {
      fetchData()
    }
  }
})
function toDetail(item) {
  // if (item.query_state !== 'success')
  //   return
  uni.navigateTo({
    url: `/pages/report?order_id=${item.order_id}`,
  })
}
// 状态文字映射
function stateText(state) {
  switch (state) {
    case 'pending':
      return '查询中'
    case 'success':
      return '查询成功'
    case 'failed':
      return '查询失败'
    default:
      return '未知状态'
  }
}

// 状态颜色映射
function statusClass(state) {
  switch (state) {
    case 'pending':
      return 'status-pending'
    case 'success':
      return 'status-success'
    case 'failed':
      return 'status-failed'
    default:
      return ''
  }
}
</script>

<template>
  <wd-notice-bar
    text="为保证用户的隐私以及数据安全，您的报告生成30天之后将自动清除，请及时保存您的报告。" prefix="warn-bold" color="#007aff"
    background-color="#f8f8f8"
  />
  <view class="flex flex-col gap-4 p-4">
    <view v-for="item in reportList" :key="item.id" class="card flex flex-col gap-2" @click="toDetail(item)">
      <view class="flex items-center justify-between">
        <view class="">
          状态:
        </view>
        <view class="rounded-xl px-2 py-1" :class="[statusClass(item.query_state)]">
          {{ stateText(item.query_state) }}
        </view>
      </view>
      <view class="flex items-center justify-between">
        <view class="">
          报告类型
        </view>
        <view>
          {{ item.product_name }}
        </view>
      </view>
      <view class="flex items-center justify-between">
        <view class="">
          查询时间:
        </view>
        <view>
          {{ item.create_time }}
        </view>
      </view>
    </view>
    <!-- 加载更多 -->
    <wd-loadmore :state="loadingState" @reload="fetchData" />
  </view>
</template>

<style lang="scss" scoped>
.status-pending {
  @apply bg-yellow-100 text-yellow-600;
}

.status-success {
  @apply bg-green-100 text-green-600;
}

.status-failed {
  @apply bg-red-100 text-red-600;
}
</style>

<route lang="json">
  {
    "layout": "page",
    "title": "历史报告"
  }
</route>
