<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="类型" prop="type" v-if="formType === 'create'">
        <div class="flex items-center">
          <el-radio v-model="formData.type" label="single" border>单次</el-radio>
          <el-radio v-model="formData.type" label="batch" border class="ml-20px">批量</el-radio>
        </div>
      </el-form-item>
      
      <el-form-item v-if="formType === 'update' || formData.type === 'single'" label="邀请码" prop="code">
        <el-input v-model="formData.code" placeholder="请输入邀请码" :disabled="formType === 'update'">
          <template #append>
            <el-button @click="generateRandomCode" :disabled="formType === 'update'">
              随机
            </el-button>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item v-else-if="formData.type === 'batch'" label="批量前缀" prop="code">
        <div class="flex items-center gap-10px">
          <el-input v-model="formData.code" placeholder="请输入批量前缀" class="flex-1" />
          <el-input-number v-model="formData.batchCount" :min="1" :max="50" placeholder="数量" style="width: 120px;">
            <template #suffix>
              <span>个</span>
            </template>
          </el-input-number>
        </div>
      </el-form-item>
      
      <el-form-item label="绑定角色" prop="roleIds">
        <el-select v-model="formData.roleIds" multiple placeholder="请选择绑定角色" >
          <el-option
            v-for="role in roleList"
            :key="role.id"
            :label="role.name"
            :value="role.id"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="有效期（天）" prop="validTime">
        <el-input-number v-model="formData.validTime" :min="1" :max="365">
          <template #suffix>
            <span>天</span>
          </template>
        </el-input-number>
      </el-form-item>
      
      <el-form-item label="状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择状态" disabled>
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.SYSTEM_INVITE_CODE_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading || formType === 'update'">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { InviteCodeApi, InviteCodeVO } from '@/api/system/invitecode'
import { getSimpleRoleList, RoleVO } from '@/api/system/role/index'
import { DICT_TYPE } from '@/utils/dict'
import { getStrDictOptions } from '@/utils/dict'

/** 邀请码 表单 */
defineOptions({ name: 'InviteCodeForm' })

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

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  code: undefined,
  type: 'single',
  batchCount: 1,
  roleIds: [],
  validTime: undefined,
  expireTime: undefined,
  useUserId: undefined,
  useUserTenantId: undefined,
  status: '1'
})
const formRules = reactive({
  type: [
    // 类型不再是必选，默认选中单次
  ],
  code: [
    { required: formData.value.type === 'single', message: '请输入邀请码', trigger: 'blur' },
    { min: 1, max: 10, message: '邀请码长度不能超过10位', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9]+$/, message: '邀请码只能包含英文和数字', trigger: 'blur' }
  ],
  roleIds: [
    { required: true, message: '请选择绑定角色', trigger: 'change' },
    { type: 'array', min: 1, message: '至少选择一个角色', trigger: 'change' }
  ],
  validTime: [
    { required: true, message: '请输入有效期', trigger: 'blur' },
    { type: 'number', min: 1, max: 365, message: '有效期必须在1-365天之间', trigger: 'blur' }
  ],
  batchCount: [
    { required: formData.value.type === 'batch', message: '请输入批量数量', trigger: 'blur' },
    { type: 'number', min: 1, max: 50, message: '批量数量必须在1-50之间', trigger: 'blur' },
    { type: 'number', integer: true, message: '批量数量必须是整数', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
})
const formRef = ref() // 表单 Ref
const roleList = ref<RoleVO[]>([])

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  
  // 获取角色列表
  await getRoleList()
  
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await InviteCodeApi.getInviteCode(id)
      // 将字符串格式的roleIds转换为数组
      if (data.roleIds && typeof data.roleIds === 'string') {
        data.roleIds = data.roleIds.split(',').map(Number)
      }
      formData.value = data
    } finally {
      formLoading.value = false
    }
  }
}

/** 获取角色列表 */
const getRoleList = async () => {
  try {
    roleList.value = await getSimpleRoleList()
  } catch (error) {
    console.error('获取角色列表失败:', error)
    message.error('获取角色列表失败')
  }
}

/** 生成随机邀请码 */
const generateRandomCode = () => {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  for (let i = 0; i < 10; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length))
  }
  formData.value.code = result
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  
  // 准备提交数据
  const submitData = { ...formData.value }
  
  // 将角色ID数组转换为逗号分隔的字符串
  if (Array.isArray(submitData.roleIds)) {
    submitData.roleIds = submitData.roleIds.join(',')
  }
  
  // 提交请求
  formLoading.value = true
  try {
    const data = submitData as unknown as InviteCodeVO
    if (formType.value === 'create') {
      await InviteCodeApi.createInviteCode(data)
      message.success(t('common.createSuccess'))
    } else {
      await InviteCodeApi.updateInviteCode(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    code: undefined,
    type: 'single',
    batchCount: 1,
    roleIds: [],
    validTime: undefined,
    expireTime: undefined,
    useUserId: undefined,
    useUserTenantId: undefined,
    status: '1'
  }
  formRef.value?.resetFields()
}
</script>
