package cn.com.poc.equity.scheduler;


import cn.com.poc.common.constant.CommonConstant;
import cn.com.poc.common.utils.DateUtils;
import cn.com.poc.equity.aggregate.MemberEquityService;
import cn.com.poc.equity.constants.EquityEnum;
import cn.com.poc.equity.constants.ModifyEventEnum;
import cn.com.poc.equity.domain.modifyEquityInfo.ExpiredModifyEventInfo;
import cn.com.poc.equity.entity.BizMemberEquityEntity;
import cn.com.poc.equity.service.BizMemberEquityService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

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

@Component
public class MemberEquityScheduler {

    @Resource
    private MemberEquityService memberEquityService;

    @Resource
    private BizMemberEquityService bizMemberEquityService;

    /**
     * 权益信息状态更新-【过期】
     * 每分钟执行一次
     *
     * @throws Exception
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void memberEquityExpiredStatus() throws Exception {
        BizMemberEquityEntity bizMemberEquityEntity = new BizMemberEquityEntity();
        bizMemberEquityEntity.setIsDeleted(CommonConstant.IsDeleted.N);
        List<BizMemberEquityEntity> entities = bizMemberEquityService.findByExample(bizMemberEquityEntity, null);
        if (CollectionUtils.isEmpty(entities)) {
            return;
        }
        Date currDateTime = DateUtils.getCurrDateTime();
        for (BizMemberEquityEntity entity : entities) {
            if (entity.getEquityLevel().equals(EquityEnum.TYPE.normal.name())) {
                continue;
            }
            if (currDateTime.after(entity.getExpiredDate())) {
                ExpiredModifyEventInfo expiredModifyEventInfo = new ExpiredModifyEventInfo();
                memberEquityService.changeEquityLevel(entity.getMemberId(), ModifyEventEnum.expired, EquityEnum.TYPE.normal, EquityEnum.VALIDITY_UNIT.indefinite, expiredModifyEventInfo);
            }
        }


    }
}
