package org.springblade.modules.quartz.task;

import cn.hutool.core.collection.CollUtil;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.enums.YesOrNoEnum;
import org.springblade.core.log.logger.BladeLogger;
import org.springblade.modules.distribution.entity.DistributionConfig;
import org.springblade.modules.distribution.service.ICommissionService;
import org.springblade.modules.distribution.service.IDistributionConfigService;
import org.springblade.modules.distribution.vo.CommissionVO;
import org.springblade.modules.finance.service.IWxPayService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * Author pangqijun
 * Date 2023/6/20
 * Description 分佣结算定时器
 */
@Slf4j
@Component("commissionSettlementTask")
public class CommissionSettlementTask {

    @Resource
    private IDistributionConfigService distributionConfigService;
    @Resource
    private ICommissionService commissionService;
    @Resource
    private IWxPayService wxPayService;
    @Resource
    private BladeLogger logger;


    public void execute() {
        DistributionConfig config = distributionConfigService.lambdaQuery().one();
        List<CommissionVO> list = commissionService.getNotPayouts(config.getSettleDays());
        log.info("待分佣数据:[{}]", list.size());
        if (CollUtil.isNotEmpty(list)) {
            for (CommissionVO vo : list) {
                boolean result = wxPayService.profitSharing(vo.getThirdOrderNo(), vo.getOrderNo(), vo.getOpenId(),
                        (int) (vo.getAmount().doubleValue() * 100), "分佣结算");
                logger.info("分佣结算", "结算订单号:" + vo.getOrderNo() + ", 受益人:" + vo.getBenefitUserName()
                        + ", 佣金:" + vo.getAmount().toString() + "元, 结算结果:" + (result ? "成功" : "失败"));
                if (result) {
                    vo.setIsPayouts(YesOrNoEnum.YES.getValue());
                    commissionService.updateById(vo);
                }
            }
        }
    }
}
