<script lang="ts" setup>
import { ref } from 'vue'
import { onShow, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
import { getMyAppointments } from '@/api/appointment'
import type { IAppointment } from '@/api/types/appointment'

definePage({
  style: { navigationBarTitleText: '预约我的' },
})

const loading = ref(false)
const list = ref<IAppointment[]>([])
const page = ref(1)
const total = ref(0)
const noMore = ref(false)
const pageSize = 10

async function loadData(reset = false) {
  if (loading.value) return
  if (!reset && noMore.value) return

  loading.value = true
  if (reset) {
    page.value = 1
    list.value = []
    noMore.value = false
  }

  try {
    const res = await getMyAppointments({
      page: page.value,
      page_size: pageSize,
      type: 'mine',
    })
    if (reset) {
      list.value = res.list || []
    } else {
      list.value.push(...(res.list || []))
    }
    total.value = res.total
    noMore.value = list.value.length >= total.value
  } catch {
    uni.showToast({ title: '加载失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

function loadMore() {
  if (!noMore.value) {
    page.value++
    loadData()
  }
}

function goDetail(id: number) {
  uni.navigateTo({ url: `/subpackages/appointment/appointment-detail?id=${id}` })
}

/**
 * 智能状态标签
 * 根据预约状态返回显示文字和标签类型
 */
function smartStatus(item: IAppointment): { text: string; type: 'warning' | 'success' | 'danger' | 'info' | 'primary' } {
  const status = item.status
  if (status === 3) return { text: '申请已取消', type: 'info' }
  if (status === 1) return { text: '已通过', type: 'success' }
  if (status === 2) return { text: '已拒绝', type: 'danger' }
  // status === 0 (审核中) — 详情页会加载步骤并显示当前审批人
  return { text: '待审核', type: 'warning' }
}

onShow(() => {
  loadData(true)
})

// 分享
onShareAppMessage(() => ({ title: '预约我的', path: '/subpackages/appointment/approval-list' }))
onShareTimeline(() => ({ title: '预约我的' }))
</script>

<template>
  <view class="page min-h-screen bg-[#f5f7fa]">
    <view class="px-3 pt-3">
      <!-- 列表 -->
      <view v-if="loading && list.length === 0" class="flex justify-center py-20">
        <wd-loading />
      </view>

      <view v-else-if="list.length === 0" class="flex flex-col items-center justify-center py-20">
        <wd-icon name="check-outline" size="48px" color="#ccc" />
        <text class="mt-3 text-sm text-gray-400">暂无预约</text>
      </view>

      <view v-else>
        <view
          v-for="item in list"
          :key="item.id"
          class="card mb-3 px-4 py-3"
          @click="goDetail(item.id)"
        >
          <view class="flex items-center justify-between">
            <view class="flex items-center gap-2">
              <wd-tag :type="smartStatus(item).type">
                {{ smartStatus(item).text }}
              </wd-tag>
              <text class="text-sm font-medium text-[#333]">{{ item.visit_type }}</text>
            </view>
            <wd-icon name="right" size="14px" color="#ccc" />
          </view>
          <view class="mt-2 text-xs text-gray-400">
            申请人：{{ (JSON.parse(item.creator_info || '{}') as any)?.name || '-' }}
            ｜{{ item.visit_start_time?.slice(0, 16) }}
          </view>
          <view class="mt-1 text-xs text-gray-400">
            访客：{{ (JSON.parse(item.visitor_info || '{}') as any)?.name || '-' }}
          </view>
        </view>
      </view>
    </view>

    <view v-if="list.length > 0 && !noMore" class="flex justify-center py-4" @click="loadMore">
      <text class="text-sm text-blue-500">{{ loading ? '加载中...' : '加载更多' }}</text>
    </view>
    <view v-else-if="noMore && list.length > 0" class="flex justify-center py-4">
      <text class="text-xs text-gray-300">没有更多了</text>
    </view>

    <view class="h-6" />
  </view>
</template>

<style lang="scss" scoped>
.page {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}
.card {
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
}
</style>
