package com.ruoyi.ai.service.impl;

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.mapper.AiRechargeMapper;
import com.ruoyi.ai.service.*;
import com.ruoyi.common.constant.BalanceChangerConstants;
import com.ruoyi.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
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.List;

/**
 * 充值管理Service业务层处理
 *
 * @author shi
 * @date 2025-11-13
 */
@Service
@Slf4j
public class AiRechargeServiceImpl implements IAiRechargeService {

    @Autowired
    private AiRechargeMapper aiRechargeMapper;
    @Autowired
    private IAiUserService aiUserService;
    @Autowired
    private IAiRechargeGiftGearService aiRechargeGiftGearService;
    @Autowired
    private IAiRechargeGiftService aiRechargeGiftService;
    @Autowired
    private IAiStatisticsService statisticsService;
    @Autowired
    private IAiRechargeGiftRecordService aiRechargeGiftRecordService;

    /**
     * 查询充值管理
     *
     * @param id 充值管理主键
     * @return 充值管理
     */
    @Override
    public AiRecharge selectAiRechargeById(Long id) {
        return aiRechargeMapper.selectById(id);
    }

    /**
     * 查询充值管理列表
     *
     * @param aiRecharge 充值管理
     * @return 充值管理
     */
    @Override
    public List<AiRecharge> selectAiRechargeList(AiRecharge aiRecharge) {
        return aiRechargeMapper.selectAiRechargeList(aiRecharge);
    }

    @Override
    public List<AiRecharge> getAiRechargeList(AiRecharge aiRecharge) {
        return aiRechargeMapper.getAiRechargeList(aiRecharge);
    }

    @Override
    public BigDecimal getTotalAmount(AiRecharge aiRecharge) {
        return aiRechargeMapper.getTotalAmount(aiRecharge);
    }

    @Override
    @Transactional
    public void addRecharge(String orderNo) {
        // 设置到账时间
        AiRecharge aiRecharge = this.getAiRechargeByOrderNum(orderNo);
        if (aiRecharge == null) {
            log.error("支付回调订单不存在，orderNo: {}", orderNo);
            return;
        }
        Date creditedTime = aiRecharge.getCreditedTime();
        if (creditedTime != null) {
            log.error("支付回调重复 {}", orderNo);
            return;
        }
        Long gearId = aiRecharge.getGearId();
        AiRechargeGiftGear aiRechargeGiftGear = aiRechargeGiftGearService.selectAiRechargeGiftGearById(gearId);
        AiRechargeGift aiRechargeGift = aiRechargeGiftService.selectAiRechargeGiftById(aiRechargeGiftGear.getRechargeId());

        // 如果是首充活动就判断是否是第一次充值
        boolean isFristRecharge = true;
        if (aiRechargeGift.getIsFristRecharge().equals("Y")) {
            QueryWrapper<AiRecharge> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", aiRecharge.getUserId());
            queryWrapper.isNotNull("credited_time");
            isFristRecharge = aiRechargeMapper.selectCount(queryWrapper) == 0;
        }

        BigDecimal amount = aiRechargeGiftGear.getGiftAmount();
        aiRecharge.setCreditedTime(DateUtils.getNowDate());
        aiRecharge.setGiftAmount(amount);


        // 新增用户余额
        aiUserService.addUserBalance(orderNo, aiRecharge.getUserId(), amount, BalanceChangerConstants.RECHARGE);
        // 处理返佣 (根据充值金额计算返佣)
        aiUserService.handleRebate(orderNo, aiRecharge.getUserId(), aiRechargeGiftGear.getRechargeAmount());
        // 新增充值统计
        AiStatistics aiStatistics = new AiStatistics();
        aiStatistics.setSource(aiRecharge.getSource());
        aiStatistics.setRechargeAmount(amount);
        statisticsService.saveOrUpdateData(aiStatistics);


        // 处理赠送金额
        if (isFristRecharge && aiRecharge.getGearId() != null) {
            // 查询活动是否过期
            boolean isAvailable = aiRechargeGiftService.isActivityAvailable(aiRechargeGiftGear.getRechargeId());
            if (isAvailable) {
                aiRecharge.setGiveAmount(aiRechargeGiftGear.getGiveAmount());
                // 新增用户赠送余额
                aiUserService.addUserBalance(orderNo, aiRecharge.getUserId(), aiRechargeGiftGear.getGiveAmount(), BalanceChangerConstants.RECHARGE_BONUS);
                // 新增充值赠送记录
                AiRechargeGiftRecord aiRechargeGiftRecord = new AiRechargeGiftRecord();
                aiRechargeGiftRecord.setOrderNum(orderNo);
                aiRechargeGiftRecord.setRechargeGearTitle(aiRechargeGiftGear.getTitle());  // 档位说明
                aiRechargeGiftRecord.setGearAmount(aiRechargeGiftGear.getRechargeAmount()); // 档位金额
                aiRechargeGiftRecord.setGiftAmount(aiRechargeGiftGear.getGiveAmount());  // 赠送金额
                aiRechargeGiftRecord.setUserId(aiRecharge.getUserId());
                aiRechargeGiftRecordService.insertAiRechargeGiftRecord(aiRechargeGiftRecord);
            }
        }
        this.updateAiRecharge(aiRecharge);
    }

    /**
     * 分页查询充值管理列表
     *
     * @param aiRecharge 充值管理
     * @return 充值管理
     */
    @Override
    public IPage<AiRecharge> selectAiRechargePage(Page page, AiRecharge aiRecharge) {
        LambdaQueryWrapper<AiRecharge> query = Wrappers.lambdaQuery(aiRecharge);
        query.eq(AiRecharge::getDelFlag, "0");
        return aiRechargeMapper.selectPage(page, query);
    }

    /**
     * 新增充值管理
     *
     * @param aiRecharge 充值管理
     * @return 结果
     */
    @Override
    public int insertAiRecharge(AiRecharge aiRecharge) {
        aiRecharge.setDelFlag("0");
        aiRecharge.setCreateTime(DateUtils.getNowDate());

        return aiRechargeMapper.insert(aiRecharge);
    }

    /**
     * 修改充值管理
     *
     * @param aiRecharge 充值管理
     * @return 结果
     */
    @Override
    public int updateAiRecharge(AiRecharge aiRecharge) {
//        aiRecharge.setUpdateBy(SecurityUtils.getUsername());
        aiRecharge.setUpdateTime(DateUtils.getNowDate());
        return aiRechargeMapper.updateById(aiRecharge);
    }

    /**
     * 批量删除充值管理
     *
     * @param ids 需要删除的充值管理主键
     * @return 结果
     */
    @Override
    public int deleteAiRechargeByIds(Long[] ids) {
        return aiRechargeMapper.deleteAiRechargeByIds(ids);
    }

    /**
     * 删除充值管理信息
     *
     * @param id 充值管理主键
     * @return 结果
     */
    @Override
    public int deleteAiRechargeById(Long id) {
        return aiRechargeMapper.deleteAiRechargeById(id);
    }

    /**
     * 通过订单号获取充值记录
     *
     * @param orderno
     * @return
     */
    @Override
    public AiRecharge getAiRechargeByOrderNum(String orderno) {
        return aiRechargeMapper.getAiRechargeByOrderNum(orderno);
    }
}
