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

export interface Props { consumable_id?: number; consumable_name?: string }
const props = withDefaults(defineProps<Props>(), { consumable_id: undefined, consumable_name: '' })

const formRef = useTemplateRef<FormInstance>('formRef')
const form = ref({
  consumable_id: props.consumable_id as number | undefined,
  action_type: 'STOCK_IN' as string, quantity: 1,
  operator_id: undefined as number | undefined, note: '',
})

const rules = {
  consumable_id: [{ required: true, message: '耗材ID不能为空' }],
  action_type: [{ required: true, message: '请选择变动类型', trigger: 'change' }],
  quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }],
  operator_id: [{ required: true, message: '请输入操作人ID', trigger: 'blur' }],
}

onMounted(() => { form.value.consumable_id = props.consumable_id })

defineExpose({
  submit() {
    return new Promise<void>((resolve) => {
      formRef.value?.validate().then(() => {
        apiBizTransaction.inOut(form.value).then(() => { faToast.success('操作成功'); resolve() })
      }).catch(() => {})
    })
  },
})
</script>

<template>
  <div class="text-sm text-gray-500 mb-4">耗材：{{ props.consumable_name || `ID:${props.consumable_id}` }}</div>
  <AForm ref="formRef" :model="form" :rules="rules" :label-col="{ span: 5 }">
    <AFormItem label="变动类型" name="action_type">
      <ASelect v-model:value="form.action_type" :options="[
        { value: 'STOCK_IN', label: '入库' }, { value: 'STOCK_OUT', label: '出库' }, { value: 'ADJUST', label: '调整' },
      ]" />
    </AFormItem>
    <AFormItem label="变动数量" name="quantity"><AInputNumber v-model:value="form.quantity" :min="1" class="w-full" /></AFormItem>
    <AFormItem label="操作人ID" name="operator_id"><AInputNumber v-model:value="form.operator_id" placeholder="操作人ID" class="w-full" /></AFormItem>
    <AFormItem label="备注" name="note"><ATextarea v-model:value="form.note" placeholder="请输入备注" :rows="3" /></AFormItem>
  </AForm>
</template>
