<template>
    <a-drawer v-model:visible="visible" :title="isEdit ? '编辑细则' : '新增细则'" @before-ok="save">
        <a-form ref="formRef" :model="form" auto-label-width>
            <a-form-item label="细则名称" field="ruleName" required>
                <a-input v-model="form.ruleName" />
            </a-form-item>
            <a-form-item label="描述" field="description">
                <a-textarea v-model="form.description" :rows="3" />
            </a-form-item>
            <a-form-item label="分数" field="score">
                <a-input-number v-model="form.score" :min="0" />
            </a-form-item>
            <a-form-item label="权重" field="weight">
                <a-input-number v-model="form.weight" :min="0" :max="100" />
            </a-form-item>
            <a-form-item label="奖金" field="bonus">
                <a-input v-model="form.bonus" />
            </a-form-item>
            <a-form-item label="状态" field="status">
                <a-switch v-model="form.status" :checked-value="0" :unchecked-value="1" />
            </a-form-item>
        </a-form>
    </a-drawer>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { addRule, updateRule } from '@/apis/performance-setting'
import type { PerformanceRule, PerformanceDimension } from '@/apis/performance-setting/type'

const props = defineProps<{ dimension?: PerformanceDimension }>()
const emit = defineEmits(['success'])
const visible = ref(false)
const isEdit = ref(false)
const formRef = ref()
const form = ref<Partial<PerformanceRule>>({
    ruleName: '',
    description: '',
    score: 0,
    weight: 0,
    bonus: '',
    status: 0,
    dimensionName: '',
})

watch(
    () => props.dimension,
    (val) => {
        if (val && !isEdit.value) {
            form.value.dimensionName = val.dimensionName
        }
    },
    { immediate: true }
)

const open = (record?: PerformanceRule) => {
    if (record) {
        Object.assign(form.value, record)
        isEdit.value = true
    } else {
        Object.assign(form.value, {
            ruleName: '',
            description: '',
            score: 0,
            weight: 0,
            bonus: '',
            status: 0,
            dimensionName: props.dimension?.dimensionName || '',
        })
        isEdit.value = false
    }
    visible.value = true
}

const save = async () => {
    if (isEdit.value && form.value.ruleId) {
        await updateRule(form.value.ruleId, form.value)
    } else {
        await addRule(form.value)
    }
    visible.value = false
    emit('success')
}

defineExpose({ open })
</script>