<template>
{% if component_type == 1 %}
  <el-dialog
{% else %}
  <el-drawer
{% endif %}
    v-model="visible"
    :title="dialogType === 'add' ? '新增{{menu_name}}' : '编辑{{menu_name}}'"
{% if is_full == 2 %}
{% if component_type == 1 %}
    :fullscreen="true"
{% else %}
    size="100%"
{% endif %}
{% else %}
{% if component_type == 1 %}
    width="{{form_width}}px"
{% else %}
    :size="{{form_width}}"
{% endif %}
{% endif %}
    align-center
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
{% for column in columns %}
{% if column.is_insert == 2 %}
{% if column.view_type == 'input' %}
      <el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
        <el-input v-model="formData.{{column.column_name}}" placeholder="请输入{{column.column_comment}}" />
      </el-form-item>
{% endif %}
{% if column.view_type == 'password' %}
      <el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
        <el-input v-model="formData.{{column.column_name}}" type="password" placeholder="请输入{{column.column_comment}}" show-password />
      </el-form-item>
{% endif %}
{% if column.view_type == 'textarea' %}
      <el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
        <el-input v-model="formData.{{column.column_name}}" type="textarea" :rows="2" placeholder="请输入{{column.column_comment}}" />
      </el-form-item>
{% endif %}
{% if column.view_type == 'inputNumber' %}
      <el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
        <el-input-number v-model="formData.{{column.column_name}}" placeholder="请输入{{column.column_comment}}" />
      </el-form-item>
{% endif %}
{% if column.view_type == 'inputTag' %}
      <el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
        <el-input-tag v-model="formData.{{column.column_name}}" placeholder="请输入{{column.column_comment}}" clearable />
      </el-form-item>
{% endif %}
{% if column.view_type == 'switch' %}
      <el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
        <sa-switch v-model="formData.{{column.column_name}}" />
      </el-form-item>
{% endif %}
{% if column.view_type == 'slider' %}
      <el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
        <el-slider v-model="formData.{{column.column_name}}" placeholder="请输入{{column.column_comment}}" />
      </el-form-item>
{% endif %}
{% if column.view_type == 'select' %}
      <el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
        <el-select v-model="formData.{{column.column_name}}" :options="[]" placeholder="请选择{{column.column_comment}}" clearable />
      </el-form-item>
{% endif %}
{% if column.view_type == 'saSelect' %}
      <el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
        <sa-select v-model="formData.{{column.column_name}}" dict="{{column.dict_type}}" placeholder="请选择{{column.column_comment}}" clearable />
      </el-form-item>
{% endif %}
{% if column.view_type == 'treeSelect' and column.column_name == options.tree_parent_id %}
      <el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
        <el-tree-select
          v-model="formData.{{column.column_name}}"
          :data="optionData.treeData"
          placeholder="请选择{{column.column_comment}}"
          check-strictly
          clearable
        />
      </el-form-item>
{% endif %}
{% if column.view_type == 'treeSelect' and column.column_name != options.tree_parent_id %}
      <el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
        <el-tree-select v-model="formData.{{column.column_name}}" :data="[]" placeholder="请选择{{column.column_comment}}" clearable />
      </el-form-item>
{% endif %}
{% if column.view_type == 'radio' %}
      <el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
        <sa-radio v-model="formData.{{column.column_name}}" dict="{{column.dict_type}}" />
      </el-form-item>
{% endif %}
{% if column.view_type == 'checkbox' %}
      <el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
        <sa-checkbox v-model="formData.{{column.column_name}}" dict="{{column.dict_type}}" />
      </el-form-item>
{% endif %}
{% if column.view_type == 'date' %}
      <el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
        <el-date-picker v-model="formData.{{column.column_name}}" type="{{column.options.mode}}" placeholder="请选择{{column.column_comment}}" />
      </el-form-item>
{% endif %}
{% if column.view_type == 'time' %}
      <el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
        <el-time-picker v-model="formData.{{column.column_name}}" placeholder="请选择{{column.column_comment}}" />
      </el-form-item>
{% endif %}
{% if column.view_type == 'rate' %}
      <el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
        <el-rate v-model="formData.{{column.column_name}}" />
      </el-form-item>
{% endif %}
{% if column.view_type == 'cascader' %}
      <el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
        <el-cascader v-model="formData.{{column.column_name}}" :options="[]" placeholder="请选择{{column.column_comment}}" allow-clear />
      </el-form-item>
{% endif %}
{% if column.view_type == 'userSelect' %}
      <el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
        <sa-user v-model="formData.{{column.column_name}}" :multiple="{{column.options.multiple|bool}}" />
      </el-form-item>
{% endif %}
{% if column.view_type == 'uploadImage' %}
      <el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
        <sa-image-upload v-model="formData.{{column.column_name}}" :limit="{{column.options.limit|formatNumber}}" :multiple="{{column.options.multiple|bool}}" />
      </el-form-item>
{% endif %}
{% if column.view_type == 'imagePicker' %}
      <el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
        <sa-image-picker v-model="formData.{{column.column_name}}" :limit="{{column.options.limit|formatNumber}}" :multiple="{{column.options.multiple|bool}}" />
      </el-form-item>
{% endif %}
{% if column.view_type == 'uploadFile' %}
      <el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
        <sa-file-upload v-model="formData.{{column.column_name}}" :limit="{{column.options.limit|formatNumber}}" :multiple="{{column.options.multiple|bool}}" />
      </el-form-item>
{% endif %}
{% if column.view_type == 'chunkUpload' %}
      <el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
        <sa-chunk-upload v-model="formData.{{column.column_name}}" :limit="{{column.options.limit|formatNumber}}" :multiple="{{column.options.multiple|bool}}" />
      </el-form-item>
{% endif %}
{% if column.view_type == 'editor' %}
      <el-form-item label="{{column.column_comment}}" prop="{{column.column_name}}">
        <sa-editor v-model="formData.{{column.column_name}}" height="{{column.options.height}}px" />
      </el-form-item>
{% endif %}
{% endif %}
{% endfor %}
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
    </template>
{% if component_type == 1 %}
  </el-dialog>
{% else %}
  </el-drawer>
{% endif %}
</template>

<script setup lang="ts">
  import api from '../../../api/{{package_name}}/{{business_name}}'
  import { ElMessage } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'

  interface Props {
    modelValue: boolean
    dialogType: string
    data?: Record<string, any>
  }

  interface Emits {
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
  }

  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    dialogType: 'add',
    data: undefined
  })

  const emit = defineEmits<Emits>()

  const formRef = ref<FormInstance>()
{% if tpl_category == 'tree' %}
  const optionData = reactive({
    treeData: <any[]>[]
  })
{% endif %}

  /**
   * 弹窗显示状态双向绑定
   */
  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
  })

  /**
   * 表单验证规则
   */
  const rules = reactive<FormRules>({
{% for column in columns %}
{% if column.is_required == 2 and column.is_pk == 1  %}
    {{column.column_name}}: [{ required: true, message: '{{column.column_comment}}必需填写', trigger: 'blur' }],
{% endif %}
{% endfor %}
  })

  /**
   * 初始数据
   */
  const initialFormData = {
{% for column in columns %}
{% if column.is_pk == 2 %}
    {{column.column_name}}: null,
{% elseif column.is_insert == 2 %}
{% if column.column_type == 'int' or column.column_type == 'smallint' or column.column_type == 'tinyint' %}
    {{column.column_name}}: {{column.default_value | parseNumber}},
{% elseif column.view_type == 'inputTag' or column.view_type == 'checkbox' or column.options.limit > 1 %}
    {{column.column_name}}: [],
{% elseif column.view_type == 'userSelect' %}
    {{column.column_name}}: null,
{% else %}
    {{column.column_name}}: '{{column.default_value}}',
{% endif %}
{% endif %}
{% endfor %}
  }

  /**
   * 表单数据
   */
  const formData = reactive({ ...initialFormData })

  /**
   * 监听弹窗打开，初始化表单数据
   */
  watch(
    () => props.modelValue,
    (newVal) => {
      if (newVal) {
        initPage()
      }
    }
  )

  /**
   * 初始化页面数据
   */
  const initPage = async () => {
    // 先重置为初始值
    Object.assign(formData, initialFormData)
{% if tpl_category == 'tree' %}
    // 初始化树形数据
    const data = await api.list({ tree: true })
    optionData.treeData = [
      {
        id: 0,
        value: 0,
        label: '无上级分类',
        children: data
      }
    ]
{% endif %}
    // 如果有数据，则填充数据
    if (props.data) {
      await nextTick()
      initForm()
    }
  }

  /**
   * 初始化表单数据
   */
  const initForm = () => {
    if (props.data) {
      for (const key in formData) {
        if (props.data[key] != null && props.data[key] != undefined) {
          ;(formData as any)[key] = props.data[key]
        }
      }
    }
  }

  /**
   * 关闭弹窗并重置表单
   */
  const handleClose = () => {
    visible.value = false
    formRef.value?.resetFields()
  }

  /**
   * 提交表单
   */
  const handleSubmit = async () => {
    if (!formRef.value) return
    try {
      await formRef.value.validate()
      if (props.dialogType === 'add') {
        await api.save(formData)
        ElMessage.success('新增成功')
      } else {
        await api.update(formData)
        ElMessage.success('修改成功')
      }
      emit('success')
      handleClose()
    } catch (error) {
      console.log('表单验证失败:', error)
    }
  }
</script>
