<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="30%">
    <el-form :model="formData" :rules="formRules" ref="formRef">
      <el-form-item label="等级" prop="levelConfigId">
        <el-select v-model="formData.levelConfigId">
          <el-option
            v-for="item in levelConfigList"
            :key="item.id"
            :label="item.displayName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submit" :disabled="submitDisable">确定</el-button>
      <el-button type="default" @click="dialogVisible = false">取消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts" name="UserLevelTable">
import { ElMessage } from 'element-plus';
import { updateUserLevel } from '@/api/member/user'
import { LevelConfigVO, getLevelConfigPage } from '@/api/member/levelConfig'
defineOptions({ name: 'UserLevelTable' })
const { t } = useI18n() // 国际化
const submitDisable = ref(false) // 提交按钮是否禁用

const formRef = ref()
const formData = ref({
  userId: undefined,
  levelConfigId: undefined,
}) // 表单数据

// 重置表单
const resetForm = () => {
  formData.value = {
    userId: undefined,
    levelConfigId: undefined,
  }
}

const formRules = reactive({
  levelConfigId: [{ required: true, message: '用户等级不能为空', trigger: 'blur' }],
})
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  resetForm()
  formData.value.userId = id as any
  await pageLevelConfig()
  dialogVisible.value = true
  dialogTitle.value = '用户等级变更'
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const emit = defineEmits(['success']) 

const levelConfigList = ref<Array<LevelConfigVO>>([]) // 等级配置
const pageLevelConfig = async () => {
  const params = {
    pageIndex: 1,
    pageSize: 20,
  }
  try {
    const res = await getLevelConfigPage(params)
    levelConfigList.value = res.list
  } catch (error) {
    console.log(error)
  }
}


const submit = async () => {
  const valid = await formRef.value.validate()
  if (!valid) {
    return
  }
  submitDisable.value = true
  try {
    await updateUserLevel(formData.value)
    ElMessage.success(t('common.success'))
    dialogVisible.value = false
    emit('success')
  } finally {
    submitDisable.value = false
  }
}
</script>