package com.dayou.brokerage.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dayou.common.BaseEntity;
import com.dayou.configuration.AsyncManager;
import com.dayou.entity.ItemBrokerageSequence;
import com.dayou.message.handler.SystemMessageHandler;
import com.dayou.service.IItemBrokerageSequenceService;
import com.dayou.service.IMessageService;
import com.dayou.utils.DateUtils;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Set;

import static com.dayou.brokerage.constants.BrokerageMsg.BROKERAGE_SEQUENCE_EMBODY;
import static com.dayou.common.Constants.YEARMONTH;

/**
 * 类说明：
 *
 * @author: wucl
 * @since: 2023/3/27
 * created with IntelliJ IDEA.
 */
@Slf4j
@Component
public class BrokerageSettleSchedule {

    @Autowired
    private IItemBrokerageSequenceService itemBrokerageSequenceService;

    @Autowired
    private IMessageService messageService;


    //@Scheduled(cron = "0 0/1 * * * ?")
    @Scheduled(cron = "59 59 23 23 * ?")
    public void doBrokerageSettle(){
        AsyncManager.me().execute(new AsyncManager.BizHandler() {
            @Override
            public Boolean validBefore() {
                Date now = new Date();
                int year = DateUtils.getYear(now);
                int month = DateUtils.getMonth(now);
                String embody = BROKERAGE_SEQUENCE_EMBODY.replace(YEARMONTH, year + "-" + (month));
                int count = itemBrokerageSequenceService.count(new LambdaQueryWrapper<ItemBrokerageSequence>().eq(ItemBrokerageSequence::getEmbody, embody).eq(BaseEntity::getDeleted, Boolean.FALSE));
                if (count!=0){
                    log.info(embody+"提成已被结算,无需重复结算.");
                    return Boolean.FALSE;
                }
                return Boolean.TRUE;
            }

            @Override
            public Object doCustom() {
                log.info("市场人员结算程序开始执行...");
                Set<Long> marketers = itemBrokerageSequenceService.doAbleItemBrokerageSettle();
                log.info("市场人员结算程序执行完成");
                log.info("技术人员默认预提结算程序开始执行...");
                Set<Long> techs = itemBrokerageSequenceService.doNonMarketerAheadSettle();
                log.info("技术人员默认预提结算程序开始执行完成");
                Set<Long> userIds= Sets.newHashSet();
                userIds.addAll(marketers);
                userIds.addAll(techs);
                messageService.packagingSettleMessage(userIds);
                return null;
            }
        }, AsyncManager.AsyncLockStrategy.LOCK_BIZ, AsyncManager.AsyncBiz.BROKERAGE_SETTLE);
    }
}

