package com.sckw.car.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sckw.car.entity.*;
import com.sckw.car.entity.req.*;
import com.sckw.car.entity.res.KwOrderWaybillDetailRes;
import com.sckw.car.enums.WaybillOrderStatusEnum;
import com.sckw.car.enums.WaybillStatusEnums;
import com.sckw.car.mapper.*;
import com.sckw.core.web.response.HttpResult;
import com.sckw.redis.utils.GenerateOrderIdUtil;
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 org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

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

/**
 * @desc: 运单服务
 * @author: Lt
 * @date: 2024-04-18
 */
@Service
public class KwWayBillService {

    @Autowired
    KwCarWaybillOrderMapper kwCarWaybillOrderMapper;

    @Autowired
    KwCarOrderMapper kwOrderMapper;

    @Autowired
    GenerateOrderIdUtil generateOrderIdUtil;

    @Autowired
    KwOrderCarWaybillOrderDispatchMapper kwOrderCarWaybillOrderDispatchMapper;

    @Autowired
    KwOrderCarWaybillOrderDispatchAssignMapper kwOrderCarWaybillOrderDispatchAssignMapper;

    @Autowired
    KwOrderCarLandTransportPathMapper kwOrderCarLandTransportPathMapper;

    @Autowired
    KwOrderCarWaybillOrderDispatchAddressMapper kwOrderCarWaybillOrderDispatchAddressMapper;

    @Autowired
    KwOrderCarWaybillTransportPathGoodsMapper kwOrderCarWaybillTransportPathGoodsMapper;

    public HttpResult sendCarInsert(KwOrderSendCarParam kwOrderSendCarParam)
    {
        return sendCarInsert(kwOrderSendCarParam, WaybillOrderStatusEnum.ONE.getCode());
    }

    /**
     * @Description: 派车草稿
     * @Author: Lt
     * @Date: 2024/4/19 0019 17:24
     */
    public HttpResult sendCarDraft(KwOrderSendCarParam kwOrderSendCarParam)
    {
        return sendCarInsert(kwOrderSendCarParam, WaybillOrderStatusEnum.TWO.getCode());
    }

    /**
    * @Description: 订单派车
    * @Author: Lt
    * @Date: 2024/4/19 17:24
    */
    @Transactional(rollbackFor = Exception.class)
    public HttpResult sendCarInsert(KwOrderSendCarParam kwOrderSendCarParam, Integer status)
    {
        try{
            //查询订单
            LambdaQueryWrapper<KwCarOrder> objectLambdaQueryWrapper = new LambdaQueryWrapper<>();
            objectLambdaQueryWrapper.eq(KwCarOrder::getId, kwOrderSendCarParam.getOrderId())
                    .eq(KwCarOrder::getDelFlag, Global.NUMERICAL_ZERO);
            KwCarOrder kwCarOrder = kwOrderMapper.selectOne(objectLambdaQueryWrapper);
            if (ObjectUtils.isEmpty(kwCarOrder)) {
                throw new RuntimeException("当前订单号不存在");
            }
            //    /* 添加派车任务 */
            saveCreateDispatch(kwOrderSendCarParam);

            //}
        }catch (Exception e){
            return HttpResult.error(e.getMessage());
        }

        return HttpResult.ok("派车成功");
    }


    /**
    * @Description: 添加派车任务
    * @Author: Lt
    * @Date: 2024/4/19 15:47
    */
    public Boolean saveCreateDispatch(KwOrderSendCarParam kwOrderSendCarParam)
    {

        String orderId = kwOrderSendCarParam.getOrderId();   //订单Id
        ArrayList<KwCarWaybillOrder> objectsList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(kwOrderSendCarParam.getDispatch())) {
            //添加派车任务 (一个任务一个运单)
            List<kwWaybillOrderReq> dispatch = kwOrderSendCarParam.getDispatch();

            dispatch.forEach(e -> {
                KwCarWaybillOrder kwWaybillOrder = new KwCarWaybillOrder();
                String dispatchNo = generateOrderIdUtil.getOrderNo("T");
                Long waybillId = new IdWorker(Global.NUMERICAL_ONE).nextId();
                kwWaybillOrder.setId(String.valueOf(waybillId));
                kwWaybillOrder.setOrderId(orderId);
                kwWaybillOrder.setTOrderNo(dispatchNo);
                kwWaybillOrder.setType(Global.NUMERICAL_ONE);
                kwWaybillOrder.setTruckId(e.getTruckId());
                kwWaybillOrder.setTruckNo(e.getTruckNo());
                kwWaybillOrder.setDriverId(e.getDriverId());
                kwWaybillOrder.setDriverName(e.getDriverName());
                kwWaybillOrder.setDriverPhone(e.getDriverPhone());
                kwWaybillOrder.setDriverIdcard(e.getDriverIdcard());
                kwWaybillOrder.setRemark(e.getRemark());
                kwWaybillOrder.setStatus(WaybillStatusEnums.ONE.getCode());
                kwWaybillOrder.setTType(Global.NUMERICAL_TWO);  //轿运
                kwWaybillOrder.setUnit(Global.NUMERICAL_ZERO);  //轿运
                kwWaybillOrder.setEntrustAmount(BigDecimal.ZERO);  //轿运
                kwWaybillOrder.setLoadAmount(BigDecimal.ZERO);  //轿运
                kwWaybillOrder.setUnloadAmount(BigDecimal.ZERO);  //轿运
                kwWaybillOrder.setDeficitAmount(BigDecimal.ZERO);  //轿运
                kwWaybillOrder.setCreateBy(kwOrderSendCarParam.getCreateBy() == null ? "admin" : kwOrderSendCarParam.getCreateBy());  //轿运
                objectsList.add(kwWaybillOrder);
                if (CollectionUtils.isNotEmpty(e.getGoodsList())) {
                    /* 分配任务清单添加 */
                    int i = saveCreateDispatchAssign(e.getGoodsList(), waybillId, orderId);
                    kwWaybillOrder.setEntrustAmount(BigDecimal.valueOf(i));
                }
                if (CollectionUtils.isNotEmpty(e.getPathAddress())) {
                    /* 分配任务清单地址添加 */
                    saveCreateDispatchAddress(e.getPathAddress(), String.valueOf(waybillId), orderId);
                }
            });
        }
        kwCarWaybillOrderMapper.insertBatch(objectsList);
        return true;

    }
    
    /**
    * @Description: 任务清单添加
    * @Author: Lt
    * @Date: 2024/4/19 16:16
    */
    public int saveCreateDispatchAssign(List<KwOrderCarWaybillOrderDispatchAssignReq> goodsLists, Long waybillId, String orderId)
    {
        ArrayList<KwOrderCarWaybillTransportPathGoods> insertGoodsLists = new ArrayList<>();
        String goodsName;
        String goodsId;
        int remainGoodsNum = 0;
        for (KwOrderCarWaybillOrderDispatchAssignReq goodsList : goodsLists) {
            if (goodsList == null) {
                continue;
            }
            goodsName = goodsList.getGoodsName();
            goodsId = goodsList.getGoodsId();
            if (CollectionUtils.isNotEmpty(goodsList.getChildren())){
                for (InventoryNumDto child : goodsList.getChildren()) {
                    KwOrderCarWaybillTransportPathGoods kwOrderCarWaybillTransportPathGoods = new KwOrderCarWaybillTransportPathGoods();
                    kwOrderCarWaybillTransportPathGoods.setOrderId(orderId);
                    kwOrderCarWaybillTransportPathGoods.setGoodsId(goodsId);
                    kwOrderCarWaybillTransportPathGoods.setGoodsNum(child.getGoodsNum());
                    kwOrderCarWaybillTransportPathGoods.setGoodsName(goodsName);
                    kwOrderCarWaybillTransportPathGoods.setWaybillId(waybillId);
                    kwOrderCarWaybillTransportPathGoods.setId(new IdWorker(1L).nextId());
                    insertGoodsLists.add(kwOrderCarWaybillTransportPathGoods);
                    remainGoodsNum += 1;
                }
            }
        }
        kwOrderCarWaybillTransportPathGoodsMapper.insertBatch(insertGoodsLists);
        KwCarOrder kwCarOrder = kwOrderMapper.selectById(orderId);
        if (kwCarOrder.getRemainAllocation() < remainGoodsNum) {
            throw  new RuntimeException("剩余待分配量不足");
        }
        double v = kwCarOrder.getRemainAllocation() - remainGoodsNum;
        kwCarOrder.setRemainAllocation(v);
        kwCarOrder.setStatus(OrderCarStatusEnum.IN_TRANSIT.getCode());
        kwOrderMapper.updateById(kwCarOrder);

        KwCarWaybillOrder kwCarWaybillOrder = new KwCarWaybillOrder();
        kwCarWaybillOrder.setId(String.valueOf(waybillId));
        kwCarWaybillOrder.setEntrustAmount(BigDecimal.valueOf(remainGoodsNum));
        kwCarWaybillOrderMapper.updateById(kwCarWaybillOrder);
        return remainGoodsNum;
    }

    public void saveCreateDispatchAddress(List<KwOrderCarWaybillOrderDispatchAddressReq> pathList, String waybillId, String orderId)
    {
        ArrayList<KwOrderCarWaybillOrderDispatchAddress> addressLists = new ArrayList<>();
        pathList.forEach(f -> {
            KwOrderCarWaybillOrderDispatchAddress kwOrderCarWaybillOrderDispatchAddress = BeanUtils.copyProperties(f, KwOrderCarWaybillOrderDispatchAddress.class);
            Long id = new IdWorker(Global.NUMERICAL_ONE).nextId();
            kwOrderCarWaybillOrderDispatchAddress.setId(id);
            kwOrderCarWaybillOrderDispatchAddress.setOrderId(orderId);
            kwOrderCarWaybillOrderDispatchAddress.setWaybillId(waybillId);
            kwOrderCarWaybillOrderDispatchAddress.setName(f.getName());
            kwOrderCarWaybillOrderDispatchAddress.setAddressId(f.getAddressId());
            kwOrderCarWaybillOrderDispatchAddress.setAddressType(f.getAddressType());
            kwOrderCarWaybillOrderDispatchAddress.setUnit(f.getUnit());
            kwOrderCarWaybillOrderDispatchAddress.setEntrustAmount(f.getEntrustAmount());
            kwOrderCarWaybillOrderDispatchAddress.setSort(f.getSort());
            addressLists.add(kwOrderCarWaybillOrderDispatchAddress);
        });
        kwOrderCarWaybillOrderDispatchAddressMapper.insertBatch(addressLists);

    }

    @Transactional
    public HttpResult completeOrder(KwOrderCarCompleteParam kwOrderCarCompleteParam) {
        Long orderId = kwOrderCarCompleteParam.getOrderId();
        List<KwOrderCompletePathDto> pathList = kwOrderCarCompleteParam.getPath();

        BigDecimal totalMultiply = BigDecimal.ZERO;

        List<KwOrderCarLandTransportPath> pathsToUpdate = new ArrayList<>();
        for (KwOrderCompletePathDto e : pathList) {
            KwOrderCarLandTransportPath pathObj = kwOrderCarLandTransportPathMapper.selectById(e.getId());
            if (pathObj != null) {
                /* 结算量*里程价 */
                BigDecimal multiply = e.getSettleAmount().multiply(pathObj.getTransportPrice());

                totalMultiply = totalMultiply.add(multiply);

                KwOrderCarLandTransportPath pathToUpdate = new KwOrderCarLandTransportPath();
                pathToUpdate.setId(pathObj.getId());
                pathToUpdate.setSettlementAmount(multiply);
                pathsToUpdate.add(pathToUpdate);
            }
        }

        // 执行批量更新
        if (!pathsToUpdate.isEmpty()) {
            kwOrderCarLandTransportPathMapper.batchUpdateSettlementAmount(pathsToUpdate);
        }

        // 更新订单状态
        KwCarOrder kwCarOrder = new KwCarOrder();
        kwCarOrder.setId(String.valueOf(orderId));
        kwCarOrder.setStatus(OrderCarStatusEnum.FINISHED.getCode());
        kwOrderMapper.updateById(kwCarOrder);

        // TODO 添加操作记录

        return HttpResult.ok("完结成功");
    }

    /**
    * @Description: 运单详情
    * @Author: Lt
    * @Date: 2024/4/22 10:31
    */
    public KwOrderWaybillDetailRes waybillDetail(String orderId)
    {
        //查询运单详情
        return kwCarWaybillOrderMapper.selectWaybillDetailById(orderId);
    }
}
