package com.haha.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.haha.common.vo.Result;
import com.haha.entity.User;
import com.haha.service.LoginService;
import com.haha.service.UserService;
import com.haha.common.vo.LoginVO;
import com.haha.common.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {
    
    @Autowired
    private UserService userService;
    
    @Override
    public Result<LoginVO> loginByPassword(String phone, String password) {
        try {
            // 临时方案：硬编码测试账号
            // 注意：生产环境必须使用数据库存储的加密密码，并使用BCrypt等安全算法验证
            final String TEST_PHONE = "13018061579";
            final String TEST_PASSWORD = "abc123";
            
            if (!TEST_PHONE.equals(phone) || !TEST_PASSWORD.equals(password)) {
                return Result.error(401, "手机号或密码错误");
            }
            
            // 根据手机号查找或创建用户
            User user = userService.getUserByPhone(phone);
            if (user == null) {
                // 创建新用户
                user = new User();
                user.setPhone(phone);
                user.setNickname("用户" + phone.substring(7));
                userService.save(user);
            }
            
            // 使用Sa-Token进行登录，生成token
            StpUtil.login(user.getId());
            String token = StpUtil.getTokenValue();
            
            // 构建返回数据
            UserVO userVO = UserVO.builder()
                    .id(user.getId())
                    .phone(user.getPhone())
                    .nickname(user.getNickname())
                    .build();
            
            LoginVO loginVO = LoginVO.builder()
                    .token(token)
                    .userInfo(userVO)
                    .build();
            
            return Result.success("登录成功", loginVO);
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(500, "登录失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<LoginVO> wechatPhoneLogin(String code, String encryptedData, String iv) {
        try {
            // 暂时简化实现，模拟微信手机号登录
            // 实际项目中需要使用微信小程序SDK解密获取手机号
            String phoneNumber = "13800138000";
            String openid = "mock_openid_" + System.currentTimeMillis();
            
            // 根据手机号查找或创建用户
            User user = userService.getUserByPhone(phoneNumber);
            if (user == null) {
                // 创建新用户
                user = new User();
                user.setPhone(phoneNumber);
                user.setOpenid(openid);
                user.setNickname("用户" + phoneNumber.substring(7));
                userService.save(user);
            } else {
                // 更新用户的openid
                if (!openid.equals(user.getOpenid())) {
                    user.setOpenid(openid);
                    userService.updateById(user);
                }
            }
            
            // 使用Sa-Token进行登录，生成token
            StpUtil.login(user.getId());
            String token = StpUtil.getTokenValue();
            
            // 构建返回数据
            UserVO userVO = UserVO.builder()
                    .id(user.getId())
                    .phone(user.getPhone())
                    .nickname(user.getNickname())
                    .build();
            
            LoginVO loginVO = LoginVO.builder()
                    .token(token)
                    .userInfo(userVO)
                    .build();
            
            return Result.success("登录成功", loginVO);
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(500, "登录失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<Map<String, Object>> getUserInfo(String userId) {
        try {
            User user = userService.getById(userId);
            if (user == null) {
                return Result.error(404, "用户不存在");
            }
            
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", user.getId());
            userInfo.put("phone", user.getPhone());
            userInfo.put("nickname", user.getNickname());
            userInfo.put("openid", user.getOpenid());
            
            return Result.success("获取用户信息成功", userInfo);
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(500, "获取用户信息失败：" + e.getMessage());
        }
    }
}
