package com.clx.performance.job;

import com.alibaba.fastjson.JSON;
import com.clx.open.sdk.callback.OpenCallBackClient;
import com.clx.open.sdk.callback.dto.OrderChildExpectTimeDTO;
import com.clx.open.sdk.callback.message.OrderChildExpectTimeMessage;
import com.clx.order.enums.SyncPlatformEnum;
import com.clx.order.feign.OrderFeign;
import com.clx.performance.config.ThirdAppConfig;
import com.clx.performance.dao.OrderChildDao;
import com.clx.performance.dto.OrderChildExpectDTO;
import com.clx.performance.enums.OrderChildEnum;
import com.clx.performance.extranal.user.DriverService;
import com.clx.performance.listener.OrderChildDtsListener;
import com.clx.performance.model.OrderChild;
import com.clx.performance.service.OrderChildService;
import com.clx.performance.struct.OrderChildStruct;
import com.clx.performance.utils.LocalDateTimeUtils;
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.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Component
@AllArgsConstructor
public class PushOrderChildExpectTimeJob {

    private final OrderChildDao orderChildDao;
    private final OrderFeign orderFeign;
    private final OrderChildService orderChildService;
    private final OrderChildStruct orderChildStruct;
    private final DriverService driverService;
    private final ThirdAppConfig thirdAppConfig;
    private final OrderChildDtsListener orderChildDtsListener;
    /**
     * 推送运单预计时间到对应的平台
     */
    @XxlJob("pushOrderChildExpectTimeJob")
    public void pushOrderChildExpectTimeJob() {
        try {
            pushOrderChildExpectTime2ThirdPlatform();
        } catch (Exception e) {
            log.warn("定时任务推送运单预计时间到对应的平台失败，异常原因:{}", ExceptionUtils.getStackTrace(e));
            JobLog.error("定时任务获取平台车辆定位信息失败，异常原因=====================", e);
        }
    }

    //数媒宝对应的运单进行实时预计时间推送
    public void pushOrderChildExpectTime2ThirdPlatform(){
        log.info("开始查询承运系统未到达目的地前的运单开始===================");
        LocalDateTime endTime = LocalDateTime.now();
        LocalDateTime startTime = endTime.minusMonths(1);
        List<OrderChild> list = orderChildDao.listBeforeUnloadOrderChild(startTime,endTime);
        log.info("查询到承运系统未到达目的地前的运单条数：{} 条",list.size());
        if(CollectionUtils.isNotEmpty(list)){
            List<String> orderNoList = list.stream().map(OrderChild::getOrderNo).collect(Collectors.toList());
            Result<Map<String, Integer>> mapResult = orderFeign.queryListOrderSource(orderNoList);
            if(!mapResult.succeed()){
                log.warn("通过订单编号查询订单来源信息失败，响应结果:{}",mapResult);
                return;
            }
            Map<String, Integer> orderSourceMap = mapResult.getData();
            List<OrderChildExpectTimeDTO> syncSmbExpectList = new ArrayList<>();   //同步数媒宝预计时间list
            List<OrderChildExpectTimeDTO> syncNewOwnerClientExpectList = new ArrayList<>(); //同步马上来供应链预计时间list

            list.forEach(item->{
                //交易平台数媒宝同步运单同步实时预计时间
                if(Objects.equals(orderSourceMap.get(item.getOrderNo()),SyncPlatformEnum.Source.TRADE_PLATFORM.getCode())
                || Objects.equals(orderSourceMap.get(item.getOrderNo()),SyncPlatformEnum.Source.NEW_OWNER_CLIENT.getCode())){
                    List<OrderChildExpectDTO> expectList = orderChildService.getOrderChildExpect(
                            item.getChildNo());
                    if(CollectionUtils.isEmpty(expectList) ||  StringUtils.isBlank(expectList.get(0).getCreateTime())){
                        log.info("运单号：{} 未从缓存中查询到对应的预计时间信息",item.getChildNo());
                        return;
                    }
                    OrderChildExpectDTO orderChildExpect = expectList.get(0);
                    LocalDateTime calcExpectTime = DateUtils.parseDateTime(orderChildExpect.getCreateTime()).get();
                    //如果缓存预计时间 插入的不是10分钟之内的，则不进行使用
                    if(LocalDateTimeUtils.betweenMin(calcExpectTime,LocalDateTime.now()) > 10){
                        log.info("运单号：{} 从缓存中查询到对应的预计时间信息超过10分钟，不进行使用",item.getChildNo());
                        return;
                    }

                    OrderChildExpectTimeDTO dto = new OrderChildExpectTimeDTO();
                    dto.setOrderNo(item.getOrderNo());
                    dto.setChildNo(item.getChildNo());
                    dto.setStatus(item.getStatus());

                    if(item.getStatus() < OrderChildEnum.Status.ARRIVE_SEND.getCode()){  //到达货源地之前
                        dto.setExpectArriveTime(orderChildExpect.getExpectArriveTime());
                    }else{    //到达货源地之后 && 到达目的地之前
                        dto.setExpectReceiveTime(orderChildExpect.getExpectReceiveTime());
                    }
                    if(Objects.equals(orderSourceMap.get(item.getOrderNo()),SyncPlatformEnum.Source.TRADE_PLATFORM.getCode())){
                        syncSmbExpectList.add(dto);
                        //集煤宝的运单预计时间也要同步给马上来供应链，马上来供应链同步给场站
                        syncNewOwnerClientExpectList.add(dto);

                    }
                    if(Objects.equals(orderSourceMap.get(item.getOrderNo()),SyncPlatformEnum.Source.NEW_OWNER_CLIENT.getCode())){
                        syncNewOwnerClientExpectList.add(dto);
                    }
                }
            });
            if(CollectionUtils.isNotEmpty(syncSmbExpectList)){
                OrderChildExpectTimeMessage message = new OrderChildExpectTimeMessage();
                message.setList(syncSmbExpectList);
                String data = JSON.toJSONString(message);
                OpenCallBackClient openCallBackClient = thirdAppConfig.getOpenCallBackClient(
                        SyncPlatformEnum.Source.TRADE_PLATFORM.getCode().toString());
                log.info("数媒宝=====》运单预计时间信息同步开始，请求参数:{}",data);
                Result<?> result = openCallBackClient.encryptPost(data,message.topic());
                log.info("数媒宝=====》运单预计时间信息同步，响应结果:{}",JSON.toJSONString(result));
            }

            if(CollectionUtils.isNotEmpty(syncNewOwnerClientExpectList)){
                OrderChildExpectTimeMessage message = new OrderChildExpectTimeMessage();
                message.setList(syncNewOwnerClientExpectList);
                String data = JSON.toJSONString(message);
                OpenCallBackClient openCallBackClient = thirdAppConfig.getOpenCallBackClient(
                        SyncPlatformEnum.Source.NEW_OWNER_CLIENT.getCode().toString());
                log.info("马上来供应链=====》运单预计时间信息同步开始，请求参数:{}",data);
                Result<?> result = openCallBackClient.encryptPost(data,message.topic());
                log.info("马上来供应链=====》运单预计时间信息同步，响应结果:{}",JSON.toJSONString(result));
            }
        }
    }

}
