package com.sckw.car.service;

import com.sckw.car.entity.*;
import com.sckw.car.entity.req.*;
import com.sckw.car.enums.LoadOrUnLoadHandlingEnum;
import com.sckw.car.mapper.*;
import com.sckw.core.model.constant.Global;
import com.sckw.core.model.enums.OrderCarStatusEnum;
import com.sckw.core.model.enums.OrderSourceEnum;
import com.sckw.core.utils.*;
import com.sckw.redis.utils.GenerateOrderIdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @desc:
 * @author: Lt
 * @date: 2024-04-16
 */
@Service
public class CarTransportService {

    @Autowired
    GenerateOrderIdUtil generateOrderIdUtil;

    @Autowired
    KwCarOrderMapper kwCarOrderMapper;

    @Autowired
    KwOrderCarLandTransportMoreMapper kwOrderCarLandTransportMoreMapper;

    @Autowired
    KwOrderCarLandTransportPathMapper kwOrderCarLandTransportPathMapper;

    @Autowired
    KwOrderCarLandTransportPathGoodsMapper kwOrderCarLandTransportPathGoodsMapper;

    @Autowired
    KwOrderCarLandTransportPerMapper kwOrderCarLandTransportPerMapper;

    @Autowired
    KwOrderCarLandTransportDefGoodsMapper kwOrderCarLandTransportDefGoodsMapper;

    @Autowired
    KwOrderCarLandTransportTrackMapper kwOrderCarLandTransportTrackMapper;

    @Transactional
    public Boolean carTransportAdd(AddLogisticsOrderParam addLogisticsOrderParam)
    {

        Integer orderStatus = OrderCarStatusEnum.WAIT_TRANSPORT.getCode();
        //格式验证
        checkCreateLogisticOrderParam(addLogisticsOrderParam);
        Long orderId = new IdWorker(Global.NUMERICAL_ONE).nextId();
        String orderNo = generateOrderIdUtil.getOrderNo("O");
        //订单存储
        orderInsert(addLogisticsOrderParam,orderId, orderNo, orderStatus);

        //更多信息
        moreInsert(addLogisticsOrderParam, String.valueOf(orderId));

        //路径信息存储
        pathInsert(addLogisticsOrderParam, String.valueOf(orderId));

        // 履约信息存储
        perInsert(addLogisticsOrderParam, String.valueOf(orderId));

        // 扣亏货新增
        goodsDefInsert(addLogisticsOrderParam, String.valueOf(orderId));

        orderActionRecordSave(orderId, "轿运新增", orderStatus);

        return true;

        //kwOrderUsualLandTransportGoodsReq goodsReq = addLogisticsOrderParam.getGoodsReq();
        //KwOrderUsualTransportPerReq perReq = addLogisticsOrderParam.getPerReq();
        //KwOrderUsualLandTransportDefGoodsReq defGoods = addLogisticsOrderParam.getDefGoods();
        //KwOrderUsualLandTransportMoreReq usualMore = addLogisticsOrderParam.getOrderMore();
        //
        //KwOrder kwOrder = BeanUtil.copyProperties(orderGeneralTransportReq, KwOrder.class);
        //long id = new IdWorker(Global.NUMERICAL_ONE).nextId();
        //kwOrder.setId(id);
        //kwOrder.setOrderNo("O"+ id);//生成订单号
        //kwOrder.setOrderSource(OrderSourceEnum.SELF_BUILD_NORMAL_LAND_ORDER.getCode()); //普货运输
        //kwOrder.setPids(String.valueOf(id));
        //int insert = orderGeneralTransportMapper.insert(kwOrder);
        //long orderId = kwOrder.getId(); // 获取订单ID
        //String orderNo = kwOrder.getOrderNo(); // 获取订单ID
        //
        //if (insert > 0) {
        //    LambdaUpdateWrapper<KwOrder> updateWrapper = new LambdaUpdateWrapper<>();
        //    updateWrapper.eq(KwOrder::getId, kwOrder.getId());
        //
        //    int loadAddressSize = 0;
        //    int unLoadAddressSize = 0;
        //    //装载地址新增
        //    if(!loadAddressInfo.isEmpty()) {
        //        addTransportAddresses(loadAddressInfo, orderId, orderNo, AddressTypeEnum.LOAD_ADDRESS.getCode());
        //        loadAddressSize = loadAddressInfo.size();
        //    }
        //    //卸货地址新增
        //    if(!unLoadAddressInfo.isEmpty()) {
        //        addTransportAddresses(loadAddressInfo, orderId, orderNo, AddressTypeEnum.UNLOAD_ADDRESS.getCode());
        //        unLoadAddressSize = unLoadAddressInfo.size();
        //    }
        //    //商品信息新增
        //    if(com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotNull(goodsReq)) {
        //        KwOrderUsualLandTransportGoods goods = BeanUtil.copyProperties(goodsReq, KwOrderUsualLandTransportGoods.class);
        //        // 在 lambda 表达式中对 address 进行处理，例如赋值
        //        goods.setOrderId(orderId);
        //        goods.setOrderNo(orderNo);
        //        orderGeneralTransportGoodsMapper.insert(goods);
        //        updateWrapper.set(KwOrder::getGoodsId, goods.getGoodsId());
        //        updateWrapper.set(KwOrder::getGoodsName, goods.getGoodsName());
        //        updateWrapper.set(KwOrder::getGoodsType, goods.getGoodsType());
        //        updateWrapper.set(KwOrder::getGoodsUnit, goods.getGoodsUnit());
        //    }
        //    //履约信息新增
        //    if(com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotNull(perReq)) {
        //        KwOrderUsualTransportPer perReqList = BeanUtil.copyProperties(perReq, KwOrderUsualTransportPer.class);
        //        // 在 lambda 表达式中对 address 进行处理，例如赋值
        //        perReqList.setOrderId(orderId);
        //        orderGeneralTransportPerMapper.insert(perReqList);
        //    }
        //    //扣亏货信息
        //    if(com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotNull(defGoods)) {
        //        KwOrderUsualLandTransportDefGoods defGoodsParam = BeanUtil.copyProperties(defGoods, KwOrderUsualLandTransportDefGoods.class);
        //        // 在 lambda 表达式中对 address 进行处理，例如赋值
        //        defGoodsParam.setOrderId(orderId);
        //        kwOrderUsualLandTransportDefGoodsMapper.insert(defGoodsParam);
        //    }
        //    //更多信息
        //    if(com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotNull(usualMore)) {
        //        KwOrderUsualLandTransportMore orderMore = BeanUtil.copyProperties(usualMore, KwOrderUsualLandTransportMore.class);
        //        // 在 lambda 表达式中对 address 进行处理，例如赋值
        //        orderMore.setOrderId(orderId);
        //        kwOrderUsualLandTransportMoreMapper.insert(orderMore);
        //    }
        //
        //    //托运承运企业
        //    saveLogisticsOrderUnit(orderGeneralTransportReq, orderId);
        //    //如果地址大于2  就是3 那就是多装卸类型
        //    int addressTotalSize =  unLoadAddressSize + loadAddressSize;
        //
        //    if (addressTotalSize > 2) {
        //        updateWrapper.set(KwOrder::getTypeHandling, AddressLoadOrUnLoadHandlingEnum.MORE.getCode());
        //    }
        //    orderGeneralTransportMapper.update(null, updateWrapper);
        //}
        ////新增订单操作记录
        //KwOrderUsualLandTransportTrack kwOrderUsualLandTransportTrack = new KwOrderUsualLandTransportTrack();
        //kwOrderUsualLandTransportTrack.setOrderId(orderId);
        //kwOrderUsualLandTransportTrack.setActionNote("订单已创建");
        //kwOrderUsualLandTransportTrack.setStatus(OrderStatusEnum.UNDER_REVIEW.getCode());  //审核中
        //kwOrderUsualLandTransportTrackMapper.insert(kwOrderUsualLandTransportTrack);
        //
        //
        //return true;
    }

    public void orderActionRecordSave(Long orderId, String actionNote, Integer orderStatus)
    {
        String loginActionName = "10000";
        //新增订单操作记录
        KwOrderCarLandTransportTrack kwOrderCarLandTransportTrack = new KwOrderCarLandTransportTrack();
        kwOrderCarLandTransportTrack.setOrderId(orderId);
        kwOrderCarLandTransportTrack.setActionNote(actionNote);
        kwOrderCarLandTransportTrack.setStatus(orderStatus);  //审核中
        kwOrderCarLandTransportTrack.setCreateBy(loginActionName);  //操作人
        kwOrderCarLandTransportTrackMapper.insert(kwOrderCarLandTransportTrack);
    }

    public void goodsDefInsert(AddLogisticsOrderParam addLogisticsOrderParam , String orderId)
    {
        KwOrderCarLandTransportDefGoods kwOrderCarLandTransportPer = BeanUtils.copyProperties(addLogisticsOrderParam.getTransportPer(), KwOrderCarLandTransportDefGoods.class);
        kwOrderCarLandTransportPer.setOrderId(Long.valueOf(orderId));
        kwOrderCarLandTransportPer.setRationalLoss(addLogisticsOrderParam.getDefGoods().getRationalLoss());
        kwOrderCarLandTransportPer.setDedPrice(addLogisticsOrderParam.getDefGoods().getDedPrice());
        kwOrderCarLandTransportDefGoodsMapper.insert(kwOrderCarLandTransportPer);
    }

    public void perInsert(AddLogisticsOrderParam addLogisticsOrderParam , String orderId)
    {
        KwOrderCarLandTransportPer kwOrderCarLandTransportPer = BeanUtils.copyProperties(addLogisticsOrderParam.getTransportPer(), KwOrderCarLandTransportPer.class);
        kwOrderCarLandTransportPer.setOrderId(Long.valueOf(orderId));
        kwOrderCarLandTransportPerMapper.insert(kwOrderCarLandTransportPer);

    }

    /**
    * @Description: 订单新增
    * @Author: Lt
    * @Date: 2024/4/17 15:18
    */
    public void orderInsert(AddLogisticsOrderParam addLogisticsOrderParam, Long orderId, String orderNo, Integer orderStatus)
    {
        KwCarOrder kwCarOrder = BeanUtils.copyProperties(addLogisticsOrderParam, KwCarOrder.class);
        kwCarOrder.setId(String.valueOf(orderId));
        kwCarOrder.setOrderNo(orderNo);
        kwCarOrder.setPids(String.valueOf(orderId));
        kwCarOrder.setOrderSource(OrderSourceEnum.SELF_BUILD_CAR_LAND_ORDER.getCode());
        kwCarOrder.setTypeHandling(LoadOrUnLoadHandlingEnum.SINGLE.getCode());
        kwCarOrder.setStatus(orderStatus);
        String tenantId = TenantUtil.getTenant();
        kwCarOrder.setTenantId(tenantId);
        //  --
        kwCarOrder.setGoodsType(1);
        kwCarOrder.setUnit("1");
        kwCarOrder.setCreateBy("admin");
        kwCarOrderMapper.insert(kwCarOrder);
    }

    /**
    * @Description: 更多新增
    * @Author: Lt
    * @Date: 2024/4/17 15:19
    */
    public void moreInsert(AddLogisticsOrderParam addLogisticsOrderParam, String orderId)
    {
        KwOrderCarLandTransportMoreReq more = addLogisticsOrderParam.getMore();
        KwOrderCarLandTransportMore kwCarOrderMore = BeanUtils.copyProperties(more, KwOrderCarLandTransportMore.class);
        kwCarOrderMore.setOrderId(orderId);
        kwOrderCarLandTransportMoreMapper.insert(kwCarOrderMore);
    }

    /**
    * @Description: 路径新增
    * @Author: Lt
    * @Date: 2024/4/17 15:19
    */
    public void pathInsert(AddLogisticsOrderParam addLogisticsOrderParam, String orderId)
    {
        List<KwOrderCarLandTransportPathDto> pathList = addLogisticsOrderParam.getPathList();
        ArrayList<KwOrderCarLandTransportPath> objects = new ArrayList<>();

        int remainNum = 0;   //剩余代运量    清单数量

        ArrayList<KwOrderCarLandTransportPathGoods> goodsNumListArray = new ArrayList<>();
        ArrayList<String> goodsNameList = new ArrayList<>();    //轿运
        for (KwOrderCarLandTransportPathDto e : pathList) {
            KwOrderCarLandTransportPath path = BeanUtils.copyProperties(e, KwOrderCarLandTransportPath.class);
            path.setOrderId(orderId); // 设置orderId
            path.setUnloadAddressId(e.getUnloadAddressId());
            path.setBillMode(e.getBillingMode());
            objects.add(path);
            int insert = kwOrderCarLandTransportPathMapper.insert(path);

            //存储成功
            if (insert > 0) {
                if (!ObjectUtils.isEmpty(e.getGoodsList())) {
                    GoodsListDto goodsList = e.getGoodsList();
                    if (CollectionUtils.isNotEmpty(goodsList.getChildren())) {
                        List<GoodsListDetailDto> goodsNumList = goodsList.getChildren();
                        for (GoodsListDetailDto goodsNum : goodsNumList) {
                            KwOrderCarLandTransportPathGoods kwOrderCarLandTransportPathGoods = new KwOrderCarLandTransportPathGoods();
                            kwOrderCarLandTransportPathGoods.setId(new IdWorker(1L).nextId());
                            kwOrderCarLandTransportPathGoods.setCarPathId(path.getId());
                            kwOrderCarLandTransportPathGoods.setGoodsId(goodsList.getGoodsId());
                            kwOrderCarLandTransportPathGoods.setGoodsName(goodsList.getGoodsName());
                            kwOrderCarLandTransportPathGoods.setGoodsNum(goodsNum.getGoodsNum());
                            goodsNumListArray.add(kwOrderCarLandTransportPathGoods);
                            goodsNameList.add(goodsList.getGoodsName());
                            remainNum++;
                        }
                    }

                }
            }
        }
        String result = goodsNameList.stream()
                .distinct() // 去除重复项
                .collect(Collectors.joining(",")); // 转换为逗号分隔的字符串

        KwCarOrder kwCarOrder = new KwCarOrder();
        kwCarOrder.setId(orderId).setGoodsName(result).setRemainNum((double) remainNum).setRemainAllocation((double) remainNum);
        kwCarOrderMapper.updateById(kwCarOrder);
        if (CollectionUtils.isNotEmpty(goodsNumListArray)) {
            kwOrderCarLandTransportPathGoodsMapper.insertBatch(goodsNumListArray);
        }
    }




    /**
     * 校验请求参数
     *
     * @param addLogisticsOrderParam
     */
    private void checkCreateLogisticOrderParam(AddLogisticsOrderParam addLogisticsOrderParam) {

        if (!ObjectUtils.isEmpty(addLogisticsOrderParam.getTaxRate())) {
            if (addLogisticsOrderParam.getTaxRate().compareTo(new BigDecimal(Global.NUMERICAL_ZERO)) < 0) {
                throw new RuntimeException("税率填写格式错误!");
            }
        }
        if (!ObjectUtils.isEmpty(addLogisticsOrderParam.getLoss())) {
            if (addLogisticsOrderParam.getLoss().compareTo(new BigDecimal(Global.NUMERICAL_ZERO)) < 0) {
                throw new RuntimeException("合理损耗填写格式错误!");
            }
        }
        if (!ObjectUtils.isEmpty(addLogisticsOrderParam.getGoodsPrice())) {
            if (addLogisticsOrderParam.getGoodsPrice().compareTo(new BigDecimal(Global.NUMERICAL_ZERO)) < 0) {
                throw new RuntimeException("扣亏货值填写格式错误!");
            }
        }
    }
}
