package co.yixiang.yshop.module.member.service.integralrule.strategy;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import co.yixiang.yshop.module.member.api.integralRule.IntegralRuleDTO;
import co.yixiang.yshop.module.member.controller.admin.userbill.vo.UserBillPageReqVO;
import co.yixiang.yshop.module.member.dal.dataobject.user.MemberUserDO;
import co.yixiang.yshop.module.member.enums.BillDetailEnum;
import co.yixiang.yshop.module.member.service.user.MemberUserService;
import co.yixiang.yshop.module.member.service.userbill.UserBillService;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * @author pepis
 * @apiNote 积分奖励规则策略抽象
 **/
public abstract class AbstractIntegralRuleStrategy implements IntegralRuleStrategy {
    private final MemberUserService userService;

    private final UserBillService userBillService;


    public AbstractIntegralRuleStrategy(MemberUserService userService, UserBillService userBillService) {
        this.userService = userService;
        this.userBillService = userBillService;
    }

    @Override
    public Boolean beforeExecute(BillDetailEnum type, IntegralRuleDTO rule) {
        //判断是否开启
        if (!rule.getEnable()) {
            return false;
        }
        UserBillPageReqVO pageReqVO = new UserBillPageReqVO();
        pageReqVO.setUid(rule.getUserId());
        pageReqVO.setType(type.getValue());
        LocalDateTime[] createTime = new LocalDateTime[2];
        createTime[0] = DateUtil.beginOfDay(DateUtil.date()).toLocalDateTime();
        createTime[1] = LocalDateTime.now();
        pageReqVO.setCreateTime(createTime);
        Long count = userBillService.getUserBillCount(pageReqVO);
        return count < 1;
    }

    @Override
    public BigDecimal execute(BillDetailEnum type, IntegralRuleDTO rule) {
        //前置
        if (!beforeExecute(type, rule)) {
            return null;
        }
        //计算获取的积分
        BigDecimal integral = calculate(rule);
        if (integral.compareTo(BigDecimal.ZERO) <= 0) {
            return null;
        }
        //更新积分到用户
        MemberUserDO user = userService.getUser(rule.getUserId());

        BigDecimal newIntegral = NumberUtil.add(user.getIntegral(), integral);
        user.setIntegral(newIntegral);
        user.setId(rule.getUserId());
        userService.updateById(user);

        //增加流水
        userBillService.income(user.getId(), type.getDesc(), BillDetailEnum.CATEGORY_2.getValue(),
                type.getValue(),
                integral,
                newIntegral,
                type.getDesc(), null);
        return integral;
    }
}
