package com.sckw.car.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.sckw.car.entity.KwOrderCarLandTransportPath;
import com.sckw.car.entity.KwOrderCarLandTransportPathGoods;
import com.sckw.car.entity.res.CarDetailRes;
import com.sckw.car.entity.res.KwOrderCarLandTransportPathRes;
import com.sckw.car.entity.res.ListDetailRes;
import com.sckw.car.enums.OrderCarDictTypeEnum;
import com.sckw.car.enums.WaybillStatusEnums;
import com.sckw.car.mapper.KwCarOrderMapper;
import com.sckw.car.mapper.KwOrderCarLandTransportInventoryMapper;
import com.sckw.car.mapper.KwOrderCarLandTransportPathGoodsMapper;
import com.sckw.car.mapper.KwOrderCarLandTransportPathMapper;
import com.sckw.core.model.constant.Global;
import com.sckw.core.model.enums.OrderCarStatusEnum;
import com.sckw.core.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @desc:
 * @author: Lt
 * @date: 2024-04-17
 */
@Service
public class CarTransportListService {
    @Autowired
    KwOrderCarLandTransportInventoryMapper kwOrderCarLandTransportListMapper;

    @Autowired
    OrderCarDictService orderCarDictService;

    @Autowired
    KwOrderCarLandTransportPathMapper kwOrderCarLandTransportPathMapper;

    @Autowired
    KwOrderCarLandTransportPathGoodsMapper kwOrderCarLandTransportPathGoodsMapper;

    @Autowired
    KwCarOrderMapper kwCarOrderMapper;

    public List<ListDetailRes> listDetail(String name)
    {
        return kwOrderCarLandTransportListMapper.selectList(name);
    }

    public CarDetailRes detail(String orderId)
    {
        CarDetailRes carDetailRes = kwOrderCarLandTransportListMapper.selectByOrderId(orderId);
        if(ObjectUtils.isNotNull(carDetailRes)) {
            Map<String, Map<String, String>> dict = orderCarDictService.queryDictByType(new ArrayList<>(
                    Arrays.asList(OrderCarDictTypeEnum.TYPE_HANDLING.getType()
                            ,OrderCarDictTypeEnum.ORDER_STATUS.getType()
                            ,OrderCarDictTypeEnum.SETTLEMENT_CYCLE.getType()
                            ,OrderCarDictTypeEnum.PAY_METHOD.getType()
                            ,OrderCarDictTypeEnum.BILLING_MODE.getType()
                            ,OrderCarDictTypeEnum.GOODS_TYPE.getType()
                            ,OrderCarDictTypeEnum.GOODS_UNIT.getType()
                            ,OrderCarDictTypeEnum.TRUCK_TYPE.getType()
                    )));
            Map<String, String> typeHandlMap, truckTypeMap, orderStatusMap, billingCycleMap, payMethodMap, charingModedMap,goodsTypeMap,GoodsUnitMap;
            if (CollectionUtils.isNotEmpty(dict)) {
                typeHandlMap = CollectionUtils.isNotEmpty(dict.get(OrderCarDictTypeEnum.TYPE_HANDLING.getType())) ? dict.get(OrderCarDictTypeEnum.TYPE_HANDLING.getType()) : new HashMap<>(16);
                orderStatusMap = CollectionUtils.isNotEmpty(dict.get(OrderCarDictTypeEnum.ORDER_STATUS.getType())) ? dict.get(OrderCarDictTypeEnum.ORDER_STATUS.getType()) : new HashMap<>(16);
                billingCycleMap = CollectionUtils.isNotEmpty(dict.get(OrderCarDictTypeEnum.SETTLEMENT_CYCLE.getType())) ? dict.get(OrderCarDictTypeEnum.SETTLEMENT_CYCLE.getType()) : new HashMap<>(16);
                payMethodMap = CollectionUtils.isNotEmpty(dict.get(OrderCarDictTypeEnum.PAY_METHOD.getType())) ? dict.get(OrderCarDictTypeEnum.PAY_METHOD.getType()) : new HashMap<>(16);
                charingModedMap = CollectionUtils.isNotEmpty(dict.get(OrderCarDictTypeEnum.BILLING_MODE.getType())) ? dict.get(OrderCarDictTypeEnum.BILLING_MODE.getType()) : new HashMap<>(16);
                goodsTypeMap = CollectionUtils.isNotEmpty(dict.get(OrderCarDictTypeEnum.GOODS_TYPE.getType())) ? dict.get(OrderCarDictTypeEnum.GOODS_TYPE.getType()) : new HashMap<>(16);
                GoodsUnitMap = CollectionUtils.isNotEmpty(dict.get(OrderCarDictTypeEnum.GOODS_UNIT.getType())) ? dict.get(OrderCarDictTypeEnum.GOODS_UNIT.getType()) : new HashMap<>(16);
                truckTypeMap = CollectionUtils.isNotEmpty(dict.get(OrderCarDictTypeEnum.TRUCK_TYPE.getType())) ? dict.get(OrderCarDictTypeEnum.TRUCK_TYPE.getType()) : new HashMap<>(16);
            } else {
                typeHandlMap = new HashMap<>(16);
                orderStatusMap = new HashMap<>(16);
                billingCycleMap = new HashMap<>(16);
                payMethodMap = new HashMap<>(16);
                charingModedMap = new HashMap<>(16);
                goodsTypeMap = new HashMap<>(16);
                GoodsUnitMap = new HashMap<>(16);
                truckTypeMap = new HashMap<>(16);
            }
            if (ObjectUtils.isNotNull(carDetailRes.getTypeHandling())){
                carDetailRes.setTypeHandlingStr(typeHandlMap.get(carDetailRes.getTypeHandling().toString()));
            }
            if (ObjectUtils.isNotNull(carDetailRes.getStatus())){
                carDetailRes.setStatusStr(orderStatusMap.get(carDetailRes.getStatus().toString()));
            }
            if (ObjectUtils.isNotNull(carDetailRes.getPayment())) {
                carDetailRes.setPaymentStr(payMethodMap.get(carDetailRes.getPayment().toString()));
            }
            if (ObjectUtils.isNotNull(carDetailRes.getSettlementCycle())) {
                carDetailRes.setSettlementCycleStr(billingCycleMap.get(carDetailRes.getSettlementCycle().toString()));
            }
            if (ObjectUtils.isNotNull(carDetailRes.getBillingMode())) {
                carDetailRes.setBillingModeStr(charingModedMap.get(carDetailRes.getBillingMode().toString()));
            }
            if (ObjectUtils.isNotNull(carDetailRes.getGoodsType())) {
                carDetailRes.setGoodsTypeStr(goodsTypeMap.get(carDetailRes.getGoodsType().toString()));
            }
            if (ObjectUtils.isNotNull(carDetailRes.getGoodsUnit())) {
                carDetailRes.setGoodsUnitStr(GoodsUnitMap.get(carDetailRes.getGoodsUnit().toString()));
            }
            if (ObjectUtils.isNotNull(carDetailRes.getTruckType())) {
                carDetailRes.setTruckTypeStr(truckTypeMap.get(carDetailRes.getTruckType().toString()));
            }
            //查询路径信息
            List<KwOrderCarLandTransportPath> pathLists = kwOrderCarLandTransportPathMapper.getPathListByOrderId(orderId);
            if (!CollectionUtils.isEmpty(pathLists)) {
                List<KwOrderCarLandTransportPathRes> kwOrderCarLandTransportPaths = new ArrayList<>(pathLists.size());
                Map<String, Object> goodsListMap = null;
                for (KwOrderCarLandTransportPath path : pathLists) {
                    KwOrderCarLandTransportPathRes pathRes = new KwOrderCarLandTransportPathRes();
                    // 主键
                    pathRes.setId(path.getId());
                    // 物流订单id
                    pathRes.setOrderId(path.getOrderId());
                    // 线路id
                    pathRes.setPathId(path.getPathId());
                    // 线路名称
                    pathRes.setName(path.getName());
                    // 起始地-id
                    pathRes.setLoadId(path.getLoadAddressId());
                    // 起始地-地址名称
                    pathRes.setLoadName(path.getLoadName());
                    // 起始地-所在地区
                    pathRes.setLoadCityCode(path.getLoadCityCode());
                    // 起始地-所属区域名称
                    pathRes.setLoadCityName(path.getLoadCityName());
                    // 起始地-详细地址
                    pathRes.setLoadDetailAddress(path.getLoadDetailAddress());
                    // 起始地-纬度
                    pathRes.setLoadLat(path.getLoadLat());
                    // 起始地-经度
                    pathRes.setLoadLng(path.getLoadLng());
                    // 目的地-id
                    pathRes.setUnLoadId(path.getUnloadAddressId());
                    // 目的地-地址名称
                    pathRes.setUnloadName(path.getUnloadName());
                    // 目的地-所在地区
                    pathRes.setUnloadCityCode(path.getUnloadCityCode());
                    // 目的地-所属区域名称
                    pathRes.setUnloadCityName(path.getUnloadCityName());
                    // 目的地-详细地址
                    pathRes.setUnloadDetailAddress(path.getUnloadDetailAddress());
                    // 目的地-纬度
                    pathRes.setUnloadLat(path.getUnloadLat());
                    // 目的地-经度
                    pathRes.setUnloadLng(path.getUnloadLng());
                    // 运输里程
                    pathRes.setTransportMileage(path.getTransportMileage());
                    // 里程价(元)
                    pathRes.setTransportPrice(path.getTransportPrice());
                    // 运输数量（托运填写量）
                    pathRes.setTransportAmount(path.getTransportAmount());
                    // 结算货物数量（完结填写量）
                    pathRes.setSettlementAmount(path.getSettlementAmount());
                    // 计量单位
                    // 计货方式  0货物清单  1无清单货物
                    //pathRes.setUnitStr(GoodsUnitMap.get(path.getUnit().toString()));
                    //pathRes.setUnitStr(GoodsUnitMap.getOrDefault(path.getUnit().toString(), null));
                    if (ObjectUtils.isNotNull(path.getUnit())) {
                        pathRes.setUnit(path.getUnit());
                        pathRes.setUnitStr(GoodsUnitMap.get(path.getUnit().toString()));
                    }
                    // 计费方式
                    pathRes.setBillMode(path.getBillMode());

                    pathRes.setStatus(path.getStatus());
                    // 备注
                    pathRes.setRemark(path.getRemark());

                    //查询清单
                    LambdaQueryWrapper<KwOrderCarLandTransportPathGoods> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(KwOrderCarLandTransportPathGoods::getCarPathId, path.getId()).eq(KwOrderCarLandTransportPathGoods::getDelFlag, Global.NUMERICAL_ZERO);
                    List<KwOrderCarLandTransportPathGoods> kwOrderCarLandTransportPathGoods = kwOrderCarLandTransportPathGoodsMapper.selectList(wrapper);
                    if (!CollectionUtils.isEmpty(kwOrderCarLandTransportPathGoods)) {
                        String goodsNameCop = "";
                        String goodsId = "";
                        List<Map<String, String>> childrenList = new ArrayList<>();
                        for (KwOrderCarLandTransportPathGoods f : kwOrderCarLandTransportPathGoods) {
                            Map<String, String> child = new HashMap<>();
                            child.put("goodsNum", f.getGoodsNum()); // 假设所有孩子的goodsNum相同，实际情况可能不同
                            childrenList.add(child);
                            goodsNameCop = f.getGoodsName();
                            goodsId = f.getGoodsId();
                        }
                        // 创建表示goodsList的Map
                        goodsListMap = new HashMap<>();
                        goodsListMap.put("goodsId", goodsId);
                        goodsListMap.put("goodsName", goodsNameCop);
                        goodsListMap.put("children", childrenList);
                    }

                    pathRes.setGoodsListMap(goodsListMap);

                    kwOrderCarLandTransportPaths.add(pathRes);


                }
                carDetailRes.setPathList(kwOrderCarLandTransportPaths);
            }


        }
        
        
        return carDetailRes;
    }

    public HashMap<String, Object> completeDetail(String orderId)
    {
        int waybill5Count = kwCarOrderMapper.finishWaybillCount(orderId);
        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("taskNum", waybill5Count);
        return objectObjectHashMap;
    }

    public List<Map<String, Object>> getStatusCountListInSingleQuery() {
        // 查询每个状态的计数
        List<Map<String, Object>> statusCounts = kwCarOrderMapper.countByStatus();

        // 将查询结果转换为所需的格式
        List<OrderCarStatusEnum> sortedEnums = OrderCarStatusEnum.getSortList();
        List<Map<String, Object>> result = new ArrayList<>();
        for (OrderCarStatusEnum enumItem : sortedEnums) {
            Map<String, Object> statusCount = statusCounts.stream()
                    .filter(c -> enumItem.getCode().equals(c.get("status")))
                    .findFirst()
                    .orElseGet(() -> Map.of("status", enumItem.getCode(), "count", 0));
            result.add(
                    Map.of(
                            "key", enumItem.getMsg(),
                            "value", enumItem.getCode(),
                            "data", statusCount.get("count")
                    )
            );
        }
        return result;
    }


}
