<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { onShow, onShareAppMessage, onShareTimeline, onLoad } from '@dcloudio/uni-app'
import { getAllAppointments, getAppointmentDetail } from '@/api/appointment'
import { workflowAPI } from '@/api/workflow'
import type { IAppointment } from '@/api/types/appointment'
import type { ITask } from '@/api/types/workflow'

definePage({
  style: { navigationBarTitleText: '全部预约' },
})

// ===== Tab 切换 =====
const activeTab = ref<'all' | 'pending'>('all')

// ===== 全部预约 =====
const allLoading = ref(false)
const allList = ref<IAppointment[]>([])
const allPage = ref(1)
const allTotal = ref(0)
const allNoMore = ref(false)
const pageSize = 10

async function loadAll(reset = false) {
  if (allLoading.value) return
  if (!reset && allNoMore.value) return
  allLoading.value = true
  if (reset) { allPage.value = 1; allList.value = []; allNoMore.value = false }
  try {
    const res = await getAllAppointments({ page: allPage.value, page_size: pageSize })
    if (reset) { allList.value = res.list || [] }
    else { allList.value.push(...(res.list || [])) }
    allTotal.value = res.total
    allNoMore.value = allList.value.length >= allTotal.value
  } catch { uni.showToast({ title: '加载失败', icon: 'none' }) }
  finally { allLoading.value = false }
}

function loadMoreAll() {
  if (!allNoMore.value) { allPage.value++; loadAll() }
}

// ===== 待审批 =====
const pendingLoading = ref(false)
const pendingList = ref<IAppointment[]>([])

async function loadPending() {
  pendingLoading.value = true
  pendingList.value = []
  try {
    const tasks = await workflowAPI.getPendingTasks() as ITask[]
    if (!tasks || !Array.isArray(tasks)) return

    // 去重 + 查出对应的预约详情
    const seen = new Set<number>()
    for (const task of tasks) {
      const bizId = task.instance?.business_id
      if (!bizId || seen.has(bizId)) continue
      seen.add(bizId)
      // 从预约详情接口获取完整数据
      try {
        const detail = await getAppointmentDetail(bizId) as any
        if (detail) pendingList.value.push(detail)
      } catch { /* ignore */ }
    }
  } catch { /* ignore */ }
  finally { pendingLoading.value = false }
}

// ===== 通用 =====
function parseCreatorInfo(item: IAppointment): { name?: string; phone?: string } {
  try { return JSON.parse(item.creator_info || '{}') } catch { return {} }
}
function parseEmployeeInfo(item: IAppointment): { name?: string; phone?: string } {
  if (!item.employee_info) return {}
  try { const p = JSON.parse(item.employee_info); return p.name ? p : {} } catch { return {} }
}
function goDetail(id: number) {
  uni.navigateTo({ url: `/subpackages/appointment/appointment-detail?id=${id}` })
}

function onTabChange(tab: string) {
  if (tab === 'all') loadAll(true)
  else loadPending()
}

// 接收 URL 参数 tab
onLoad((options) => {
  if (options?.tab === 'pending') {
    activeTab.value = 'pending'
  }
})

onShow(() => {
  if (activeTab.value === 'all') loadAll(true)
  else loadPending()
})

onShareAppMessage(() => ({ title: '全部预约' }))
onShareTimeline(() => ({ title: '全部预约' }))
</script>

<template>
  <view class="page min-h-screen bg-[#f5f7fa]">
    <!-- Tab -->
    <view class="flex bg-white px-3 pt-2 pb-0 sticky top-0 z-10">
      <view
        class="flex-1 pb-2 text-center text-sm font-medium"
        :class="activeTab === 'all' ? 'text-[#2979ff] border-b-2 border-[#2979ff]' : 'text-[#999]'"
        @click="activeTab = 'all'; onTabChange('all')"
      >全部</view>
      <view
        class="flex-1 pb-2 text-center text-sm font-medium"
        :class="activeTab === 'pending' ? 'text-[#2979ff] border-b-2 border-[#2979ff]' : 'text-[#999]'"
        @click="activeTab = 'pending'; onTabChange('pending')"
      >待审批</view>
    </view>

    <view class="px-3 pt-3">
      <!-- ===== 全部 ===== -->
      <template v-if="activeTab === 'all'">
        <view v-if="allLoading && allList.length === 0" class="flex justify-center py-20">
          <wd-loading />
        </view>
        <view v-else-if="allList.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 allList" :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="item.status === 0 ? 'warning' : item.status === 1 ? 'success' : item.status === 2 ? 'danger' : 'info'" size="small">
                  {{ item.status === 0 ? '待审核' : item.status === 1 ? '已通过' : item.status === 2 ? '已拒绝' : '已取消' }}
                </wd-tag>
                <text class="text-sm font-medium text-[#333]">{{ item.visit_purpose || '-' }}</text>
              </view>
              <wd-icon name="right" size="14px" color="#ccc" />
            </view>
            <view class="mt-2 text-xs text-[#999] leading-relaxed">公司接待人员：{{ parseEmployeeInfo(item).name || '-' }}</view>
            <view class="text-xs text-[#999] leading-relaxed">申请人：{{ parseCreatorInfo(item).name || '-' }} ｜{{ item.created_at?.slice(0, 16) || '' }}</view>
            <view class="text-xs text-[#999] leading-relaxed">来访时间：{{ item.visit_start_time?.slice(0, 16) || '-' }} ~ {{ item.visit_end_time?.slice(5, 16) || '-' }}</view>
          </view>
        </view>
        <view v-if="allList.length > 0 && !allNoMore" class="flex justify-center py-4" @click="loadMoreAll">
          <text class="text-sm text-blue-500">{{ allLoading ? '加载中...' : '加载更多' }}</text>
        </view>
        <view v-else-if="allNoMore && allList.length > 0" class="flex justify-center py-4">
          <text class="text-xs text-gray-300">没有更多了</text>
        </view>
      </template>

      <!-- ===== 待审批 ===== -->
      <template v-else>
        <view v-if="pendingLoading && pendingList.length === 0" class="flex justify-center py-20">
          <wd-loading />
        </view>
        <view v-else-if="pendingList.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 pendingList" :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="warning" size="small">待审批</wd-tag>
                <text class="text-sm font-medium text-[#333]">{{ item.visit_purpose || '-' }}</text>
              </view>
              <wd-icon name="right" size="14px" color="#ccc" />
            </view>
            <view class="mt-2 text-xs text-[#999] leading-relaxed">公司接待人员：{{ parseEmployeeInfo(item).name || '-' }}</view>
            <view class="text-xs text-[#999] leading-relaxed">申请人：{{ parseCreatorInfo(item).name || '-' }} ｜{{ item.created_at?.slice(0, 16) || '' }}</view>
            <view class="text-xs text-[#999] leading-relaxed">来访时间：{{ item.visit_start_time?.slice(0, 16) || '-' }} ~ {{ item.visit_end_time?.slice(5, 16) || '-' }}</view>
          </view>
        </view>
      </template>
    </view>
  </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>
