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

import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO;
import cn.iocoder.yudao.module.custom.entity.CustomerBalance;
import cn.iocoder.yudao.module.custom.entity.CustomerCoupon;
import cn.iocoder.yudao.module.custom.mapper.CustomerBalanceMapper;
import cn.iocoder.yudao.module.custom.service.CustomerBalanceService;
import cn.iocoder.yudao.module.custom.service.CustomerCouponService;
import cn.iocoder.yudao.module.custom.service.CustomerMainService;
import cn.iocoder.yudao.module.custom.vo.CustomerBalanceSaveReqVO;
import cn.iocoder.yudao.module.custom.vo.CustomerMainRespVO;
import cn.iocoder.yudao.module.member.entity.ActiveRule;
import cn.iocoder.yudao.module.member.entity.MemberCoupon;
import cn.iocoder.yudao.module.member.service.ActiveMainService;
import cn.iocoder.yudao.module.member.vo.ActiveMainRespVO;
import cn.iocoder.yudao.module.order.entity.RepairOrderInfo;
import cn.iocoder.yudao.module.order.service.RepairOrderInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.common.BaseConstants.GENERAL_YES;

/**
 * 用户积分（余额） Service 实现类
 *
 * @author pqz
 */
@Service
@Validated
public class CustomerBalanceServiceImpl extends ServiceImpl<CustomerBalanceMapper, CustomerBalance> implements CustomerBalanceService {

    @Resource
    private CustomerBalanceMapper customerBalanceMapper;
    @Resource
    private CustomerMainService customerMainService;
    @Resource
    @Lazy
    private ActiveMainService activeMainService;
    @Resource
    @Lazy
    private CustomerCouponService customerCouponService;


    @Override
    public String createCustomerBalance(CustomerBalanceSaveReqVO createReqVO) {
        // 插入
        CustomerBalance customerBalance = BeanUtils.toBean(createReqVO, CustomerBalance.class);
        customerBalanceMapper.insert(customerBalance);
        // 返回
        return customerBalance.getId();
    }

    /**
     * 更新用户余额信息(充值完成的回调)
     *
     * @param orderInfo 用户订单信息
     * @author PQZ
     * @date 21:04 2024/9/23
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void balanceCallback(RepairOrderInfo orderInfo) {
        //查询当前登录用户信息
        CustomerMainRespVO customer = customerMainService.getCustomerById(orderInfo.getCusId());
        CustomerBalance balance;
        if (null != orderInfo.getActiveId()) {
            //获取当前活动信息
            ActiveMainRespVO active = activeMainService.getActiveMain(orderInfo.getActiveId(), true);
            //查询关联卡券信息（充值有礼）
            List<MemberCoupon> couponList = active.getCouponList();
            //转换卡券信息
            List<CustomerCoupon> customerCouponList = customerCouponService.transCoupon(active.getId(), customer.getId(), customer.getUserId(), couponList);
            customerCouponService.saveBatch(customerCouponList);
            balance = transBalance(customer, orderInfo.getPayMoney(), active.getRuleList());
        } else {
            balance = transBalance(customer, orderInfo.getPayMoney(), null);
        }
        updateByCusId(balance);
    }

    /**
     * 转换余额
     *
     * @param customer 用户信息
     * @param amount   实际充值金额
     * @param ruleList 规则
     * @return cn.iocoder.yudao.module.custom.entity.CustomerBalance
     * @author PQZ
     * @date 11:30 2024/9/21
     **/
    CustomerBalance transBalance(CustomerMainRespVO customer, BigDecimal amount, List<ActiveRule> ruleList) {
        CustomerBalance result = new CustomerBalance();
        result.setCusId(customer.getId());
        result.setUserId(customer.getUserId());
        BigDecimal nowChange = amount;
        if (null != ruleList && !ruleList.isEmpty()) {
            List<ActiveRule> sortList = ruleList.stream().sorted(Comparator.comparing(ActiveRule::getRechAmount).reversed()).collect(Collectors.toList());
            for (ActiveRule item : sortList) {
                //如果规则匹配
                if (amount.compareTo(item.getRechAmount()) >= 0) {
                    nowChange = amount.add(item.getGiveAmount());
                    break;
                }
            }
        }
        //余额
        result.setBalance(customer.getBalance().add(nowChange));
        //累计充值金额
        result.setAllBalance(customer.getBalance().add(nowChange));
        //本次变动金额
        result.setNowChange(nowChange);
        return result;
    }

    @Override
    public void updateCustomerBalance(CustomerBalanceSaveReqVO updateReqVO) {
        // 更新
        CustomerBalance updateObj = BeanUtils.toBean(updateReqVO, CustomerBalance.class);
        customerBalanceMapper.updateById(updateObj);
    }

    /**
     * 根据用户id更新用户余额表
     *
     * @param balance CustomerBalance
     * @return void
     * @author PQZ
     * @date 11:56 2024/9/21
     **/
    @Override
    public void updateByCusId(CustomerBalance balance) {
        LambdaQueryWrapper<CustomerBalance> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CustomerBalance::getCusId, balance.getCusId()).eq(BaseDO::getDeleted, '0');
        remove(lambdaQueryWrapper);
        this.save(balance);
    }


}