<template>
	<el-dialog
		class="api-edit"
		v-model="showDialog"
		:title="`${formData.id ? '编辑' : '新增'}`"
		width="600px"
		:close-on-click-modal="false"
		:close-on-press-escape="false"
	>
		<el-form ref="formRef" :model="formData" :rules="ruleForm" label-width="100px">
			<el-form-item label="名称" prop="name">
				<el-input v-model.trim="formData.name" placeholder="输入名称" />
			</el-form-item>
			<el-form-item label="说明" prop="ext01">
				<el-input v-model="formData.ext01" type="textarea" :rows="3" />
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="showDialog = false">取消</el-button>
				<el-button type="primary" @click="onSubmit">确定</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick } from 'vue'
import { ruleRequired } from '/@/utils/validator'
import { ElMessage } from 'element-plus'
import api from '/@/api/modules/designer'

const emit = defineEmits(['getList'])

const showDialog = ref(false)
const formRef = ref()

const jsonData = `{"0":{"rule":"[]","options":"{\"form\":{\"inline\":false,\"hideRequiredAsterisk\":false,\"labelPosition\":\"right\",\"size\":\"default\",\"labelWidth\":\"125px\"},\"resetBtn\":{\"show\":false,\"innerText\":\"重置\"},\"submitBtn\":{\"show\":true,\"innerText\":\"提交\"}}"}}`

const baseForm = {
	id: undefined,
	name: null,
	content: jsonData,
	ext01: null,
}

const formData = reactive({
	...baseForm,
})

const ruleForm = {
	name: [ruleRequired('名称不能为空')],
	ext01: [ruleRequired('说明不能为空')],
}

const onSubmit = async () => {
	await formRef.value.validate()

  const theApi = formData.id ? api.edit : api.add

  await theApi(formData)

  ElMessage.success('操作成功')
  resetForm()
  showDialog.value = false
  emit('getList')
}

const resetForm = async () => {
	Object.assign(formData, { ...baseForm })
	formRef.value && formRef.value.resetFields()
}

const open = async (row: any) => {
	resetForm()
	showDialog.value = true
  nextTick(() => {
    if (row) {
      formData.id = row.id
      formData.name = row.name
      formData.content = row.content
      formData.ext01 = row.ext01
    }
	})
}

defineExpose({ open })
</script>
