package cn.iocoder.yudao.module.shop.service.impl;

import cn.iocoder.yudao.module.shop.entity.ShopConfig;
import cn.iocoder.yudao.module.shop.entity.ShopUserBalanceChanges;
import cn.iocoder.yudao.module.shop.entity.UserBalance;
import cn.iocoder.yudao.module.shop.mapper.UserBalanceMapper;
import cn.iocoder.yudao.module.shop.service.IShopConfigService;
import cn.iocoder.yudao.module.shop.service.IShopUserBalanceChangesService;
import cn.iocoder.yudao.module.shop.service.IUserBalanceService;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserSaveReqVO;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 用户积分Service业务层处理
 *
 * @author ruoyi
 * @date 2023-07-09
 */
@Service
public class UserBalanceServiceImpl extends ServiceImpl<UserBalanceMapper, UserBalance> implements IUserBalanceService
{
    @Autowired
    private UserBalanceMapper shopUserBalanceMapper;
    @Autowired
    private IShopUserBalanceChangesService changesService;
    @Autowired
    private AdminUserService userService;
    @Autowired
    private IShopConfigService shopConfigService;

    /**
     * 查询用户积分
     *
     * @param id 用户积分主键
     * @return 用户积分
     */
    @Override
    public UserBalance selectShopUserBalanceById(Long id)
    {
        return shopUserBalanceMapper.selectShopUserBalanceById(id);
    }

    @Override
    public List<ShopUserBalanceChanges> getDetail(Long userId) {
        ShopUserBalanceChanges shopUserBalanceChanges =new ShopUserBalanceChanges();
        shopUserBalanceChanges.setUserId(userId);
      return   changesService.selectShopUserBalanceChangesList(shopUserBalanceChanges);
    }

    /**
     * 查询用户积分列表
     *
     * @param shopUserBalance 用户积分
     * @return 用户积分
     */
    @Override
    public List<UserBalance> selectShopUserBalanceList(UserBalance shopUserBalance)
    {
        return shopUserBalanceMapper.selectShopUserBalanceList(shopUserBalance);
    }

    /**
     * 新增用户积分
     *
     * @param shopUserBalance 用户积分
     * @return 结果
     */
    @Override
    public int insertShopUserBalance(UserBalance shopUserBalance)
    {
        return shopUserBalanceMapper.insertShopUserBalance(shopUserBalance);
    }

    /**
     * 修改用户积分
     *
     * @param shopUserBalance 用户积分
     * @return 结果
     */
    @Override
    public int updateShopUserBalance(UserBalance shopUserBalance)
    {
        return shopUserBalanceMapper.updateShopUserBalance(shopUserBalance);
    }

    /**
     * 批量删除用户积分
     *
     * @param ids 需要删除的用户积分主键
     * @return 结果
     */
    @Override
    public int deleteShopUserBalanceByIds(Long[] ids)
    {
        return shopUserBalanceMapper.deleteShopUserBalanceByIds(ids);
    }

    /**
     * 删除用户积分信息
     *
     * @param id 用户积分主键
     * @return 结果
     */
    @Override
    public int deleteShopUserBalanceById(Long id)
    {
        return shopUserBalanceMapper.deleteShopUserBalanceById(id);
    }

    @Override
    public UserBalance selectShopUserBalanceByUserId(Long userId) {
        return shopUserBalanceMapper.selectShopUserBalanceByUserId(userId);
    }
    //积分充值
    @Override
    public void addBalance(Long balance, Long userId, JSONObject orderInfo) {
        //增加积分
        shopUserBalanceMapper.addBalance(balance,userId);
        String reason = "充值了"+balance+"积分";
        //写入积分使用记录
        ShopUserBalanceChanges balanceChanges = new ShopUserBalanceChanges();
        balanceChanges.setUserId(userId);
        balanceChanges.setChangeTime(new Date());
        balanceChanges.setChangeAmount(balance);
        balanceChanges.setChangeType(orderInfo.getString("goodsType"));
        balanceChanges.setChangeReason(reason);
        changesService.insertShopUserBalanceChanges(balanceChanges);
        //处理会员层级的变化
        //先判断根据当前充值金额应该升级为的会员等级
        UserBalance shopUserBalance = this.selectShopUserBalanceByUserId(userId);
        if (shopUserBalance.getAllBalance()>=orderInfo.getLong("platinum")){
            //升级白金会员
            UserSaveReqVO userSaveReqVO = new UserSaveReqVO();
            userSaveReqVO.setId(userId);
            userSaveReqVO.setUserLevel(3);
            userService.updateUser(userSaveReqVO);
        }else if(shopUserBalance.getAllBalance()>=orderInfo.getLong("goldNum")){
            //升级黄金会员
            UserSaveReqVO userSaveReqVO = new UserSaveReqVO();
            userSaveReqVO.setId(userId);
            userSaveReqVO.setUserLevel(2);
            userService.updateUser(userSaveReqVO);
        }else if(shopUserBalance.getAllBalance()>=orderInfo.getLong("silverNum")){
            //升级白银会员
            UserSaveReqVO userSaveReqVO = new UserSaveReqVO();
            userSaveReqVO.setId(userId);
            userSaveReqVO.setUserLevel(1);
            userService.updateUser(userSaveReqVO);
        }

    }
    //冻结积分
    @Override
    public void frozenBalance(Long balance,Long userId) {
         shopUserBalanceMapper.frozenBalance(balance,userId);
    }
   //解冻积分
    @Override
    public void thawBalance(Long balance, Long userId) {
         shopUserBalanceMapper.thawBalance(balance,userId);
    }
    //核销积分
    @Override
    @Transactional
    public void subtractFrozenBalance(Long balance, Long userId, JSONObject orderInfo) {
         //减掉积分
         shopUserBalanceMapper.subtractFrozenBalance(balance,userId);
         String reason = "消费使用"+balance+"积分";
         if (orderInfo.getString("goodsType").equals("jc")){
             //检测
             reason = "在汽车检测板块购买"+orderInfo.getString("goodsTitle")+",消费了"+balance+"积分";
         }else if (orderInfo.getString("goodsType").equals("qx")){
             //检测
             reason = "在汽修板块购买"+orderInfo.getString("goodsTitle")+",消费了"+balance+"积分";
         }
         //写入积分使用记录
        ShopUserBalanceChanges balanceChanges = new ShopUserBalanceChanges();
        balanceChanges.setChangeTime(new Date());
        balanceChanges.setUserId(userId);
        balanceChanges.setChangeAmount(balance);
        balanceChanges.setChangeType(orderInfo.getString("goodsType"));
        balanceChanges.setChangeReason(reason);
        changesService.insertShopUserBalanceChanges(balanceChanges);
    }
    //核销积分
    @Override
    @Transactional
    public void subtractBalance(Long balance, Long userId, JSONObject orderInfo) {
        //减掉积分
        shopUserBalanceMapper.subtractBalance(balance,userId);
        String reason = "消费使用"+balance+"积分";
        if (orderInfo.getString("goodsType").equals("jc")){
            //检测
            reason = "在汽车检测板块购买"+orderInfo.getString("goodsTitle")+",消费了"+balance+"积分";
        }else if (orderInfo.getString("goodsType").equals("qx")){
            //检测
            reason = "在汽修板块购买"+orderInfo.getString("goodsTitle")+",消费了"+balance+"积分";
        }
        //写入积分使用记录
        ShopUserBalanceChanges balanceChanges = new ShopUserBalanceChanges();
        balanceChanges.setChangeTime(new Date());
        balanceChanges.setUserId(userId);
        balanceChanges.setChangeAmount(balance);
        balanceChanges.setChangeType(orderInfo.getString("goodsType"));
        balanceChanges.setChangeReason(reason);
        changesService.insertShopUserBalanceChanges(balanceChanges);
    }

    /**
     * 邀请注册奖励积分
     * @param userId
     */
    @Override
    public void inviteRewards(Long userId) {
        ShopConfig shopConfig = shopConfigService.selectShopConfigById(1l);
        Long inviteRewards = Optional.ofNullable(shopConfig.getInviteRewards()).orElse(0L);
        //奖励积分
        shopUserBalanceMapper.rewardBalance(inviteRewards,userId);
        String reason = "邀请新用户,奖励"+inviteRewards+"积分";
        //写入积分变动记录
        ShopUserBalanceChanges balanceChanges = new ShopUserBalanceChanges();
        balanceChanges.setChangeTime(new Date());
        balanceChanges.setUserId(userId);
        balanceChanges.setChangeAmount(inviteRewards);
        balanceChanges.setChangeType("reward");
        balanceChanges.setChangeReason(reason);
        changesService.insertShopUserBalanceChanges(balanceChanges);

    }
    //邀请的用户产生了消费
    // userId 用户主键 amount 消费的金额
    @Override
    public void inviteSpend(Long userId,Long amount) {
        ShopConfig shopConfig = shopConfigService.selectShopConfigById(1l);
         //奖励提成
        Double royalty = Optional.ofNullable( shopConfig.getRoyalty()).orElse(0d);
        //奖励积分
        Double temp =  (amount*royalty)/100;
        shopUserBalanceMapper.rewardBalance(temp.longValue(),userId);
        String reason = "邀请的用户,产生消费奖励"+temp.longValue()+"积分";
        //写入积分变动记录
        ShopUserBalanceChanges balanceChanges = new ShopUserBalanceChanges();
        balanceChanges.setChangeTime(new Date());
        balanceChanges.setChangeAmount(temp.longValue());
        balanceChanges.setChangeType("reward");
        balanceChanges.setChangeReason(reason);
        changesService.insertShopUserBalanceChanges(balanceChanges);
    }
    @Override
    public void refundBalance(Long userId, Long balance, JSONObject orderInfo) {
        //增加积分
        shopUserBalanceMapper.refundBalance(balance,userId);
        String reason = "退款"+balance+"积分";
        if (orderInfo.getString("goodsType").equals("jc")){
            //检测
            reason = "在汽车检测板块申请退款,商品名称："+orderInfo.getString("goodsTitle")+",增加了"+balance+"积分";
        }else if (orderInfo.getString("goodsType").equals("qx")){
            //检测
            reason = "在汽车检测板块申请退款,商品名称："+orderInfo.getString("goodsTitle")+",增加了"+balance+"积分";
        }
        //写入积分使用记录
        ShopUserBalanceChanges balanceChanges = new ShopUserBalanceChanges();
        balanceChanges.setUserId(userId);
        balanceChanges.setChangeTime(new Date());
        balanceChanges.setChangeAmount(balance);
        balanceChanges.setChangeType(orderInfo.getString("goodsType"));
        balanceChanges.setChangeReason(reason);
        changesService.insertShopUserBalanceChanges(balanceChanges);
    }
}
