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 lombok.RequiredArgsConstructor;
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")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class VehicleJobHandler extends IJobHandler {

       private final  VehicleBiz vehicleBiz;

       private final  VehicleBookInfoBiz  vehicleBookInfoBiz;

       private final 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();
            date = date.plusMonths(Integer.valueOf(dictionary.getDetail()));
            int year = date.getYear();
            int month = date.getMonthValue();
            String yearAndMonth = String.format("%d-%02d", 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;
        }
    }
}
