// import React, { useState } from 'react';
// import './UserInvite.css';
// import axios from 'axios';
// import { useUser } from '../../context/UserContext'; // 根据实际路径调整

// const UserInvite = () => {
//   const { user } = useUser();
//   const [inviteCode, setInviteCode] = useState('');
//   const [loading, setLoading] = useState(false);

//   const handleGenerateInvite = async () => {
//     if (!user?.userId) {
//       alert('未获取到用户信息，无法生成邀请码');
//       return;
//     }

//     setLoading(true);
//     try {
//       const response = await axios.get('/echo/user/getInviteCode', {
//         params: { user_id: user.userId },
//       });
//       setInviteCode(response.data.invite_code);
//     } catch (error) {
//       console.error('生成邀请码失败：', error);
//       alert('生成邀请码失败，请稍后再试');
//     }
//     setLoading(false);
//   };

//   return (
//     <div className="user-invite-container">
//       <h2>邀请新用户</h2>
//       <button className="invite-button" onClick={handleGenerateInvite} disabled={loading}>
//         {loading ? '生成中...' : '生成邀请码'}
//       </button>
//       {inviteCode && (
//         <div className="invite-code">
//           邀请码：<span>{inviteCode}</span>
//         </div>
//       )}
//     </div>
//   );
// };

// export default UserInvite;


import React, { useState } from 'react';
import './UserInvite.css';
import axios from 'axios';
import { useUser } from '../../context/UserContext';

const UserInvite = () => {
  const { user } = useUser();
  const [inviteCode, setInviteCode] = useState('');
  const [loading, setLoading] = useState(false);

  const handleGenerateInvite = async () => {
    if (!user?.userId) {
      alert('未获取到用户信息，无法生成邀请码');
      return;
    }

    setLoading(true);
    try {
      const response = await axios.post('/echo/user/getInviteCode', {
        user_id: user.userId,
      });

      const data = response.data;

      if (data.status === 'success') {
        setInviteCode(data.invite_code);
      } else {
        alert(`生成失败：${data.message}`);
      }
    } catch (error) {
      console.error('生成邀请码失败：', error);
      alert('生成邀请码失败，请稍后再试');
    }
    setLoading(false);
  };

  return (
    <div className="user-invite-container">
      <h2>邀请新用户</h2>
      <button className="invite-button" onClick={handleGenerateInvite} disabled={loading}>
        {loading ? '生成中...' : '生成邀请码'}
      </button>
      {inviteCode && (
        <div className="invite-code">
          邀请码：<span>{inviteCode}</span>
        </div>
      )}
    </div>
  );
};

export default UserInvite;
