package com.sckw.usual.service;

import cn.hutool.core.collection.CollectionUtil;
import com.sckw.usual.entity.*;
import com.sckw.usual.enums.CarWaybillEnum;
import com.sckw.usual.mapper.*;
import com.sckw.core.model.constant.Global;
import com.sckw.core.utils.*;
import com.sckw.core.model.enums.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author lfdc
 * @description 运输服务公共service接口
 * @date 2023-06-29 15:06:45
 */
@Slf4j
@Service
public class TransportCommonService {


    @Autowired
    public OrderGeneralTransportGoodsMapper logisticsOrderGoodsMapper;

    //@Autowired
    //public KwtLogisticsOrderContractMapper logisticsOrderContractMapper;

    @Autowired
    public OrderGeneralTransportMapper logisticsOrderMapper;

    @Autowired
    public KwOrderUsualLandTransportAddressMapper logisticsOrderAddressMapper;

    @Autowired
    public KwOrderUsualLandTransportTrackMapper logisticsOrderTrackMapper;

    @Autowired
    public KwOrderUsualLandTransportUnitMapper logisticsOrderUnitMapper;

    @Autowired
    public KwWaybillOrderMapper waybillOrderMapper;

    @Autowired
    public KwOrderUsualLandTransportCirculateMapper kwOrderUsualLandTransportCirculateMapper;
    @Autowired
    public KwWaybillOrderTrackMapper kwWaybillOrderTrackMapper;



    /**
     * @param lOrderId 承运订单ID
     * @desc 完结物流订单数据处理
     * @author zk
     * @date 2023/9/18
     **/
    public void closeHandle(Long lOrderId) {
        /**1数据校验**/
        KwOrder logisticsOrder = logisticsOrderMapper.selectById(lOrderId);
        if (logisticsOrder == null) {
            return;
        }

        /**2物流订单树形数据结构**/
        //所有管理物流订单
        System.out.println("0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-");
        List<KwOrder> orders = logisticsOrderMapper.findLogisticsOrder(new HashMap(Global.NUMERICAL_SIXTEEN) {{
            put("plOrderIds", lOrderId);
            put("currentlOrderId", logisticsOrder.getPids());
            put("allOrderId", Global.NUMERICAL_ONE);
        }});
        //数据copy
        List<KwOrderTreeVo> logisticsOrders = new ArrayList<>();
        for (KwOrder order : orders) {
            KwOrderTreeVo logisticsOrderVo = new KwOrderTreeVo();
            BeanUtils.copyProperties(order, logisticsOrderVo);
            logisticsOrders.add(logisticsOrderVo);
        }
        List<KwOrderTreeVo> treeData = findTree(logisticsOrders);
        //数据去除已完结订单下级
        orderTreeHandle(treeData);

        /**3链路数据组装*/
        List<List<KwOrderTreeVo>> orderLinks = new ArrayList<>();
        for (KwOrderTreeVo order : treeData) {
            Stack<KwOrderTreeVo> pathStack = new Stack<>();
            iteratorNode(order, pathStack, orderLinks);
        }
        List<KwOrderTreeVo> orderLink = findLink(orderLinks, lOrderId);
        //倒序
        assert orderLink != null;
        Collections.reverse(orderLink);

        /**4数据处理**/
        for (KwOrderTreeVo order : orderLink) {
            //排除已完结订单
            if (Objects.equals(order.getStatus(), OrderUsualStatusEnum.FINISHED.getCode())) {
                //上级物流订单分包量技术-排除一级物流订单
                if (order.getPid() != null) {
                    //mysql数据更新
                    KwOrder currentOrder = logisticsOrderMapper.selectById(order.getPid());
                    //差值=上游委托量-实际总装货量
                    BigDecimal difference = order.getAmount().subtract(order.getTotalLoadAmount());
                    currentOrder.setSubcontractAmount(currentOrder.getSubcontractAmount().subtract(difference));
                    logisticsOrderMapper.updateById(currentOrder);

                    //Mongodb数据更新
                    //SckwLogisticsOrder lOrder = new SckwLogisticsOrder();
                    //lOrder.setSubcontractAmount(currentOrder.getSubcontractAmount());
                    //waybillOrderService.editSckwLogisticsOrder(lOrder, currentOrder);
                }
            }

            ////车辆运单统计(运输中的物流订单+车辆运单审核通过)
            //KwWaybillCountVo waybillCount = waybillOrderMapper.findWaybillOrderCount(new HashMap<String, Object>(Global.NUMERICAL_SIXTEEN) {{
            //    //put("ownOrderId", order.getId());
            //    put("upperlOrderId", order.getId());
            //    put("passStatus", Global.NUMERICAL_ONE);
            //    put("logisticsStatus", OrderStatusEnum.IN_TRANSIT.getCode());
            //}});
            ////物流订单统计(运输完成后的物流订单)
            //LogisticsCountVo LogisticsCount = logisticsOrderMapper.findLogisticsOrderCount(new HashMap<String, Object>(Global.NUMERICAL_SIXTEEN) {{
            //    put("upperlOrderId", order.getId());
            //    put("finishedStatus", Global.NUMERICAL_ONE);
            //}});
            //
            ////mysql数据更新
            //KwOrder currentOrder = logisticsOrderMapper.selectById(order.getId());
            //currentOrder.setTotalLoadAmount(waybillCount.getLoadAmount().add(LogisticsCount.getTotalLoadAmount()));
            //currentOrder.setTotalUnloadAmount(waybillCount.getUnloadAmount().add(LogisticsCount.getTotalUnloadAmount()));
            //logisticsOrderMapper.updateById(currentOrder);

        }
    }

    /**
     * @param treeData 物流订单树形数据
     * @desc 数据去除已完结订单下级
     * @author zk
     * @date 2023/9/18
     **/
    public static void orderTreeHandle(List<KwOrderTreeVo> treeData) {
        if (CollectionUtil.isEmpty(treeData)) {
            return;
        }

        for (KwOrderTreeVo order : treeData) {
            orderTreeHandle(order.getChildren());
            if (order.getStatus() == OrderUsualStatusEnum.FINISHED.getCode()) {
                order.setChildren(null);
            }
        }
    }

    /**
     * @param orders 物流订单
     * @desc 树形数据处理
     * @author zk
     * @date 2023/9/18
     **/
    public static List<KwOrderTreeVo> findTree(List<KwOrderTreeVo> orders) {
        //跟节点
        List<KwOrderTreeVo> rootList = new ArrayList();

        //获取根节点数据
        if (CollectionUtil.isNotEmpty(orders)) {
            for (KwOrderTreeVo order : orders) {
                if (order.getPid() == null) {
                    rootList.add(order);
                }
            }
        }

        //遍历，找到二级节点（根节点的id和所有节点中的pid比较）
        for (KwOrderTreeVo order : rootList) {
            List<KwOrderTreeVo> child = getChild(order.getId(), orders);
            order.setChildren(child);
        }

        return rootList;
    }

    /**
     * @param pid    上级物流订单ID
     * @param orders 物流订单
     * @desc 树形数据处理-递归
     * @author zk
     * @date 2023/9/18
     **/
    public static List<KwOrderTreeVo> getChild(Long pid, List<KwOrderTreeVo> orders) {
        List<KwOrderTreeVo> childList = new ArrayList();
        for (KwOrderTreeVo order : orders) {
            if (pid.equals(order.getPid())) {
                //获取当前节点id的所有子列表
                childList.add(order);
            }
        }
        for (KwOrderTreeVo order : childList) {
            //将该id的子节点进行遍历，通过递归调用，获取每一个子节点的子节点数据
            List<KwOrderTreeVo> child = getChild(order.getId(), orders);
            order.setChildren(child);
        }
        if (childList.size() == 0) {
            //子节点的长度为0,返回null,null不会被阿里的FastJson包解析
            return null;
        }
        return childList;
    }

    /**
     * @param: order 当前节点
     * @param: pathstack 栈
     * @param: orderLinks 设备链路信息
     * @desc 链路组装
     * @author zk
     * @date 2023/8/8
     **/
    public static void iteratorNode(KwOrderTreeVo order, Stack<KwOrderTreeVo> pathstack, List orderLinks) {
        //入栈
        pathstack.push(order);
        List childlist = order.getChildren();
        //没有子节点 说明是叶子结点
        if (childlist == null) {
            List list = new ArrayList();
            Iterator stackIt = pathstack.iterator();
            while (stackIt.hasNext()) {
                list.add(stackIt.next());
            }
            List<KwOrderTreeVo> orders = print(list);
            orderLinks.add(orders);
        } else {
            Iterator iterator = childlist.iterator();
            while (iterator.hasNext()) {
                KwOrderTreeVo child = (KwOrderTreeVo) iterator.next();
                //深度优先 进入递归
                iteratorNode(child, pathstack, orderLinks);
                //回溯时候出栈
                pathstack.pop();
            }
        }
    }

    /**
     * @param list 树形数据
     * @desc 链路组装
     * @author zk
     * @date 2023/8/8
     **/
    private static List<KwOrderTreeVo> print(List list) {
        List<KwOrderTreeVo> orders = new ArrayList();
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            KwOrderTreeVo order = (KwOrderTreeVo) iterator.next();
            order.setChildren(null);
            orders.add(order);
        }
        return orders;
    }

    /**
     * @param orderLinks 物流订单链路信息
     * @param lOrderId   物流订单id
     * @desc 获取当前物流订单垂直链路
     * @author zk
     * @date 2023/9/18
     **/
    public static List<KwOrderTreeVo> findLink(List<List<KwOrderTreeVo>> orderLinks, Long lOrderId) {
        for (List<KwOrderTreeVo> logisticsOrders : orderLinks) {
            for (KwOrderTreeVo order : logisticsOrders) {
                if (Objects.equals(lOrderId, order.getId())) {
                    return logisticsOrders;
                }
            }
        }
        return null;
    }

    public void cancelSendCar(Long lorderId) {
        /**1数据校验**/
        KwOrder order = logisticsOrderMapper.selectById(lorderId);
        if (order == null) {
            return;
        }

        /**1-5循环派车失效kwt_logistics_order_circulate**/
        //趟次派车信息
        List<KwWaybillOrder> waybillOrders = waybillOrderMapper.findWaybillOrder(new HashMap<String, Object>(Global.NUMERICAL_SIXTEEN) {{
            put("lOrderId", lorderId);
            put("status", CarWaybillEnum.ONE.getCode());
        }});
        for (KwWaybillOrder waybillOrder : waybillOrders) {
            waybillOrder.setStatus(CarWaybillEnum.SEVEN.getCode());
            waybillOrderMapper.updateById(waybillOrder);
            setWaybillOrderTrack(waybillOrder.getId(), waybillOrder.getUpdateTime(), waybillOrder.getStatus(), "完结物流订单时撤回车辆运单！");

            //车辆订单-Mongodb数据更新
            //SckwWaybillOrder wOrder = new SckwWaybillOrder();
            //wOrder.set_id(waybillOrder.getId());
            //editSckwWaybillOrder(wOrder, waybillOrder, 2);
        }

        //循环派车信息
        List<KwOrderUsualLandTransportCirculate> circulates = kwOrderUsualLandTransportCirculateMapper.findCirculateList(lorderId, null, null, 0);
        for (KwOrderUsualLandTransportCirculate circulate : circulates) {
            circulate.setStatus(Global.NUMERICAL_ONE);
            circulate.setRemark("完结物流订单时撤回车辆运单！");
            kwOrderUsualLandTransportCirculateMapper.updateById(circulate);

            //车辆订单-Mongodb数据更新
            //SckwWaybillOrder wOrder = new SckwWaybillOrder();
            //wOrder.set_id(circulate.getId());
            //KwtWaybillOrder waybillOrder = new KwtWaybillOrder();
            //waybillOrder.setStatus(CarWaybillEnum.REVOKED.getCode());
            //waybillOrder.setUpdateTime(circulate.getUpdateTime());
            //waybillOrder.setUpdateBy(circulate.getUpdateBy());
            //editSckwWaybillOrder(wOrder, waybillOrder, 2);
        }
    }

    public KwWaybillOrderTrack setWaybillOrderTrack(Long wOrderId, Date operateTime, int status, String remark) {
        KwWaybillOrderTrack orderTrack = new KwWaybillOrderTrack();
        orderTrack.setTOrderId(wOrderId);
        orderTrack.setOperateTime(operateTime);
        orderTrack.setStatus(status);
        orderTrack.setRemark(remark);
        int count = kwWaybillOrderTrackMapper.insert(orderTrack);
        return count > 0 ? orderTrack : null;
    }

}
