<template>
  <el-card v-loading="loading">
    <template #header>
      <div class="card-header">
        <span>用户UID设置</span>
        <el-button type="primary" :loading="saving" @click="handleSave">
          <el-icon><Check /></el-icon>保存配置
        </el-button>
      </div>
    </template>

    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      class="config-form"
    >
      <el-alert
        title="UID设置说明"
        type="info"
        :closable="false"
        show-icon
        style="margin-bottom: 20px;"
      >
        <template #default>
          <p>配置新用户注册时生成的UID格式。修改后仅对新注册用户生效。</p>
        </template>
      </el-alert>

      <el-form-item label="UID类型" prop="uid_type">
        <el-radio-group v-model="formData.uid_type">
          <el-radio value="1">真实ID</el-radio>
          <el-radio value="2">数字ID</el-radio>
          <el-radio value="3">随机字符和数字</el-radio>
        </el-radio-group>
        <div class="form-tip">
          <span v-if="formData.uid_type === '1'">使用数据库自增ID作为用户UID</span>
          <span v-else-if="formData.uid_type === '2'">生成指定长度的纯数字UID</span>
          <span v-else-if="formData.uid_type === '3'">生成指定长度的字母数字混合UID</span>
        </div>
      </el-form-item>

      <el-form-item 
        v-if="formData.uid_type !== '1'" 
        label="UID长度" 
        prop="uid_length"
      >
        <el-input-number
          v-model.number="formData.uid_length"
          :min="6"
          :max="20"
          placeholder="请输入UID长度"
          style="width: 200px"
        />
        <div class="form-tip">UID长度范围：6-20位</div>
      </el-form-item>

      <!-- UID预览 -->
      <el-form-item label="UID预览">
        <div class="uid-preview">
          <el-tag type="info" size="large">{{ uidPreview }}</el-tag>
        </div>
        <div class="form-tip">示例UID格式预览</div>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Check } from '@element-plus/icons-vue'
import { getUserConfigSetting, updateUserConfigSetting, type UserConfigSetting } from '@/api/business/config'

// 加载状态
const loading = ref(false)
const saving = ref(false)

// 表单引用
const formRef = ref<FormInstance>()

// 表单数据
interface FormDataType {
  uid_type: string
  uid_length: number
}

const formData = reactive<FormDataType>({
  uid_type: '1',
  uid_length: 8
})

// UID预览
const uidPreview = computed(() => {
  if (formData.uid_type === '1') {
    return '10001'
  } else if (formData.uid_type === '2') {
    return '0'.repeat(formData.uid_length).replace(/0/g, () => String(Math.floor(Math.random() * 10)))
  } else {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
    let result = ''
    for (let i = 0; i < formData.uid_length; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length))
    }
    return result
  }
})

// 表单验证规则
const formRules: FormRules = {
  uid_type: [
    { required: true, message: '请选择UID类型', trigger: 'change' }
  ],
  uid_length: [
    { type: 'number', min: 6, max: 20, message: 'UID长度必须在6-20之间', trigger: 'blur' }
  ]
}

// 加载配置数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await getUserConfigSetting()
    if (res.data?.value) {
      const data = res.data.value
      Object.assign(formData, {
        uid_type: data.uid_type || '1',
        uid_length: Number(data.uid_length) || 8
      })
    }
  } catch (error) {
    ElMessage.error('加载用户UID设置失败')
    console.error('加载用户UID设置失败:', error)
  } finally {
    loading.value = false
  }
}

// 保存配置
const handleSave = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
  } catch {
    ElMessage.warning('请检查表单填写是否正确')
    return
  }

  saving.value = true
  try {
    const submitData: UserConfigSetting = {
      uid_type: formData.uid_type,
      uid_length: String(formData.uid_length)
    }

    await updateUserConfigSetting(submitData)
    ElMessage.success('保存成功')
  } catch (error) {
    ElMessage.error('保存失败')
    console.error('保存用户UID设置失败:', error)
  } finally {
    saving.value = false
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.config-form {
  max-width: 600px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  margin-top: 4px;
}

.uid-preview {
  padding: 8px 0;
}

:deep(.el-alert p) {
  margin: 4px 0;
  line-height: 1.6;
}
</style>
