<template>
  <el-dialog
      :model-value="visible"
      title="系统管理"
      width="500px"
      @close="handleClose"
      :close-on-click-modal="false"
  >
    <el-form label-width="120px">
      <el-form-item label="开放注册">
        <el-switch v-model="isRegistrationEnabled" @change="handleToggleRegistration"></el-switch>
      </el-form-item>
      <el-form-item label="生成注册码">
        <el-button type="primary" @click="handleGenerateCode">生成</el-button>
      </el-form-item>
      <el-form-item v-if="generatedCode" label="新注册码">
        <el-input v-model="generatedCode" readonly>
          <template #append>
            <el-button @click="copyToClipboard(generatedCode)">复制</el-button>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import {
  getRegistrationStatus,
  toggleRegistration,
  generateRegistrationCode,
} from '@/api/CommonApi.js';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(['update:visible']);

const isRegistrationEnabled = ref(true);
const generatedCode = ref('');

watch(() => props.visible, (newVal) => {
  if (newVal) {
    fetchRegistrationStatus();
    generatedCode.value = ''; // Reset code when dialog opens
  }
});

const fetchRegistrationStatus = async () => {
  try {
    isRegistrationEnabled.value = await getRegistrationStatus();
  } catch (error) {
    // 错误已在 axios 拦截器中显示，这里不再重复显示
    console.error("Failed to fetch registration status:", error);
  }
};

const handleToggleRegistration = async (value) => {
  try {
    await toggleRegistration(value);
    ElMessage.success(`注册功能已${value ? '开启' : '关闭'}`);
  } catch (error) {
    // 错误已在 axios 拦截器中显示，这里不再重复显示
    isRegistrationEnabled.value = !value; // Revert on failure
  }
};

const handleGenerateCode = async () => {
  try {
    const code = await generateRegistrationCode();
    generatedCode.value = code;
    ElMessage.success('注册码生成成功');
  } catch (error) {
    // 错误已在 axios 拦截器中显示，这里不再重复显示
    console.error('生成注册码失败:', error);
  }
};

const copyToClipboard = (text) => {
  navigator.clipboard.writeText(text).then(() => {
    ElMessage.success('已复制到剪贴板');
  }, () => {
    ElMessage.error('复制失败');
  });
};

const handleClose = () => {
  emit('update:visible', false);
};
</script>
