<template>
  <el-dialog
    v-model="visible"
    :title="dialogType === 'add' ? '新增配置' : '编辑配置'"
    width="600px"
    align-center
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="配置标识" prop="key">
        <el-input v-model="formData.key" placeholder="请输入配置标识" />
      </el-form-item>
      <el-form-item label="配置标题" prop="name">
        <el-input v-model="formData.name" placeholder="请输入配置标题" />
      </el-form-item>
      <el-form-item label="组件类型" prop="input_type">
        <el-select v-model="formData.input_type" :options="inputComponent" />
      </el-form-item>
      <el-form-item
        label="组件数据"
        prop="config_select_data"
        v-if="['select', 'radio'].includes(formData.input_type)"
      >
        <el-row
          :gutter="10"
          class="mb-2"
          v-for="(item, index) in formData.config_select_data"
          :key="index"
        >
          <el-col :span="10">
            <el-input v-model="item.label" placeholder="请输入label"></el-input>
          </el-col>
          <el-col :span="10">
            <el-input v-model="item.value" placeholder="请输入value"></el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="danger" @click="removeConfigSelectData(index)">
              <template #icon>
                <ArtSvgIcon icon="ri:delete-bin-5-line" />
              </template>
            </el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-button type="primary" @click="addConfigSelectData">
              <template #icon>
                <ArtSvgIcon icon="ri:add-fill" />
              </template>
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="formData.sort" placeholder="请输入排序" />
      </el-form-item>
      <el-form-item label="描述" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入配置描述"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import api from '@/api/system/config'
  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>()

  interface ConfigSelectData {
    label: string
    value: string
  }

  const inputComponent = [
    { label: '文本框', value: 'input' },
    { label: '文本域', value: 'textarea' },
    { label: '下拉选择框', value: 'select' },
    { label: '单选框', value: 'radio' },
    { label: '图片上传', value: 'uploadImage' },
    { label: '文件上传', value: 'uploadFile' },
    { label: '富文本编辑器', value: 'wangEditor' }
  ]

  const addConfigSelectData = () => {
    formData.config_select_data.push({ label: '', value: '' })
  }

  const removeConfigSelectData = (index: number) => {
    formData.config_select_data.splice(index, 1)
  }

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

  /**
   * 表单验证规则
   */
  const rules = reactive<FormRules>({
    key: [{ required: true, message: '请输入配置标识', trigger: 'blur' }],
    name: [{ required: true, message: '请输入配置标题', trigger: 'blur' }],
    input_type: [{ required: true, message: '请输入组件类型', trigger: 'blur' }]
  })

  /**
   * 初始数据
   */
  const initialFormData = {
    id: null,
    group_id: null,
    key: '',
    value: '',
    name: '',
    input_type: 'input',
    config_select_data: [] as ConfigSelectData[],
    sort: 100,
    remark: ''
  }

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

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

  /**
   * 初始化页面数据
   */
  const initPage = async () => {
    // 先重置为初始值
    Object.assign(formData, initialFormData)
    formData.config_select_data = []
    // 如果有数据，则填充数据
    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.configSave(formData)
        ElMessage.success('新增成功')
      } else {
        await api.configUpdate(formData)
        ElMessage.success('修改成功')
      }
      emit('success')
      handleClose()
    } catch (error) {
      console.log('表单验证失败:', error)
    }
  }
</script>
