<template>
  <div class="login-container">
    <p class="login-form-title"><h2>新账号注册</h2></p>
    <p class="login-form-title-l2"><h4>基于分布式WebSocket的在线IM对话软件</h4></p>
    <div style="height: 80px; text-align: center">
      <a-upload
        name="avatar"
        :showUploadList="false"
        :beforeUpload="beforeUpload"
        :customRequest="handleUpload"
      >
        <a-avatar :src="avatarUrl" :size="64" style="background-color: black; color: white">
            上传头像
        </a-avatar>
      </a-upload>
    </div>
    <a-input class="oauth-input" v-model:value="userName" placeholder="请设置昵称" />
    <a-input class="oauth-input" v-model:value="mobile" placeholder="请输入手机号" />
    <div class="captcha-container">
      <a-input class="oauth-input" v-model:value="picCheckCode" placeholder="数字验证码" />
      <img
        :src="picCheckCodeImage"
        alt="验证码"
        @click="refreshPicCheckCode"
        style="width: 100px; cursor: pointer; margin-left: 10px"
      />
    </div>
    <a-input class="oauth-input" v-model:value="password" placeholder="请输入密码" type="password" autocomplete="new-password" :style="{ backgroundColor: 'transparent' }"/>
    <a-button type="primary" class="login-btn" @click="register">注册新账号</a-button>
    <router-link :to="{ path: '/', query: { call_back: callBackUrl } }"  tag="a">
      <a-button type="link" style="line-height: 40px; color: black;">有账号，立即登录</a-button>
    </router-link>
  </div>
</template>

<script setup>
import axios from 'axios';
import { ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { message } from 'ant-design-vue';

const userName = ref('');
const mobile = ref('');
const password = ref('');
const avatarUrl = ref('');
const picCheckCode = ref('');
const picCheckCodeImage = ref(`/sso-service/oauth/valid/code`); // 初始的验证码图片地址
const route = useRoute()
const router = useRouter()
const callBackUrl = ref(route.query.call_back || new URLSearchParams(window.location.search).get('call_back'));
const register = async () => {
  if (!avatarUrl.value) {
    message.error('请上传头像');
    return;
  }
  if (!userName.value) {
    message.error('请输入用户名');
    return;
  }
  if (!mobile.value) {
    message.error('请输入手机号');
    return;
  }
  if (!password.value) {
    message.error('请输入密码');
    return;
  }
  if (!picCheckCode.value) {
    message.error('请输入验证码');
    return;
  }
try {
  // 调用接口发送登录请求
  const response = await axios.post(`/sso-service/oauth/register`, {
    photo: avatarUrl.value,
    picCheckCode: picCheckCode.value,
    userName: userName.value,
    mobile: mobile.value,
    password: password.value
  });
  if (response.data.code === 200) {
      // 注册成功，显示 toast 提示
      message.success('注册成功, 请重新登录');
      // 路由跳转到 /，重新登录
      router.push({
        path: '/',
        query: {
          call_back: callBackUrl.value
        }
      });
  } else {
    message.error(response.data.msg || '注册失败');
  }
} catch (error) {
  // 处理错误，例如显示错误消息

}
};
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG 格式的图片');
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB');
    return false;
  }
  return isJpgOrPng && isLt2M;
};

const handleUpload = (options) => {
  const { file } = options;
  const formData = new FormData();
  formData.append('file', file);
  axios.post(`/sso-service/file/upload`, formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
      'upload-path': 'images/avatar'
    }
  }).then(response => {
    if (response.data.code === 200) {
      avatarUrl.value = response.data.data.url;
      message.success('头像上传成功');
    } else {
      message.error('头像上传失败');
    }
  }).catch(error => {
    console.error('头像上传出错:', error);
    message.error('头像上传出错，请稍后重试');
  });
};
const refreshPicCheckCode = async () => {
  try {
    const response = await axios.get(`/sso-service/oauth/valid/code`, {
      responseType: 'blob'
    });
    const imageUrl = URL.createObjectURL(response.data);
    picCheckCodeImage.value = imageUrl;
  } catch (error) {
    console.error('刷新验证码出错:', error);
    message.error('刷新验证码出错，请稍后重试');
  }
};
</script>

<style scoped>
* {
  margin: 0px;
  padding: 0px;
}
.login-container {
  width: 400px;
  height: 620px;
  background-color: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .1), 0 1px 2px -1px rgba(0, 0, 0, .1);
  border: 1px solid #c0c5cd;
  padding: 40px;
}
.login-form-title {
  line-height: 60px;
}
.login-form-title-l2 {
  line-height: 30px;
  margin-bottom: 20px;
  color: rgb(84, 84, 84);
}
.login-btn {
  width: 100%; 
  background-color: black; 
  height: 50px;
}
.oauth-input {
  height: 50px;
  text-indent: 2em;
  margin-bottom: 10px;
  overflow: hidden;
}
.oauth-input input {
  margin-left: 20px;
}
.captcha-container {
  display: flex;
  align-items: center;
}
</style>
