package track.task;

import adi.model.ADIUser;
import adi.service.ADIAccountService;
import common.model.Contract;
import common.model.PackageBase;
import common.repository.ContractRepository;
import common.repository.PackageBaseRepository;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import util.DateUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liyin
 * @description
 * @date
 */
public class CASIPSendTimeTask {
    private final Logger logger = LoggerFactory.getLogger(CASIPSendTimeTask.class);

    @Autowired
    ADIAccountService adiAccountService;
    @Autowired
    ContractRepository contractRepository;
    @Autowired
    PackageBaseRepository packageBaseRepository;


    public void task(){
        logger.info("CAS的IP定制发送日定时任务");
        List<PackageBase> packageBases = packageBaseRepository.findByPlatAndStatus("cas", 1);
        Map<Long, PackageBase> packageBaseMap = new HashMap<>();
        for (PackageBase base : packageBases) {
            packageBaseMap.put(base.getId(), base);
        }
        List<Contract> contracts = contractRepository.findByPlatformAndShareSign("cas",0);
        for (Contract contract : contracts) {
            PackageBase packageBase = packageBaseMap.get(contract.getPriceLevel());
            ADIUser adiUser = adiAccountService.findOne(contract.getEmail(), packageBase==null?"":packageBase.getPackageName());
            if(adiUser!=null&&!StringUtils.isEmpty(adiUser.getSendTime())){
                contract.setShareSign(1);
                DateTime sendTime = new DateTime(DateUtil.parseDate(DateUtil.C_TIME_PATTON_DEFAULT,adiUser.getSendTime()));

                DateTime startDate = new DateTime(contract.getStartDate());
                if(sendTime.isBefore(startDate)){
                    sendTime = startDate;
                }
                DateTime endDate = new DateTime(contract.getEndDate());
                String validStartDateStr = sendTime.toString(DateUtil.C_DATE_PATTON_DEFAULT);
                int contractAllDay = Days.daysBetween(startDate, endDate).getDays();//合同总天数-1 ,用于计算结束日期
                String validEndDateStr = sendTime.plusDays(contractAllDay).toString("yyyy-MM-dd");
                contract.setValidStartDate(validStartDateStr);
                contract.setValidEndDate(validEndDateStr);
                contractRepository.save(contract);
            }
        }
    }
}
