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

definePage({
  style: { navigationBarTitleText: '待审批' },
})

const loading = ref(false)
const list = ref<ITask[]>([])

async function loadData() {
  loading.value = true
  try {
    const tasks = await workflowAPI.getPendingTasks() as ITask[]
    list.value = Array.isArray(tasks) ? tasks : []
  } catch {
    list.value = []
  } finally {
    loading.value = false
  }
}

function parseVariables(v: string): Record<string, any> {
  try { return JSON.parse(v || '{}') } catch { return {} }
}

function goDetail(task: ITask) {
  const bizId = task.instance?.business_id
  if (bizId) {
    uni.navigateTo({ url: `/subpackages/appointment/appointment-detail?id=${bizId}` })
  }
}

onShow(() => { loadData() })
onShareAppMessage(() => ({ title: '待审批' }))
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="task in list"
          :key="task.id"
          class="card mb-3 px-4 py-3"
          @click="goDetail(task)"
        >
          <!-- 顶部：节点名称 + 状态 -->
          <view class="flex items-center justify-between mb-2">
            <view class="flex items-center gap-2">
              <wd-tag type="warning" size="small">待审批</wd-tag>
              <text class="text-sm font-medium text-[#333]">{{ task.node_name }}</text>
            </view>
            <wd-icon name="right" size="14px" color="#ccc" />
          </view>

          <!-- 来访信息 -->
          <view class="text-xs text-[#666] leading-relaxed space-y-1">
            <view v-if="task.instance?.business_id">
              预约编号：#{{ task.instance.business_id }}
            </view>
            <view v-if="task.instance?.process_def">
              审批流程：{{ task.instance.process_def.process_name }}
            </view>
            <view v-if="task.instance?.variables">
              被访部门：{{ parseVariables(task.instance.variables).department_name || '-' }}
            </view>
            <view class="text-[#999]">
              创建时间：{{ task.created_at?.slice(0, 16) || '' }}
            </view>
          </view>
        </view>
      </view>
    </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>
