package com.corewing.app.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.corewing.app.entity.User;
import com.corewing.app.mapper.UserMapper;
import com.corewing.app.service.UserService;
import com.corewing.app.service.VerifyCodeService;
import com.corewing.app.util.I18nUtil;
import com.corewing.app.util.Ip2RegionUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;

/**
 * 应用用户 Service 实现类
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final VerifyCodeService verifyCodeService;
    private final Ip2RegionUtil ip2RegionUtil;

    public UserServiceImpl(VerifyCodeService verifyCodeService, Ip2RegionUtil ip2RegionUtil) {
        this.verifyCodeService = verifyCodeService;
        this.ip2RegionUtil = ip2RegionUtil;
    }

    @Override
    public User getByUsername(String username) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        return this.getOne(wrapper);
    }

    @Override
    public User getByAccount(String account) {
        if (!StringUtils.hasText(account)) {
            return null;
        }

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, account)
                .or()
                .eq(User::getEmail, account)
                .or()
                .eq(User::getTelephone, account);
        return this.getOne(wrapper);
    }

    @Override
    public User getByEmail(String email) {
        if (!StringUtils.hasText(email)) {
            return null;
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getEmail, email);
        return this.getOne(wrapper);
    }

    @Override
    public User getByTelephone(String telephone) {
        if (!StringUtils.hasText(telephone)) {
            return null;
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getTelephone, telephone);
        return this.getOne(wrapper);
    }

    @Override
    public String login(String account, String password) {
        // 查询用户（支持用户名/邮箱/手机号）
        User user = getByAccount(account);
        if (user == null) {
            throw new RuntimeException(I18nUtil.getMessage("error.user.not.found"));
        }

        // 验证密码（MD5加密）
        String encryptPassword = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        if (!encryptPassword.equals(user.getPassword())) {
            throw new RuntimeException(I18nUtil.getMessage("error.password.incorrect"));
        }

        // 检查用户状态
        if (user.getStatus() == 0) {
            throw new RuntimeException(I18nUtil.getMessage("error.account.disabled"));
        }

        // 登录成功，使用 Sa-Token 生成 token
        StpUtil.login(user.getId());
        return StpUtil.getTokenValue();
    }

    @Override
    public boolean register(User user, String code, String registerIp) {
        // 检查用户名是否已存在
        User existUser = getByUsername(user.getUsername());
        if (existUser != null) {
            throw new RuntimeException(I18nUtil.getMessage("error.username.exists"));
        }

        // 邮箱和手机号至少要有一个
        if (!StringUtils.hasText(user.getEmail()) && !StringUtils.hasText(user.getTelephone())) {
            throw new RuntimeException(I18nUtil.getMessage("error.email.or.phone.required"));
        }

        // 检查邮箱是否已存在
        if (StringUtils.hasText(user.getEmail())) {
            existUser = getByEmail(user.getEmail());
            if (existUser != null) {
                throw new RuntimeException(I18nUtil.getMessage("error.email.exists"));
            }
        }

        // 检查手机号是否已存在
        if (StringUtils.hasText(user.getTelephone())) {
            existUser = getByTelephone(user.getTelephone());
            if (existUser != null) {
                throw new RuntimeException(I18nUtil.getMessage("error.phone.exists"));
            }
        }

        // 验证验证码
        String account = StringUtils.hasText(user.getTelephone()) ? user.getTelephone() : user.getEmail();
        boolean codeValid = verifyCodeService.verifyCode(account, code, "register");
        if (!codeValid) {
            throw new RuntimeException(I18nUtil.getMessage("error.verify.code.invalid"));
        }

        // 密码加密（MD5）
        String encryptPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8));
        user.setPassword(encryptPassword);

        // 设置默认状态为启用
        if (user.getStatus() == null) {
            user.setStatus(1);
        }

        // 设置注册IP和归属地
        if (StringUtils.hasText(registerIp)) {
            user.setRegisterIp(registerIp);
            user.setRegisterRegion(ip2RegionUtil.getRegion(registerIp));
        }

        // 保存用户
        return this.save(user);
    }

    @Override
    public void updateLoginIp(Long userId, String loginIp) {
        User user = new User();
        user.setId(userId);
        user.setLoginIp(loginIp);
        this.updateById(user);
    }

    @Override
    public void updateLoginInfo(Long userId, String loginIp) {
        User user = new User();
        user.setId(userId);
        user.setLoginIp(loginIp);
        user.setLoginRegion(ip2RegionUtil.getRegion(loginIp));
        this.updateById(user);
    }
}
