<template>
  <a-drawer
    v-model:visible="visible"
    :title="isUpdate ? '修改维度' : '新增维度'"
    @before-ok="save"
    @cancel="reset"
  >
    <a-form ref="formRef" :model="form" auto-label-width>
      <a-form-item label="维度名称" field="name" required>
        <a-input v-model="form.name" />
      </a-form-item>
      <a-form-item label="权重%" field="weight" required>
        <a-input-number v-model="form.weight" :min="1" :max="100" />
      </a-form-item>
      <a-form-item label="描述" field="desc">
        <a-textarea v-model="form.desc" :rows="3" />
      </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 { reactive, ref } from 'vue'
import { addDimension, getDimensionDetail, updateDimension } from '@/apis/performance'

const emit = defineEmits<{
  (e: 'success'): void
}>()
const visible = ref(false)
const isUpdate = ref(false)
const formRef = ref()
const id = ref('')
const form = reactive({
  name: '',
  weight: 50,
  desc: '',
  status: 0 as 0 | 1,
})

const reset = () => {
  formRef.value?.resetFields()
  Object.assign(form, { name: '', weight: 50, desc: '', status: 0 })
  id.value = ''
}

const save = async () => {
  if (isUpdate.value) {
    await updateDimension(id.value, form)
  } else {
    await addDimension(form)
  }
  visible.value = false
  emit('success')
}

const onAdd = () => {
  reset()
  isUpdate.value = false
  visible.value = true
}

const onUpdate = async (dimensionId: string) => {
  reset()
  isUpdate.value = true
  id.value = dimensionId
  const data = await getDimensionDetail(dimensionId)
  Object.assign(form, data)
  visible.value = true
}

defineExpose({ onAdd, onUpdate })
</script>
