package com.xxfc.platform.vehicle.jobhandler;

import com.xxfc.platform.universal.entity.Dictionary;
import com.xxfc.platform.universal.feign.ThirdFeign;
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;

       @Autowired
       private ThirdFeign thirdFeign;


       private static  final  String DIC_VEHICLE_TYPE="VEHICLE";
       private static  final  String DIC_VEHICLE_CODE="VEHICLE_JOB";

    @Override
    public ReturnT<String> execute(String s) throws Exception {
        try {
            List<String> existVehicleIds = vehicleBiz.findExistVehicleIds();
            Dictionary dictionary = thirdFeign.findDictionaryByTypeAndCode(DIC_VEHICLE_TYPE, DIC_VEHICLE_CODE);
            LocalDate date = LocalDate.now();
            int year = date.getYear();
            int nowMonth = date.getMonthValue();
            int betweenMonth = Integer.valueOf(dictionary.getDetail()).intValue();
            int month = nowMonth +  betweenMonth> 12 ? (betweenMonth + nowMonth) - 12 : nowMonth + betweenMonth;
            year = month > nowMonth ? year : year + 1;
            String yearAndMonth = String.format("%d-%s", year, month>10?month:"0"+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;
        }
    }
}
