package com.clx.performance.job;

import com.alibaba.fastjson.JSON;
import com.clx.performance.constant.RedisConstants;
import com.clx.performance.dto.zjxl.TruckTraceDTO;
import com.clx.performance.utils.LocalDateTimeUtils;
import com.clx.performance.utils.zjxl.ZjxlGpsService;
import com.clx.user.feign.UserClxFeign;
import com.msl.common.enums.ResultCodeEnum;
import com.msl.common.job.JobLog;
import com.msl.common.result.Result;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@Component
public class TruckTraceJob {

    @Autowired(required = false)
    UserClxFeign userClxFeign;
    @Autowired
    ZjxlGpsService zjxlGpsService;
    @Autowired
    RedisTemplate redisTemplate;



    /**
     * 驾驶证过期
     */
    @XxlJob("truckTrace")
    public void truckTrace() {
        try {
            getPlatformTruckTrace();
        } catch (Exception e) {
            log.warn("定时任务获取平台车辆定位信息失败，异常原因:{}", ExceptionUtils.getStackTrace(e));
            JobLog.error("定时任务获取平台车辆定位信息失败，异常原因=====================", e);
        }
    }

    /**
     * @Author kavin
     * @Description 定时获取平台车辆的定位
     * @Param []
     * @return
     **/
    public void getPlatformTruckTrace(){
        Result<List<String>> result = userClxFeign.getPlatformTruckList();
        log.info("通过clx-user服务获取平台认证成功车辆，返回结果:{}", JSON.toJSONString(result));
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime beginTime = now.minusMinutes(5);
        if(Objects.equals(result.getCode(), ResultCodeEnum.SUCCESS.getCode())){

            //本次拉取定位信息成功的车辆
            List<String> pullTruckList = new ArrayList<>();

            // 测试白名单
            result.setData(Arrays.asList("晋HG9859", "陕KK6523"));

            List<String> truckNos = result.getData();
            for(String truckNo : truckNos){
                List<TruckTraceDTO> truckTrace = zjxlGpsService.getTruckTrace(truckNo,
                        LocalDateTimeUtils.formatTime(beginTime), LocalDateTimeUtils.formatTime(now));

                if(CollectionUtils.isNotEmpty(truckTrace)){
                    TruckTraceDTO truckTraceDTO = truckTrace.get(truckTrace.size()-1);
                    truckTraceDTO.setTruckNo(truckNo);
                    redisTemplate.opsForHash().put(RedisConstants.ZJXL_TRUCK_TRACE_LIST,truckNo,truckTraceDTO);
                    log.info("放入缓存成功，滚存 key：{}，车牌号{}",RedisConstants.ZJXL_TRUCK_TRACE_LIST,truckNo);
                    pullTruckList.add(truckNo);
                }
            }
            //获取上次拉取的车辆
            if(Objects.equals(Boolean.TRUE,redisTemplate.hasKey(RedisConstants.ZJXL_LAST_PULL_TRUCK))){
                List<String> lastTimeTruck= redisTemplate.opsForList().range(RedisConstants.ZJXL_LAST_PULL_TRUCK,0,-1);//获取上次拉取的车辆列表
                //上次拉取的车辆 去除掉 本次拉运的车辆  = 本次没有拉取的车辆（可能车辆过期，删除了，所以此类数据不需要在缓存中存在了）
                if(CollectionUtils.isNotEmpty(lastTimeTruck)){
                    lastTimeTruck.removeAll(pullTruckList);
                }
                if(CollectionUtils.isNotEmpty(lastTimeTruck)){
                    //移除掉本次没拉运的定位信息
                    redisTemplate.opsForHash().delete(RedisConstants.ZJXL_TRUCK_TRACE_LIST,lastTimeTruck.toArray());
                }
                redisTemplate.delete(RedisConstants.ZJXL_LAST_PULL_TRUCK);
            }
            if(CollectionUtils.isNotEmpty(pullTruckList)){
                redisTemplate.opsForList().leftPushAll(RedisConstants.ZJXL_LAST_PULL_TRUCK,pullTruckList);
            }
        }else{
            log.info("通过clx-user服务获取平台认证成功车辆，获取失败");
        }
    }

}
