<script lang="ts" setup>
import { ref, watch } from 'vue'
import { onLoad, onReachBottom, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
import type { IAppointment } from '@/api/types/appointment'
import { getMyAppointments, cancelAppointment } from '@/api/appointment'
import { APPOINTMENT_STATUS_MAP } from '@/utils/constants'

definePage({
  style: {
    navigationBarTitleText: '预约列表',
  },
})

const tabs = [
  { title: '全部', value: -1 },
  { title: '审核中', value: 0 },
  { title: '已通过', value: 1 },
  { title: '已取消', value: 3 },
]

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

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 params: Record<string, any> = { page: page.value, page_size: 10, type: 'created' }
    const tabValue = tabs[activeTabIndex.value]?.value
    if (tabValue !== undefined && tabValue >= 0) {
      params.status = tabValue
    }
    const res = await getMyAppointments(params)
    if (reset) {
      list.value = res.list || []
    } else {
      list.value.push(...(res.list || []))
    }
    total.value = res.total
    if (list.value.length >= total.value) {
      noMore.value = true
    }
  } catch {
    // ignore
  } finally {
    loading.value = false
  }
}

function onTabChange(index: any) {
  activeTabIndex.value = typeof index === 'number' ? index : (index.detail?.value ?? index)
}

// 监听标签页切换，重新加载数据
watch(activeTabIndex, () => {
  loadData(true)
})

async function handleCancel(item: IAppointment) {
  const res = await new Promise<boolean>((resolve) => {
    uni.showModal({
      title: '提示',
      content: '确定要取消该预约吗？',
      success: (r) => resolve(r.confirm),
    })
  })
  if (!res) return
  try {
    await cancelAppointment(item.id)
    uni.showToast({ title: '已取消', icon: 'success' })
    loadData(true)
  } catch {
    // ignore
  }
}

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

// 判断是否待审核状态
function isPending(status: number) {
  return status === 0
}

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

onReachBottom(() => {
  if (!noMore.value) {
    page.value++
    loadData()
  }
})

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

<template>
  <view class="list-page min-h-screen bg-[#f5f5f5]">
    <!-- 状态筛选 -->
    <wd-tabs v-model="activeTabIndex" @change="onTabChange">
      <wd-tab v-for="tab in tabs" :key="tab.value" :title="tab.title" />
    </wd-tabs>

    <!-- 列表 -->
    <view class="px-3 py-2">
      <view v-if="list.length === 0 && !loading" class="py-20 text-center text-[#999]">
        暂无预约记录
      </view>

      <view
        v-for="item in list"
        :key="item.id"
        class="mb-3 rounded-xl bg-white p-4 shadow-sm"
        @click="goDetail(item.id)"
      >
        <view class="mb-2 flex items-center justify-between">
          <wd-tag :type="APPOINTMENT_STATUS_MAP[item.status]?.color === '#18bc37' ? 'success' : APPOINTMENT_STATUS_MAP[item.status]?.color === '#dd524d' ? 'danger' : 'primary'">
            {{ APPOINTMENT_STATUS_MAP[item.status]?.text || '未知' }}
          </wd-tag>
          <text class="text-sm text-[#999]">{{ item.visit_type }}</text>
        </view>
        <view class="text-sm text-[#666]">
          <view class="mb-1">被访人：{{ JSON.parse(item.employee_info || "{}")?.name || '-' }}</view>
          <view class="mb-1">访客：{{ JSON.parse(item.visitor_info || "{}")?.name || '-' }} {{ JSON.parse(item.visitor_info || "{}")?.phone || '' }}</view>
          <view class="mb-1">时间：{{ item.visit_start_time?.slice(0, 16) }} ~ {{ item.visit_end_time?.slice(11, 16) }}</view>
          <view v-if="item.areas_info?.length">
            区域：{{ JSON.parse(item.areas_info || "[]").join("、") }}
          </view>
        </view>
        <view v-if="isPending(item.status)" class="mt-3 flex justify-end">
          <wd-button type="warning" @click.stop="handleCancel(item)">
            取消预约
          </wd-button>
        </view>
      </view>

      <!-- 加载状态 -->
      <view v-if="loading" class="py-4 text-center text-[#999]">
        加载中...
      </view>
      <view v-else-if="noMore && list.length > 0" class="py-4 text-center text-[#ccc]">
        没有更多了
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.list-page {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}
</style>
