package com.ruoyi.ai.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.ai.domain.*;
import com.ruoyi.ai.domain.enums.AiConfigEnum;
import com.ruoyi.ai.mapper.AiRechargeMapper;
import com.ruoyi.ai.mapper.AiUserMapper;
import com.ruoyi.ai.service.*;
import com.ruoyi.common.constant.BalanceChangerConstants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.entity.AiUser;
import com.ruoyi.common.core.domain.model.LoginAiUser;
import com.ruoyi.common.core.domain.model.LoginAiUserBody;
import com.ruoyi.common.core.domain.model.RegisterAiUserBody;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.mapper.SysConfigMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ai-用户信息Service业务层处理
 *
 * @author shi
 * @date 2025-11-12
 */
@Service
public class AiUserServiceImpl implements IAiUserService {

    @Autowired
    private AiUserMapper aiUserMapper;

    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Autowired
    private EmailVerifyService emailVerifyService;

    @Autowired
    private IAiBalanceChangeRecordService balanceChangeRecordService;

    @Autowired
    private IAiRebateRecordService aiRebateRecordService;

    @Autowired
    private IAiStatisticsService aiStatisticsService;

    @Autowired
    private IAiSampleAmountRecordService aiSampleAmountRecordService;

    @Autowired
    private AiRechargeMapper aiRechargeMapper;


    /**
     * 查询ai-用户信息
     *
     * @param id ai-用户信息主键
     * @return ai-用户信息
     */
    @Override
    public AiUser selectAiUserById(Long id) {
        return aiUserMapper.selectAiUserById(id);
    }

    @Override
    public AiUser getUserInfo(Long id) {
        return aiUserMapper.getUserInfo(id);
    }

    /**
     * 查询ai-用户信息列表
     *
     * @param aiUser ai-用户信息
     * @return ai-用户信息
     */
    @Override
    public List<AiUser> selectAiUserList(AiUser aiUser) {
        return aiUserMapper.selectAiUserList(aiUser);
    }

    /**
     * 分页查询ai-用户信息列表
     *
     * @param aiUser ai-用户信息
     * @return ai-用户信息
     */
    @Override
    public IPage<AiUser> selectAiUserPage(Page page, AiUser aiUser) {
        LambdaQueryWrapper<AiUser> query = Wrappers.lambdaQuery(aiUser);
        query.eq(AiUser::getDelFlag, "0");
        return aiUserMapper.selectPage(page, query);
    }

    /**
     * 新增ai-用户信息
     *
     * @param aiUser ai-用户信息
     * @return 结果
     */
    @Override
    public int insertAiUser(AiUser aiUser) {
        aiUser.setDelFlag("0");
        aiUser.setCreateBy(SecurityUtils.getUsername());
        aiUser.setCreateTime(DateUtils.getNowDate());
        return aiUserMapper.insert(aiUser);
    }

    /**
     * 修改ai-用户信息
     *
     * @param aiUser ai-用户信息
     * @return 结果
     */
    @Override
    public int updateAiUser(AiUser aiUser) {
        aiUser.setUpdateTime(DateUtils.getNowDate());
        return aiUserMapper.updateById(aiUser);
    }

    @Override
    public int countAiUserByDeptId(Long deptId) {
        if (deptId == null) {
            return 0;
        }
        return aiUserMapper.countAiUserByDeptId(deptId);
    }

    @Override
    public int updateAiUserDept(Long userId, Long deptId) {
        return aiUserMapper.updateAiUserDeptId(userId, deptId);
    }

    /**
     * 批量删除ai-用户信息
     *
     * @param ids 需要删除的ai-用户信息主键
     * @return 结果
     */
    @Override
    public int deleteAiUserByIds(Long[] ids) {

        return aiUserMapper.deleteBatchIds(ListUtils.arrayToList(ids));
    }

    /**
     * 删除ai-用户信息信息
     *
     * @param id ai-用户信息主键
     * @return 结果
     */
    @Override
    public int deleteAiUserById(Long id) {
        return aiUserMapper.deleteById(id);
    }

    @Override
    public int updateUserStatus(AiUser aiUser) {
        return aiUserMapper.updateById(aiUser);
    }

    @Override
    @Transactional
    public AiUser registerAiUser(RegisterAiUserBody registerAiUserBody) {
        // 判断用户名是否重复
        if (getUserCountByUserName(registerAiUserBody.getUsername()) > 0) {
            throw new ServiceException(MessageUtils.message("user.username.exists", registerAiUserBody.getUsername()), HttpStatus.CONFLICT);
        }
        // 判断邮箱是否重复
        if (getUserCountByEmail(registerAiUserBody.getEmail()) > 0) {
            throw new ServiceException(MessageUtils.message("user.email.registered"), HttpStatus.CONFLICT);
        }
        boolean b = emailVerifyService.verifyCode(registerAiUserBody.getEmail(), registerAiUserBody.getCode());
        if (!b) {
            throw new ServiceException(MessageUtils.message("email.verification.code.error"), HttpStatus.BAD_REQUEST);
        }
        AiUser aiUser = new AiUser();
        aiUser.setUsername(registerAiUserBody.getUsername());
        aiUser.setNickname(registerAiUserBody.getNickname());
        aiUser.setGender(registerAiUserBody.getGender());
        aiUser.setAvatar(registerAiUserBody.getAvatar());
        aiUser.setPhone(registerAiUserBody.getPhone());
        aiUser.setEmail(registerAiUserBody.getEmail());
        aiUser.setBirthday(registerAiUserBody.getBirthday());
        aiUser.setCreateTime(DateUtils.getNowDate());
        aiUser.setUserId(generateUuiD());
        String ip = IpUtils.getIpAddr();
        String country = IpCountryQueryByApi.getIpCountry(ip);
        aiUser.setIp(ip);
        aiUser.setCountry(country);
        // 获取上级ID
        AiUser user = getUserByInvitationCode(registerAiUserBody.getInvitationCode());
        if (user != null) {
            aiUser.setSuperiorId(user.getId());
        }
        aiUser.setInvitationCode(generateUniqueString());
        aiUser.setPassword(SecurityUtils.encryptPassword(registerAiUserBody.getPassword()));
        aiUser.setSource(registerAiUserBody.getSource());
        // 新增用户
        aiUserMapper.insert(aiUser);

        // 新增访客统计
        AiStatistics aiStatistics = new AiStatistics();
        aiStatistics.setSource(registerAiUserBody.getSource());
        aiStatistics.setAddUserCount(1L);
        aiStatisticsService.saveOrUpdateData(aiStatistics);
        return aiUser;
    }

    private String generateUniqueString() {
        // 初始长度为8
        int currentLength = 8;
        // 记录当前长度下的连续重复次数
        int duplicateCount = 0;

        while (true) {
            // 生成一个当前长度的随机字符串
            String newString = RandomStringUtil.generateRandomString(currentLength);
            // 检查是否已经存在
            if (!getUserCountByInvitationCode(newString)) {
                return newString;
            } else {
                // 如果存在，增加重复计数
                duplicateCount++;
                // 如果连续重复达到3次
                if (duplicateCount >= 3) {
                    // 增加长度
                    currentLength++;
                    // 重置重复计数
                    duplicateCount = 0;
                    System.out.println("连续3次重复，将字符串长度增加到 " + currentLength + " 位。");
                }
            }
        }
    }

    private String generateUuiD() {
        while (true) {
            // 生成一个当前长度的随机字符串
            String newString = RandomStringUtil.generateRandomUUIDString();
            // 检查是否已经存在
            if (!getUserCountByUuid(newString)) {
                return newString;
            }
        }
    }


    /**
     * 通过邀请码获取用户
     *
     * @param invitationCode
     * @return
     */
    private AiUser getUserByInvitationCode(String invitationCode) {
        LambdaQueryWrapper<AiUser> query = Wrappers.lambdaQuery();
        query.eq(AiUser::getInvitationCode, invitationCode);
        query.eq(AiUser::getDelFlag, 0);
        return aiUserMapper.selectOne(query);
    }

    private Long getUserCountByUserName(String username) {
        QueryWrapper<AiUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        queryWrapper.eq("del_flag", "0");
        return aiUserMapper.selectCount(queryWrapper);
    }

    @Override
    public Long getUserCountByEmail(String email) {
        QueryWrapper<AiUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email);
        queryWrapper.eq("del_flag", "0");
        return aiUserMapper.selectCount(queryWrapper);
    }

    @Override
    public AiUser getUserByEmail(String email) {
        QueryWrapper<AiUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email);
        queryWrapper.eq("del_flag", "0");
        return aiUserMapper.selectOne(queryWrapper);
    }

    public Boolean getUserCountByInvitationCode(String invitationCode) {
        QueryWrapper<AiUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("invitation_code", invitationCode);
        return aiUserMapper.selectCount(queryWrapper) > 0;
    }

    public Boolean getUserCountByUuid(String uuid) {
        QueryWrapper<AiUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", uuid);
        return aiUserMapper.selectCount(queryWrapper) > 0;
    }

    @Override
    public LoginAiUser loginAiUser(LoginAiUserBody loginAiUserBody) {
        QueryWrapper<AiUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", loginAiUserBody.getUsername()).or().eq("email", loginAiUserBody.getEmail());
        AiUser aiUser = aiUserMapper.selectOne(queryWrapper);
        if (aiUser == null) {
            throw new ServiceException(MessageUtils.message("user.not.found"), HttpStatus.CONFLICT);
        }
        // 验证密码是否正确
        if (!SecurityUtils.matchesPassword(loginAiUserBody.getPassword(), aiUser.getPassword())) {
            throw new ServiceException(MessageUtils.message("user.password.incorrect"), HttpStatus.CONFLICT);
        }
        // 更新登录时间
        aiUser.setLoginTime(new Date());
        aiUserMapper.updateById(aiUser);
        return new LoginAiUser(aiUser.getId(), aiUser);
    }

    @Override
    public void updatePassword(String oldPassword, String newPassword) {
        String password = aiUserMapper.selectPasswordById(SecurityUtils.getAiUserId());
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            throw new ServiceException(MessageUtils.message("user.password.incorrect"), HttpStatus.CONFLICT);
        }
        newPassword = SecurityUtils.encryptPassword(newPassword);
        AiUser user = new AiUser();
        user.setId(SecurityUtils.getAiUserId());
        user.setPassword(newPassword);
        aiUserMapper.updateById(user);
    }

    @Override
    public void updateEmail(String email, String code) {
        boolean b = emailVerifyService.verifyCode(email, code);
        if (!b) {
            throw new ServiceException(MessageUtils.message("email.verification.code.error"), HttpStatus.BAD_REQUEST);
        }
        AiUser user = new AiUser();
        user.setId(SecurityUtils.getAiUserId());
        user.setEmail(email);
        aiUserMapper.updateById(user);
    }

    @Override
    public void updateAvatar(String avatar) {
        AiUser user = new AiUser();
        user.setId(SecurityUtils.getAiUserId());
        user.setAvatar(avatar);
        aiUserMapper.updateById(user);
    }

    @Override
    public void addUserBalance(String orderNo, Long userId, BigDecimal amount, int recharge) {
        addUserBalance(orderNo, userId, amount, recharge, null);
    }

    @Override
    @Transactional
    public void addUserBalance(String orderNo, Long userId, BigDecimal amount, int recharge, String remark) {
        // 新增余额使用记录
        AiUser aiUser = aiUserMapper.selectById(userId);
        AiBalanceChangeRecord balanceChangeRecord = new AiBalanceChangeRecord();
        balanceChangeRecord.setUserId(userId);
        balanceChangeRecord.setType(recharge);
        balanceChangeRecord.setChangeAmount(amount);
        balanceChangeRecord.setResultAmount(NumberUtil.add(amount, aiUser.getBalance()));
        balanceChangeRecord.setRemark(remark);
        balanceChangeRecord.setOrderNo(orderNo);
        balanceChangeRecordService.insertAiBalanceChangeRecord(balanceChangeRecord);
        // 修改用户余额
        aiUser.setBalance(balanceChangeRecord.getResultAmount());
        aiUserMapper.updateById(aiUser);
//        // 如果是充值余额就返佣上级用户
//        if (recharge == BalanceChangerConstants.RECHARGE && aiUser.getSuperiorId() != null) {
//            // 查询上级用户
//            AiUser superiorUser = aiUserMapper.selectById(aiUser.getSuperiorId());
//            if (superiorUser != null) {
//                // 获取返佣比例%
////                SysConfig sysConfig = sysConfigMapper.selectConfigById(100l);
//                SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique(AiConfigEnum.SYS_INVITE_COMMISSION.getValue());
//                double decimal = NumberUtil.div(Integer.parseInt(sysConfig.getConfigValue()), 100, 2);
//                BigDecimal rebateAmount = NumberUtil.mul(amount, decimal);
//                addUserBalance(superiorUser.getId(), rebateAmount, BalanceChangerConstants.REBATE);
//                // 新增返佣记录
//                AiRebateRecord rebateRecord = new AiRebateRecord();
//                rebateRecord.setSuperiorId(superiorUser.getId());
//                rebateRecord.setSubordinateId(aiUser.getId());
//                rebateRecord.setAmount(rebateAmount);
//                aiRebateRecordService.insertAiRebateRecord(rebateRecord);
//            }
//        }
    }

    @Override
    public int updatePassword(AiUser aiUser) {
        aiUser.setPassword(SecurityUtils.encryptPassword(aiUser.getNewPassword()));
        return aiUserMapper.updateById(aiUser);
    }

    @Override
    @Transactional
    public void deductSampleAmount(String userId) {
        // 查询对应用户的体验金记录
        AiSampleAmountRecord aiSampleAmountRecord = aiSampleAmountRecordService.getAiSampleAmountRecordByUserId(userId);
//        // 查询用户使用所有合计金额
//        BigDecimal amount = aiOrderService.getSumAmountByUserId(userId);
//        // 计算回收金额，假如使用过的金额大于赠送金额则回收0
//        BigDecimal deductAmount = NumberUtil.sub(aiSampleAmountRecord.getSampleAmount(), amount);
//        if (deductAmount.compareTo(BigDecimal.ZERO) < 0) {
//            deductAmount = new BigDecimal(0);
//        }
        addUserBalance(aiSampleAmountRecord.getOrderNo(), Long.valueOf(userId), NumberUtil.mul(aiSampleAmountRecord.getSampleAmount(), -1), BalanceChangerConstants.EXPERIENCE_GOLD_RECYCLE);
        // 修改状态已回收
        aiSampleAmountRecord.setStatus(1);
        aiSampleAmountRecordService.updateAiSampleAmountRecord(aiSampleAmountRecord);
    }

    @Override
    public void handleRebate(String orderNo, Long userId, BigDecimal amount) {
        AiUser aiUser = aiUserMapper.selectById(userId);
        if (aiUser.getSuperiorId() == null) return;
        // 查询上级用户
        AiUser superiorUser = aiUserMapper.selectById(aiUser.getSuperiorId());
        if (superiorUser != null) {
            // 获取返佣比例%
//                SysConfig sysConfig = sysConfigMapper.selectConfigById(100l);
            SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique(AiConfigEnum.SYS_INVITE_COMMISSION.getValue());
            double decimal = NumberUtil.div(Integer.parseInt(sysConfig.getConfigValue()), 100, 2);
            BigDecimal rebateAmount = NumberUtil.mul(amount, decimal);
            addUserBalance(orderNo, superiorUser.getId(), rebateAmount, BalanceChangerConstants.REBATE);
            // 新增返佣记录
            AiRebateRecord rebateRecord = new AiRebateRecord();
            rebateRecord.setSuperiorId(superiorUser.getId());
            rebateRecord.setSubordinateId(aiUser.getId());
            rebateRecord.setAmount(rebateAmount);
            aiRebateRecordService.insertAiRebateRecord(rebateRecord);
        }
    }

    @Override
    public String getRebateConfig() {
        SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique(AiConfigEnum.SYS_INVITE_COMMISSION.getValue());
        return sysConfig.getConfigValue() + "%";
    }

    @Override
    public Map<String, Object> checkIsStandard() {
        // 获取累计金额
        SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique(AiConfigEnum.SYS_TOTAL_AMOUNT.getValue());
        double targetAmount = Double.parseDouble(sysConfig.getConfigValue());
        // 获取当前用户累计充值金额
        AiRecharge aiRecharge = new AiRecharge();
        aiRecharge.setUserId(SecurityUtils.getAiUserId());
        double totalAmount = aiRechargeMapper.getTotalAmount(aiRecharge).doubleValue();
        Map<String, Object> map = new HashMap<>();
        map.put("result", totalAmount >= targetAmount);
        map.put("totalAmount", totalAmount);
        return map;
    }
}
