package org.springblade.modules.distribution.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springblade.modules.distribution.entity.Commission;
import org.springblade.modules.distribution.entity.DistributionConfig;
import org.springblade.modules.distribution.mapper.CommissionMapper;
import org.springblade.modules.distribution.service.ICommissionService;
import org.springblade.modules.distribution.service.IDistributionConfigService;
import org.springblade.modules.distribution.vo.CommisStatisVO;
import org.springblade.modules.distribution.vo.CommissionVO;
import org.springblade.modules.finance.entity.Order;
import org.springblade.modules.groupon.entity.Embers;
import org.springblade.modules.groupon.service.IEmbersService;
import org.springblade.modules.platform.service.UserAppService;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.entity.UserApp;
import org.springblade.modules.system.service.IUserService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Date;
import java.util.Objects;

@Slf4j
@Service
public class CommissionServiceImpl  extends ServiceImpl<CommissionMapper, Commission> implements ICommissionService {

    @Resource
    private IDistributionConfigService distributionConfigService;

    @Resource
    private UserAppService userAppService;

    @Resource
    private IUserService userService;

    @Resource
    private IEmbersService embersService;

    @Override
    public List<CommissionVO> getNotPayouts(Integer days) {
        return this.baseMapper.selectNotPayouts(days);
    }

    @Async
    @Override
    public void commissionCalculation(Order order) {
        try {
            DistributionConfig config = distributionConfigService.lambdaQuery().eq(DistributionConfig::getIsDelete, 0).one();
            if (Objects.isNull(config)){return;}
            if (!config.getIsOpen()){return;}
            User orderCreateUser = userService.getById(order.getUserId());

            Embers one = embersService.lambdaQuery()
                    .eq(Embers::getBindUserId, order.getUserId())
                    .eq(Embers::getIsDelete, 0)
                    .eq(Embers::getState,0)
                    .one();
            if (Objects.isNull(one)) {
                return;
            }
            User benefitUser = userService.getById(one.getShareUserId());
            BigDecimal amount = order.getPaymentAmount().multiply(config.getProportion());
            Commission commission = new Commission();
            commission.setBenefitUserId(benefitUser.getId());
            commission.setBenefitUserName(benefitUser.getRealName());
            commission.setOrderId(order.getId());
            commission.setBindUserId(orderCreateUser.getId());
            commission.setBindUserName(orderCreateUser.getRealName());
            commission.setAmount(amount);
            commission.setIsPayouts(0);
            commission.setIsUse(1);
            this.save(commission);
        } catch (Exception e) {
            log.error("计算收益失败:订单号:" + order.getOrderNo() + "_" + e.getMessage());
        }
    }



    @Override
    public CommisStatisVO statistics(Long userId) {
        return  this.getBaseMapper().statistics(userId);
    }

    @Override
    public void invalidCommission(Long orderId) {
        LambdaUpdateWrapper<Commission> u = new LambdaUpdateWrapper<>();
        u.set(Commission::getIsUse,0);
        u.set(Commission::getUpdateTime,new Date());
        u.eq(Commission::getIsUse,1);
        u.eq(Commission::getOrderId,orderId);
        this.update(u);
    }



    @Override
    public void commissionCalculationTwo(Long orderId, BigDecimal amount) {
        try {
            this.invalidCommission(orderId);
            LambdaQueryWrapper<Commission> q = new LambdaQueryWrapper<>();
            q.eq(Commission::getOrderId,orderId);
            q.eq(Commission::getIsDelete,0);
            q.last("limit 1");
            Commission commissionOne = this.getOne(q);
            if (Objects.isNull(commissionOne)){
                return; //如果之前没有分佣记录，说明该订单没有产生分佣
            }
            DistributionConfig config = distributionConfigService.lambdaQuery().eq(DistributionConfig::getIsDelete, 0).one();
            BigDecimal commissionAmount = amount.multiply(config.getProportion());
            Commission commission = new Commission();
            commission.setBenefitUserId(commissionOne.getBenefitUserId());
            commission.setBenefitUserName(commissionOne.getBenefitUserName());
            commission.setOrderId(orderId);
            commission.setBindUserId(commissionOne.getBindUserId());
            commission.setBindUserName(commissionOne.getBindUserName());
            commission.setAmount(amount);
            commission.setIsPayouts(0);
            commission.setIsUse(1);
            this.save(commission);
        } catch (Exception e) {
            log.error("计算收益失败:订单号:" + orderId + "_" + e.getMessage());
        }

    }
}
