<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { getApprovalDetail, approveRecord, rejectRecord } from '@/api/appointment'
import type { IApprovalDetail, IApprovalRecord } from '@/api/types/appointment'

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

const loading = ref(false)
const detail = ref<IApprovalDetail | null>(null)
const instanceId = ref(0)
const currentRecordId = ref(0)

// 审批操作
const showAction = ref(false)
const actionType = ref<'approve' | 'reject'>('approve')
const comment = ref('')
const submitting = ref(false)

onMounted(() => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1] as any
  const options = currentPage.$page?.options || currentPage.options || {}
  instanceId.value = Number(options.instanceId || 0)
  currentRecordId.value = Number(options.recordId || 0)
  loadDetail()
})

async function loadDetail() {
  loading.value = true
  try {
    detail.value = await getApprovalDetail(instanceId.value)
  } catch {
    uni.showToast({ title: '加载失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

function openApprove() {
  actionType.value = 'approve'
  comment.value = ''
  showAction.value = true
}

function openReject() {
  actionType.value = 'reject'
  comment.value = ''
  showAction.value = true
}

async function submitAction() {
  submitting.value = true
  try {
    if (actionType.value === 'approve') {
      await approveRecord({ record_id: currentRecordId.value, comment: comment.value })
    } else {
      await rejectRecord({ record_id: currentRecordId.value, comment: comment.value })
    }
    showAction.value = false
    uni.showToast({ title: actionType.value === 'approve' ? '审批通过' : '已拒绝', icon: 'success' })
    loadDetail()
  } catch (err: any) {
    uni.showToast({ title: err.message || '操作失败', icon: 'none' })
  } finally {
    submitting.value = false
  }
}

// 状态映射
function instanceStatusText(status: number) {
  const map: Record<number, string> = { 0: '审批中', 1: '已通过', 2: '已拒绝', 3: '已撤销' }
  return map[status] || '未知'
}

function instanceStatusType(status: number) {
  const map: Record<number, string> = { 0: 'warning', 1: 'success', 2: 'danger', 3: 'info' }
  return map[status] || 'info'
}

function recordStatusText(status: number) {
  const map: Record<number, string> = { 0: '待审批', 1: '已通过', 2: '已拒绝' }
  return map[status] || '未知'
}

function recordStatusType(status: number) {
  const map: Record<number, string> = { 0: 'warning', 1: 'success', 2: 'danger' }
  return map[status] || 'info'
}

// 判断当前记录是否可操作
const canOperate = () => {
  if (!detail.value) return false
  const currentRecord = detail.value.records.find(r => r.id === currentRecordId.value)
  return currentRecord && currentRecord.status === 0 && detail.value.instance.status === 0
}
</script>

<template>
  <view class="page min-h-screen bg-[#f5f5f5]">
    <wd-loading v-if="loading" class="py-20" />

    <template v-else-if="detail">
      <!-- 流程状态 -->
      <view class="mx-3 mt-3 rounded-xl bg-white p-4">
        <view class="flex items-center justify-between">
          <text class="text-base font-semibold text-[#333]">
            {{ detail.instance.template?.name || '审批流程' }}
          </text>
          <wd-tag :type="instanceStatusType(detail.instance.status)">
            {{ instanceStatusText(detail.instance.status) }}
          </wd-tag>
        </view>
        <view class="mt-2 text-xs text-gray-400">
          发起时间：{{ detail.instance.created_at }}
        </view>
      </view>

      <!-- 审批记录时间线 -->
      <view class="mx-3 mt-3 rounded-xl bg-white p-4">
        <text class="text-sm font-semibold text-[#333]">审批进度</text>
        <view class="mt-3">
          <view
            v-for="(record, idx) in detail.records"
            :key="record.id"
            class="timeline-item flex"
          >
            <!-- 时间线节点 -->
            <view class="timeline-left flex flex-col items-center">
              <view
                class="node-dot h-3 w-3 rounded-full"
                :class="{
                  'bg-blue-500': record.status === 1,
                  'bg-red-500': record.status === 2,
                  'bg-orange-400': record.status === 0,
                  'bg-gray-300': record.status === 0 && detail.instance.status !== 0,
                }"
              />
              <view
                v-if="idx < detail.records.length - 1"
                class="node-line w-0.5 flex-1"
                :class="record.status === 1 ? 'bg-blue-300' : 'bg-gray-200'"
              />
            </view>
            <!-- 节点内容 -->
            <view class="ml-3 flex-1 pb-4">
              <view class="flex items-center justify-between">
                <text class="text-sm font-medium text-[#333]">{{ record.node_name }}</text>
                <wd-tag :type="recordStatusType(record.status)">
                  {{ recordStatusText(record.status) }}
                </wd-tag>
              </view>
              <view v-if="record.approver" class="mt-1 text-xs text-gray-400">
                审批人：{{ record.approver.real_name || '未知' }}
              </view>
              <view v-if="record.comment" class="mt-1 rounded-lg bg-gray-50 p-2 text-xs text-gray-600">
                {{ record.comment }}
              </view>
              <view v-if="record.approved_at" class="mt-1 text-xs text-gray-400">
                {{ record.approved_at }}
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view v-if="canOperate()" class="mx-3 mt-6 flex gap-3">
        <wd-button type="danger" size="large" block @click="openReject">
          拒绝
        </wd-button>
        <wd-button type="primary" size="large" block @click="openApprove">
          通过
        </wd-button>
      </view>
    </template>

    <!-- 审批操作弹窗 -->
    <wd-popup
      v-model="showAction"
      position="bottom"
      custom-style="border-radius: 16px 16px 0 0; padding: 20px;"
    >
      <view class="text-center">
        <text class="text-lg font-bold">
          {{ actionType === 'approve' ? '审批通过' : '审批拒绝' }}
        </text>
      </view>
      <view class="mt-4">
        <text class="text-sm text-gray-500">审批意见（选填）</text>
        <wd-textarea
          v-model="comment"
          placeholder="请输入审批意见"
          ::maxlength="200"
          custom-style="margin-top: 8px;"
        />
      </view>
      <view class="mt-4 flex gap-3">
        <wd-button size="large" block @click="showAction = false">取消</wd-button>
        <wd-button
          :type="actionType === 'approve' ? 'primary' : 'danger'"
          size="large"
          block
          :loading="submitting"
          @click="submitAction"
        >
          {{ actionType === 'approve' ? '确认通过' : '确认拒绝' }}
        </wd-button>
      </view>
      <view class="h-4" />
    </wd-popup>

    <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);
}

.timeline-left {
  width: 20px;
  flex-shrink: 0;
}

.node-line {
  min-height: 20px;
}
</style>
