package org.dromara.zhishu.service.impl;

import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.bo.SysUserBo;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.service.ISysUserService;
import org.dromara.system.service.IUserTransferService;
import org.dromara.zhishu.domain.Shop;
import org.dromara.zhishu.domain.vo.ShopVo;
import org.dromara.zhishu.service.IShopService;
import org.springframework.stereotype.Service;
import org.dromara.zhishu.domain.bo.UserRechargeBo;
import org.dromara.zhishu.domain.vo.UserRechargeVo;
import org.dromara.zhishu.domain.UserRecharge;
import org.dromara.zhishu.mapper.UserRechargeMapper;
import org.dromara.zhishu.service.IUserRechargeService;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 用户充值Service业务层处理
 *
 * @author yxy
 * @date 2025-04-26
 */
@RequiredArgsConstructor
@Service
public class UserRechargeServiceImpl implements IUserRechargeService {

    private final UserRechargeMapper baseMapper;
    private final ISysUserService userService;
    private final IShopService shopService;
    private final IUserTransferService userTransferService;

    /**
     * 查询用户充值
     *
     * @param id 主键
     * @return 用户充值
     */
    @Override
    public UserRechargeVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询用户充值列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 用户充值分页列表
     */
    @Override
    public TableDataInfo<UserRechargeVo> queryPageList(UserRechargeBo bo, PageQuery pageQuery) {
        Long userId = LoginHelper.getUserId();
        if (userId != 1) {
            bo.setCreateBy(userId);
        }
        LambdaQueryWrapper<UserRecharge> lqw = buildQueryWrapper(bo);
        Page<UserRechargeVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的用户充值列表
     *
     * @param bo 查询条件
     * @return 用户充值列表
     */
    @Override
    public List<UserRechargeVo> queryList(UserRechargeBo bo) {
        LambdaQueryWrapper<UserRecharge> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<UserRecharge> buildQueryWrapper(UserRechargeBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<UserRecharge> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(UserRecharge::getCreateTime);
        lqw.eq(bo.getUserId() != null, UserRecharge::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getRechargType()), UserRecharge::getRechargType, bo.getRechargType());
        if(bo.getRechargPrice() != null){
            bo.setRechargPrice(bo.getRechargPrice().multiply(new BigDecimal(100)));
        }
        lqw.eq(bo.getRechargPrice() != null, UserRecharge::getRechargPrice, bo.getRechargPrice());
        lqw.eq(bo.getSuccessTime() != null, UserRecharge::getSuccessTime, bo.getSuccessTime());
        lqw.between(params.get("beginTime") != null && params.get("endTime") != null,
                UserRecharge::getCreateTime, params.get("beginTime"), params.get("endTime"));
        lqw.eq(StringUtils.isNotBlank(bo.getAllDataStr()), UserRecharge::getAllDataStr, bo.getAllDataStr());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), UserRecharge::getStatus, bo.getStatus());
        lqw.eq(bo.getCreateBy()!=null, UserRecharge::getCreateBy, bo.getCreateBy());
        lqw.like(bo.getLogTxt() != null, UserRecharge::getLogTxt, bo.getLogTxt());
        return lqw;
    }

    /**
     * 新增用户充值
     *
     * @param bo 用户充值
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(UserRechargeBo bo) {
        UserRecharge add = MapstructUtils.convert(bo, UserRecharge.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改用户充值
     *
     * @param bo 用户充值
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(UserRechargeBo bo) {
        UserRecharge update = MapstructUtils.convert(bo, UserRecharge.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(UserRecharge entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除用户充值信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 充值金额到钱包里
     * @return
     */
    @Override
    public R<Void> addUserBalance(UserRechargeBo bo){
        // 获取充值金额
        BigDecimal money = bo.getRechargPrice();
        // 换算成单位 分
        money = money.multiply(new BigDecimal(100));
        // 查询支付订单
        UserRechargeVo userRechargeVo = queryById(bo.getId());
        // 如果 1.不存在支付订单  2.支付订单已完成支付  3.传入的金额与支付订单中的金额不一致
        if(userRechargeVo == null || userRechargeVo.getIsBalance().equals("1") || money.compareTo(new BigDecimal(userRechargeVo.getRechargPrice())) != 0){
            // 返回异常信息
            return R.fail("异常操作");
        }else{
            // 修改支付订单
            UserRechargeBo userRechargeBo = new UserRechargeBo();
            // 支付订单id
            userRechargeBo.setId(bo.getId());
            // 支付订单支付状态
            userRechargeBo.setIsBalance("1");
            // 获取登陆人id
            Long userId = LoginHelper.getUserId();
            // 获取用户信息
            SysUserVo userVo =  userService.selectUserById(userId);
            // 充值金额
            BigDecimal newPrice = userVo.getBalance().add(money);
            // 创建用户信息
            SysUserBo userBo = new SysUserBo();
            // 用户id
            userBo.setUserId(userId);
            // 充值金额
            userBo.setBalance(newPrice);
            // 原始价格
            userRechargeBo.setOriginalPrice(userVo.getBalance());
            // 更新价格
            userRechargeBo.setUpdatePrice(newPrice);
            // 修改用户信息
            userService.updateUser(userBo);
            // 修改支付订单的支付状态
            updateByBo(userRechargeBo);
            // 返回
            return R.ok();
        }
    }

    /**
     * 余额支付
     * @param userId
     * @param shopId
     * @param logType
     * @param rechargPrice
     * @return
     */
    @Override
    public R<Map> balancePayment(Long userId, Long shopId, int logType, BigDecimal rechargPrice){
        String logTxt = "";
        switch (logType){
            case 1:
                logTxt = "孔夫子店铺订阅;";
                break;
            case 3:
                logTxt = "闲鱼店铺订阅;";
                break;
            case 1001:
                logTxt = "开通子账号权限;";
                break;
        }
        if (shopId != null){
            ShopVo shopVo = shopService.queryById(shopId);
            logTxt =  "店铺名称："+shopVo.getShopName()+";" + logTxt;
        }

        SysUserVo userVo = userService.selectUserById(userId);
        BigDecimal balance =  userVo.getBalance();

        if (balance.compareTo(rechargPrice) < 0){
            // 余额不足
            return R.fail("余额不足");
        }else{
            BigDecimal newBalance = balance.subtract(rechargPrice);
//            SysUserBo bo = new SysUserBo();
//            bo.setUserId(userId);
//            bo.setBalance(newBalance);
            userTransferService.updateBalance(userId,newBalance.longValue());

            UserRechargeBo userRechargeBo = new UserRechargeBo();
            userRechargeBo.setCommission(BigDecimal.ZERO);
            userRechargeBo.setRechargPrice(rechargPrice);
            userRechargeBo.setRechargType("6");
            userRechargeBo.setStatus("6");
            userRechargeBo.setUserId(userId);
            userRechargeBo.setCreateBy(userId);
            userRechargeBo.setUpdateBy(userId);
            userRechargeBo.setLogTxt(logTxt);
            userRechargeBo.setOriginalPrice(balance);
            userRechargeBo.setUpdatePrice(newBalance);
            insertByBo(userRechargeBo);

            Map returnMap = new HashMap();
            returnMap.put("code",200);
            returnMap.put("msg","余额充足");
            returnMap.put("id", userRechargeBo.getId());
            return R.ok(returnMap);
        }
    }
}
