<script setup lang="ts">
import type { FormInstance } from 'antdv-next'
import apiBizRequest from '@/api/modules/bizRequest'

export interface Props { id?: number | string }
const props = withDefaults(defineProps<Props>(), { id: '' })

const loading = ref(false)
const isEdit = computed(() => props.id === '')
const formRef = useTemplateRef<FormInstance>('formRef')

const form = ref({
  user_id: undefined as number | undefined, item_type: undefined as string | undefined,
  category_id: undefined as number | undefined, item_id: undefined as number | undefined,
  quantity: 1, reason: '', is_long_term: 1, expected_return_time: '',
})

const rules = {
  user_id: [{ required: true, message: '请输入申请人ID', trigger: 'blur' }],
  item_type: [{ required: true, message: '请选择资产类型', trigger: 'change' }],
}

// Detail mode
const detailData = ref<any>(null)
const approveForm = ref({ approver_id: undefined as number | undefined, status: 'approved', approval_note: '' })

onMounted(() => { if (props.id !== '') getInfo() })

function getInfo() {
  loading.value = true
  apiBizRequest.detail(props.id as number).then((res: any) => {
    loading.value = false
    detailData.value = res.data
  }).catch(() => { loading.value = false })
}

function onApprove() {
  if (!approveForm.value.approver_id) { faToast.warning('请输入审批人ID'); return }
  apiBizRequest.approve({ id: detailData.value.id, ...approveForm.value }).then(() => { faToast.success('审批完成'); getInfo() })
}

defineExpose({
  submit() {
    return new Promise<void>((resolve) => {
      if (!isEdit.value) { resolve(); return }
      formRef.value?.validate().then(() => {
        apiBizRequest.submit(form.value).then(() => { faToast.success('提交申请成功'); resolve() })
      }).catch(() => {})
    })
  },
})
</script>

<template>
  <div v-if="loading" class="flex-center py-12"><ASpin /></div>
  <!-- Detail mode -->
  <div v-else-if="!isEdit && detailData" class="text-sm space-y-4">
    <div class="grid grid-cols-2 gap-3">
      <div><span class="text-gray-500">申请单号：</span>{{ detailData.request_no }}</div>
      <div><span class="text-gray-500">申请人：</span>{{ detailData.user_name }}</div>
      <div><span class="text-gray-500">资产类型：</span><ATag>{{ detailData.item_type }}</ATag></div>
      <div><span class="text-gray-500">分类：</span>{{ detailData.category_name }}</div>
      <div><span class="text-gray-500">数量：</span>{{ detailData.quantity }}</div>
      <div><span class="text-gray-500">状态：</span><ATag :color="detailData.status === 'approved' ? 'green' : detailData.status === 'rejected' ? 'red' : 'orange'">{{ detailData.status }}</ATag></div>
      <div><span class="text-gray-500">长期使用：</span>{{ detailData.is_long_term ? '是' : '否' }}</div>
      <div><span class="text-gray-500">预计归还：</span>{{ detailData.expected_return_time }}</div>
      <div><span class="text-gray-500">审批人：</span>{{ detailData.approver_name }}</div>
      <div><span class="text-gray-500">审批时间：</span>{{ detailData.approval_time }}</div>
    </div>
    <div v-if="detailData.reason"><span class="text-gray-500">申请原因：</span>{{ detailData.reason }}</div>
    <div v-if="detailData.approval_note"><span class="text-gray-500">审批意见：</span>{{ detailData.approval_note }}</div>
    <!-- Approval section -->
    <div v-if="detailData.status === 'pending'" class="border-t pt-4 mt-4">
      <div class="font-medium mb-3">审批操作</div>
      <div class="flex gap-3 items-end">
        <div>
          <div class="text-xs text-gray-500 mb-1">审批人ID</div>
          <AInputNumber v-model:value="approveForm.approver_id" placeholder="审批人ID" class="w-32" />
        </div>
        <div>
          <div class="text-xs text-gray-500 mb-1">审批意见</div>
          <AInput v-model:value="approveForm.approval_note" placeholder="审批意见" class="w-48" />
        </div>
        <AButton type="primary" @click="onApprove">通过</AButton>
        <AButton variant="outline" @click="approveForm.status = 'rejected'; onApprove()">拒绝</AButton>
      </div>
    </div>
  </div>
  <!-- Create mode -->
  <AForm v-else ref="formRef" :model="form" :rules="rules" :label-col="{ span: 5 }">
    <AFormItem label="申请人ID" name="user_id"><AInputNumber v-model:value="form.user_id" placeholder="申请人ID" class="w-full" /></AFormItem>
    <AFormItem label="资产类型" name="item_type">
      <ASelect v-model:value="form.item_type" placeholder="请选择" :options="[
        { value: 'device', label: '设备' }, { value: 'license', label: '许可' }, { value: 'accessory', label: '配件' },
      ]" />
    </AFormItem>
    <AFormItem label="分类ID" name="category_id"><AInputNumber v-model:value="form.category_id" placeholder="分类ID(可选)" class="w-full" /></AFormItem>
    <AFormItem label="资产ID" name="item_id"><AInputNumber v-model:value="form.item_id" placeholder="资产ID(可选)" class="w-full" /></AFormItem>
    <AFormItem label="数量" name="quantity"><AInputNumber v-model:value="form.quantity" :min="1" class="w-full" /></AFormItem>
    <AFormItem label="长期使用" name="is_long_term">
      <ASelect v-model:value="form.is_long_term" :options="[{ value: 1, label: '是' }, { value: 0, label: '否' }]" />
    </AFormItem>
    <AFormItem label="预计归还" name="expected_return_time"><ADatePicker v-model:value="form.expected_return_time" show-time value-format="YYYY-MM-DD HH:mm:ss" class="w-full" /></AFormItem>
    <AFormItem label="申请原因" name="reason"><ATextarea v-model:value="form.reason" placeholder="请输入申请原因" :rows="3" /></AFormItem>
  </AForm>
</template>
