<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'

import { addWordList } from '#/api'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  vocabularyId: {
    type: String,
    default: '',
  },
  title: {
    type: String,
    default: '新增单词',
  },
  diaData: {
    type: Object,
    default: () => ({}),
  },
})
const emits = defineEmits(['update:modelValue', 'onRefresh'])

const show = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emits('update:modelValue', val)
  },
})

const _formData = {
  wordSpell: '',
  status: 0,
}
const formRef = ref<FormInstance | undefined>()
const formData = reactive<Record<string, any>>({
  ..._formData,
})

const rules = reactive<FormRules>({
  wordSpell: [{ required: true, message: '单词不能为空', trigger: 'blur' }],
})

function onOpen() {
  onClear()
  if (props.diaData.id) {
    for (const i in formData) {
      formData[i] = props.diaData[i]
    }
  }
}

async function handleSave() {
  await formRef.value?.validate((valid, _) => {
    if (valid) {
      addWordList({ ...formData, vocabularyId: props.vocabularyId }).then(
        () => {
          show.value = false
          onClear()
          emits('onRefresh')
        },
      )
    }
  })
}

function onClear() {
  Object.assign(formData, _formData)
}
</script>

<template>
  <el-dialog
    v-model="show"
    width="30vw"
    :title="title"
    class="box"
    destroy-on-close
    @open="onOpen"
  >
    <el-form ref="formRef" label-width="80px" :model="formData" :rules="rules">
      <el-form-item label="单词" prop="wordSpell">
        <el-input v-model="formData.wordSpell" placeholder="请输入" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="handleSave"> 保存 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped></style>
