package com.xxfc.platform.vehicle.jobhandler;

import com.xxfc.platform.vehicle.biz.VehicleBiz;
import com.xxfc.platform.vehicle.biz.VehicleBookInfoBiz;
import com.xxfc.platform.vehicle.entity.VehicleBookInfo;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author libin
 * @version 1.0
 * @description
 * @data 2019/8/1 11:28
 */
@JobHandler(value = "vehicle_job_handler")
@Component("vehicle_job_handler")
public class VehicleJobHandler extends IJobHandler {

       @Autowired
       private VehicleBiz vehicleBiz;

       @Autowired
       private VehicleBookInfoBiz  vehicleBookInfoBiz;

    @Override
    public ReturnT<String> execute(String s) throws Exception {
        try {
            List<String> existVehicleIds = vehicleBiz.findExistVehicleIds();
            LocalDate date = LocalDate.now();
            int year = date.getYear();
            int nowMonth = date.getMonthValue();
            int month = nowMonth + VehicleBookInfoBiz.MONTH_INTERVAL > 12 ? (VehicleBookInfoBiz.MONTH_INTERVAL + nowMonth) - 12 : nowMonth + VehicleBookInfoBiz.MONTH_INTERVAL;
            year = month > nowMonth ? year : year + 1;
            String yearAndMonth = String.format("%d-%d", year, month);
            XxlJobLogger.log("----查询到的车型ids:【{}】",existVehicleIds);
            if (CollectionUtils.isNotEmpty(existVehicleIds)) {
                List<VehicleBookInfo> bookInfos = existVehicleIds.stream().map(vehicleId -> {
                    VehicleBookInfo vehicleBookInfo = new VehicleBookInfo();
                    vehicleBookInfo.setVehicle(vehicleId);
                    vehicleBookInfo.setYearMonth(yearAndMonth);
                    return vehicleBookInfo;
                }).collect(Collectors.toList());
                vehicleBookInfoBiz.InsertBatch(bookInfos);
                XxlJobLogger.log("----插入车型对象:【{}】",bookInfos);
            }
            ReturnT returnT = new ReturnT();
            returnT.setCode(100);
            returnT.setMsg("成功");
            return returnT;
        } catch (Exception ex) {
            XxlJobLogger.log(ex);
            return FAIL;
        }
    }
}
