<script setup lang="ts">
import type { BasicForm, AdvancedForm } from '@/types/form'
import type { DialogProps } from 'element-plus'

interface Props {
  modelValue: boolean
  dialogConfig?: DialogProps
  formConfig: BasicForm | AdvancedForm
  formData: any
  create: Function
  update: Function
  advanced?: boolean
}

const props = defineProps<Props>()
const emits = defineEmits(['update:modelValue', 'success'])

const formInitData = ref({})
watchEffect(() => {
  console.log(props.formData)
  formInitData.value = props.formData
})

const formRef = ref()

const dialogTitle = computed(() => (props.formData.id ? '编辑' : '新增'))
const dialogVisible = computed({
  get: () => props.modelValue,
  set: value => emits('update:modelValue', value)
})

const closeDialog = () => {
  dialogVisible.value = false
  formInitData.value = {}
}

const submit = async () => {
  const res = await formRef.value.submit()
  if (res) {
    closeDialog()
    emits('success')
  }
}
</script>

<template>
  <el-dialog
    draggable
    :title="dialogTitle"
    v-bind="dialogConfig"
    v-model="dialogVisible"
    @close="closeDialog"
    :close-on-click-modal="false"
  >
    <pro-form
      ref="formRef"
      :formConfig="formConfig"
      :formData="formInitData"
      :create="create"
      :update="update"
      :advanced="advanced"
    />

    <template #footer>
      <el-button icon="Close" @click="closeDialog">取消</el-button>
      <el-button icon="Check" type="primary" @click="submit">保存</el-button>
    </template>
  </el-dialog>
</template>

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