<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="800">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="80px"
    >
      <el-form-item label="参数名称" prop="sysAttrName">
        <el-input v-model="formData.sysAttrName" placeholder="请输入参数名称" />
      </el-form-item>
      <el-form-item label="参数键名" prop="sysAttrKey">
        <el-input v-model="formData.sysAttrKey" placeholder="请输入参数键名" />
      </el-form-item>
      <el-form-item label="参数类型" prop="sysAttrType">
        <el-select v-model="formData.sysAttrType" clearable placeholder="请选择参数类型">
          <el-option
            v-for="(dict, index) in getIntDictOptions(DICT_TYPE.SYS_TYPE)"
            :key="index"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="键值类型" prop="inputType">
        <el-radio-group v-model="inputType" @change="handleInputTypeChange">
          <el-radio label="text">文字</el-radio>
          <el-radio label="image">图片</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="参数键值" prop="sysAttrValue">
        <UploadImg
          v-if="inputType === 'image'"
          v-model="formData.sysAttrValue"
        />
        <el-input
          v-else
          type="textarea"
          :rows="4"
          v-model="formData.sysAttrValue"
          placeholder="请输入参数键值"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as ConfigApi from '@/api/basic/configuration'


defineOptions({ name: 'SystemConfigForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const inputType = ref('text') // 输入类型：text - 文字；image - 图片
const formData = ref({
  sysAttrId: undefined,
  sysAttrName: '',
  sysAttrKey: '',
  sysAttrType: undefined,
  sysAttrValue: '',
  remark: ''
})
const formRules = reactive({
  sysAttrName: [{ required: true, message: '参数名称不能为空', trigger: 'blur' }],
  sysAttrKey: [{ required: true, message: '参数键名不能为空', trigger: 'blur' }],
  sysAttrValue: [{ required: true, message: '参数键值不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ConfigApi.selectIsSystemAttributeById(id)
      // 如果值是图片，设置输入类型为图片
      if (isImageUrl(formData.value.sysAttrValue)) {
        inputType.value = 'image'
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    if (formType.value === 'create') {
      await ConfigApi.insertIsSystemAttribute(data)
      message.success(t('common.createSuccess'))
    } else {
      await ConfigApi.updateIsSystemAttribute(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    sysAttrId: undefined,
    sysAttrName: '',
    sysAttrKey: '',
    sysAttrType: undefined,
    sysAttrValue: '',
    remark: ''
  }
  inputType.value = 'text'
  formRef.value?.resetFields()
}

/** 处理输入类型变更 */
const handleInputTypeChange = () => {
  formData.value.sysAttrValue = ''
}


/** 判断是否为图片URL */
const isImageUrl = (url: string) => {
  if (typeof url !== 'string') return false
  return /\.(jpg|jpeg|png|gif|webp|bmp)$/i.test(url)
}
</script>
