package cn.pluss.platform.job;

import cn.pluss.platform.MerchantRateRecordService;
import cn.pluss.platform.entity.MerchantRate;
import cn.pluss.platform.entity.MerchantRateRecord;
import cn.pluss.platform.mapper.MerchantRateMapper;
import cn.pluss.platform.userInfo.UserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

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

/**
 * 检查商户费率是否过期
 */
@Configuration
@ConditionalOnProperty(prefix = "scheduling", name = "enabled", havingValue = "true")
public class CheckMerchantRateExpireJob {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Resource
    private MerchantRateMapper merchantRateMapper;

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private MerchantRateRecordService merchantRateRecordService;

    /**
     * 检查商户交易费率是否过期 每天执行一次
     *
     */
    @Scheduled(cron = "0 0 18 1/1 * ? ")
    //@Scheduled(fixedDelay = 24 * 60 * 60 * 1000)
    public void checkMercRateExpireTask(){
        log.info("===============>检查商户交易费率是否过期定时任务开始<==================");
        Date now = new Date();
        QueryWrapper<MerchantRate> queryWrapper = new QueryWrapper<MerchantRate>().eq("isfixedDelay","0")
                .apply("date_format (endTime,'%Y-%m-%d') = date_format('" + now + "','%Y-%m-%d')");
        List<MerchantRate> rateList = merchantRateMapper.selectList(queryWrapper);
        if(rateList.isEmpty()){
            log.info("===============>未筛选出符合条件的数据，检查商户交易费率是否过期定时任务结束<==================");
            return;
        }
        log.info("===============>即将过期的商户费率数据条数为：{}<==================",rateList.size());
        rateList.forEach(r ->{

            MerchantRateRecord rateRecord = new MerchantRateRecord();

            Integer rate = r.getPreviousRate();
            Integer pRate = r.getRate();
            r.setRate(rate);
            r.setPreviousRate(pRate);
            r.setUpdateTime(new Date());
            r.setEndTime(null);
            r.setStartTime(null);
            r.setIsFixedRate("1");
            merchantRateMapper.updateById(r);
            userInfoService.changeRate(r.getUserId(),rate);

            //添加费率修改记录
            rateRecord.setUserId(r.getUserId());
            rateRecord.setRate(rate);
            rateRecord.setCreateTime(new Date());
            merchantRateRecordService.save(rateRecord);


            log.info("===============>商户userId为：{},更新费率为:{}成功!<==================",r.getUserId(),rate);
        });
        log.info("===============>检查商户交易费率是否过期定时任务结束<==================");
    }
}
