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

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

const loading = ref(false)
const formRef = useTemplateRef<FormInstance>('formRef')
const form = ref({
  id: props.id as number | string, name: '', status: 1,
  months: 36, floor_type: 'amount', floor_val: 0 as number | undefined,
  remark: '',
})

const rules = {
  name: [{ required: true, message: '请输入折旧规则名称', trigger: 'blur' }],
  months: [{ required: true, message: '请输入折旧月数', trigger: 'blur' }],
}

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

function getInfo() {
  loading.value = true
  apiAssetDepreciation.detail(form.value.id as number).then((res: any) => {
    loading.value = false
    const d = res.data
    Object.assign(form.value, {
      name: d.name, status: d.status, months: d.months,
      floor_type: d.floor_type, floor_val: d.floor_val, remark: d.remark,
    })
  }).catch(() => { loading.value = false })
}

defineExpose({
  submit() {
    return new Promise<void>((resolve) => {
      formRef.value?.validate().then(() => {
        apiAssetDepreciation.save(form.value).then(() => { faToast.success(form.value.id ? '编辑成功' : '新增成功'); resolve() })
      }).catch(() => {})
    })
  },
})
</script>

<template>
  <div v-if="loading" class="flex-center py-12"><ASpin /></div>
  <AForm v-else ref="formRef" :model="form" :rules="rules" :label-col="{ span: 5 }">
    <AFormItem label="规则名称" name="name"><AInput v-model:value="form.name" placeholder="请输入规则名称" /></AFormItem>
    <AFormItem label="状态" name="status">
      <ASelect v-model:value="form.status" :options="[{ value: 1, label: '启用' }, { value: 0, label: '停用' }]" />
    </AFormItem>
    <AFormItem label="折旧月数" name="months"><AInputNumber v-model:value="form.months" :min="1" class="w-full" /></AFormItem>
    <AFormItem label="残值类型" name="floor_type">
      <ASelect v-model:value="form.floor_type" :options="[{ value: 'amount', label: '固定金额' }, { value: 'percent', label: '百分比' }]" />
    </AFormItem>
    <AFormItem label="残值" name="floor_val">
      <AInputNumber v-model:value="form.floor_val" :precision="2" class="w-full" :addon-after="form.floor_type === 'percent' ? '%' : '元'" />
    </AFormItem>
    <AFormItem label="描述" name="remark"><ATextarea v-model:value="form.remark" placeholder="请输入描述" :rows="3" /></AFormItem>
  </AForm>
</template>
