package com.clx.performance.job.position;

import com.alibaba.fastjson.JSON;
import com.clx.order.enums.DeleteStatusEnum;
import com.clx.performance.constant.RedisConstants;
import com.clx.performance.dao.OrderChildDao;
import com.clx.performance.dao.TruckPositionDao;
import com.clx.performance.dto.zjxl.TruckTraceDTO;
import com.clx.performance.model.OrderChild;
import com.clx.performance.model.TruckPosition;
import com.clx.performance.service.trace.TruckTraceService;
import com.clx.performance.vo.pc.trace.DriverTraceVO;
import com.clx.user.feign.TruckFeign;
import com.clx.user.feign.UserClxFeign;
import com.clx.user.vo.feign.TruckOwnerInfoVO;
import com.msl.common.enums.ResultCodeEnum;
import com.msl.common.job.JobLog;
import com.msl.common.result.Result;
import com.msl.common.utils.DateUtils;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 车辆位置;
 *
 * @author : jiangwenye
 * @date : 2024-05-29
 */
@Slf4j
@Component
public class TruckPositionJob {

    @Autowired(required = false)
    UserClxFeign userClxFeign;
    @Autowired(required = false)
    TruckFeign truckFeign;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    TruckTraceService truckTraceService;
    @Autowired
    OrderChildDao orderChildDao;
    @Autowired
    TruckPositionDao truckPositionDao;

    /**
     * 车辆位置
     */
    @XxlJob("truckPosition")
    public void truckPosition() {
        try {
            getPlatformTruckPosition();
        } catch (Exception e) {
            log.warn("定时任务获取平台车辆当前定位信息失败，异常原因:{}",e);
            JobLog.error("定时任务获取平台车辆当前定位信息失败，异常原因=====================", e);
        }
    }

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

        if(Objects.equals(result.getCode(), ResultCodeEnum.SUCCESS.getCode())){

            List<TruckPosition> truckPositionList = new ArrayList<>();
            List<String> truckNos = result.getData();

            //处理不在内的车牌号均至为失效
            truckPositionDao.updateTruckPositionStatus(DeleteStatusEnum.YES.getCode(),truckNos);

            if(CollectionUtils.isEmpty(truckNos)){
                return;
            }

            //有效运单集合
            List<OrderChild> orderChildList = orderChildDao.selectListWithEmptyCarList();
            Map<String, OrderChild> truckChildStatusMap = orderChildList.stream()
                    .collect(Collectors.toMap(item -> item.getTruckNo(), item -> item,(v1,v2) -> v1));

            //获取缓存中所有车辆位置信息
            Map<String, TruckTraceDTO> truckTraceMap =
                    redisTemplate.opsForHash().entries(RedisConstants.ZJXL_TRUCK_TRACE_LIST);

            LocalDateTime now = LocalDateTime.now();
            LocalDateTime beginTime = now.plus(-5, ChronoUnit.MINUTES);
            String beginTimeStr = DateUtils.formatDateTime(beginTime, "yyyy-MM-dd HH:mm:ss").get();
            String endTimeStr = DateUtils.formatDateTime(now, "yyyy-MM-dd HH:mm:ss").get();

            //既没接单 又没有中交兴路坐标的车辆集合
            List<String> noZJXLNoChildTruckNos = new ArrayList<>();

            for(String truckNo : truckNos){

                TruckTraceDTO trace = truckTraceMap.get(truckNo);
                OrderChild child = truckChildStatusMap.get(truckNo);

                if(Objects.isNull(trace)){
                    //无中交轨迹
                    TruckPosition position = new TruckPosition();
                    position.setTruckNo(truckNo);
                    position.setDeleteStatus(DeleteStatusEnum.NO.getCode());
                    Long userNo = null;
                    if(Objects.isNull(child)){
                        //车辆当前没有运单 取车主手机位置
                        Result<TruckOwnerInfoVO> truckOwnerResult = truckFeign.getTruckOwnerInfo(truckNo);
                        if(Objects.equals(truckOwnerResult.getCode(), ResultCodeEnum.SUCCESS.getCode())){
                            userNo = truckOwnerResult.getData().getUserNo();
                        }
                    }else{
                        position.setChildNo(child.getChildNo());
                        //车辆有运单 取运单司机手机位置
                        userNo = child.getDriverUserNo();
                    }
                    if(Objects.nonNull(userNo)){
                        List<DriverTraceVO> traceVOS =
                                truckTraceService.listDriverTraceByTime(userNo,beginTimeStr,endTimeStr);
                        if(!CollectionUtils.isEmpty(traceVOS)){
                            position.setLatitude(traceVOS.get(0).getLatitude());
                            position.setLongitude(traceVOS.get(0).getLongitude());
                        }
                    }
                    truckPositionList.add(position);
                }else{
                    //有中交轨迹
                    TruckPosition position = new TruckPosition();
                    position.setTruckNo(truckNo);
                    position.setDeleteStatus(DeleteStatusEnum.NO.getCode());
                    if(Objects.nonNull(child)){
                        position.setChildNo(child.getChildNo());
                    }
                    BigDecimal[] location = trace.getLocation();
                    if(location.length > 1){
                        position.setLatitude(location[1]);
                        position.setLongitude(location[0]);
                    }
                    truckPositionList.add(position);
                }
            }
            //保存
            truckPositionDao.replaceTruckPosition(truckPositionList);
        }else{
            log.info("通过clx-user服务获取平台认证成功车辆，获取失败");
        }
    }


}
