<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { addWordRoot, updateWordRoot } from '#/api'
import getDict from '#/hooks/useDict'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  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 ROOT_TYPE: anyObj = getDict('word_root_type')
const _formData = {
  wordRoot: '',
  wordRootType: undefined,
  wordRootMeaning: '',
  sameSourceWords: '',
}
const formRef = ref<FormInstance | undefined>()
const formData = reactive<Record<string, any>>({
  ..._formData,
})

const rules = reactive<FormRules>({
  wordRoot: [{ required: true, message: '词根词缀不能为空', trigger: 'blur' }],
  wordRootType: [{ 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) {
      if (props.diaData.id) {
        updateWordRoot({ ...formData, id: props.diaData.id }).then(() => {
          show.value = false
          onClear()
          emits('onRefresh')
        })
      } else {
        addWordRoot({ ...formData }).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="wordRoot">
        <el-input v-model="formData.wordRoot" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="类型" prop="wordRootType">
        <el-select v-model="formData.wordRootType" placeholder="请选择">
          <el-option
            v-for="op in ROOT_TYPE"
            :key="op.id"
            :label="op.value"
            :value="op.code * 1"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="词根含义">
        <el-input v-model="formData.wordRootMeaning" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="同源单词">
        <el-input v-model="formData.sameSourceWords" 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>
.box {
}
</style>
