package com.sckw.transport.handler;


import com.alibaba.fastjson.JSON;
import com.sckw.core.common.enums.enums.DictTypeEnum;
import com.sckw.core.common.enums.enums.ErrorCodeEnum;
import com.sckw.core.exception.BusinessPlatfromException;
import com.sckw.core.model.enums.CarWaybillV1Enum;
import com.sckw.core.model.enums.ForkliftStatusEnum;
import com.sckw.core.model.enums.LoadingTypeEnum;
import com.sckw.core.utils.CollectionUtils;
import com.sckw.fleet.api.model.vo.RTruckVo;
import com.sckw.order.api.model.OrderUnitInfoDetailVO;
import com.sckw.product.api.model.KwpGoods;
import com.sckw.system.api.model.dto.res.SysDictResDto;
import com.sckw.transport.model.*;
import com.sckw.transport.model.param.WaybillOrderReplenishParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Author: donglang
 * Time: 2025-11-19
 * Des: 补货
 * Version: 1.0
 */

@Slf4j
@Service
public class ReplenishHandler extends AbstractWaybillOrderHandler<WaybillOrderReplenishParam> {

    @Override
    protected KwtWaybillOrder getWaybillOrder(WaybillOrderReplenishParam param) {
        return getWaybillOrder(param.getWaybillOrderId());
    }

    @Override
    protected void checkState(WaybillOrderReplenishParam param, KwtWaybillOrder waybill) {
        if (!Objects.equals(CarWaybillV1Enum.WAIT_LEAVE.getCode(), waybill.getStatus())) {
            throw new BusinessPlatfromException(ErrorCodeEnum.WAYBILL_ORDER_STATUS_ERROR, "运单状态不是“待离场”状态, 无法推进下一节点！");
        }
    }

    @Override
    protected void doBusiness(WaybillOrderReplenishParam param, KwtWaybillOrder waybillOrder) {
        //1. 补货：创建铲车记录
        createForkliftWaybill(waybillOrder);
    }

    /**
     * 创建铲车记录
     * @param waybillOrder
     */
    private void createForkliftWaybill(KwtWaybillOrder waybillOrder) {
        try {
            log.debug("开始异步保存铲车司机数据，运单ID:{}", waybillOrder.getId());
            //企业id
            Long entId = getEntId(waybillOrder);

            KwtForkliftWaybillOrder forklift = new KwtForkliftWaybillOrder();
            forklift.setFOrderNo("F" + System.currentTimeMillis());
            forklift.setEntId(entId);
            forklift.setWOrderId(waybillOrder.getId());
            forklift.setLOrderId(waybillOrder.getLOrderId());

            //查询字典
            Map<String, Map<String, String>> dictValueAndDictResDtoMap = remoteSystemService.queryDictByType(
                    Arrays.asList(DictTypeEnum.PRODUCT_NAME_TYPE.getType(), DictTypeEnum.GOODS_SPEC.getType()));
            Map<String, String> goodsTypeMap= dictValueAndDictResDtoMap.getOrDefault(DictTypeEnum.PRODUCT_NAME_TYPE.getType(), new HashMap<>());
            Map<String, String> goodsSpecMap= dictValueAndDictResDtoMap.getOrDefault(DictTypeEnum.GOODS_SPEC.getType(), new HashMap<>());

            // 查询商品信息
            KwtLogisticsOrderGoods orderGoods = logisticsOrderGoodsRepository.queryByLogOrderId(waybillOrder.getLOrderId());
            KwpGoods goods = goodsInfoService.getGoodsById(orderGoods.getGoodsId());
            if (goods != null) {
                List<SysDictResDto> dictResDtoList = remoteSystemService.queryDictFrontAll(DictTypeEnum.GOODS_SPEC.getType(), goods.getSpec());
                forklift.setDictId(CollectionUtils.isNotEmpty(dictResDtoList) ? dictResDtoList.get(0).getId() : -1L);
                forklift.setGoodsId(goods.getId());
                forklift.setGoodsName(goods.getName()+"/"+goodsTypeMap.getOrDefault(goods.getGoodsType(),"")+"/"+goodsSpecMap.getOrDefault(goods.getSpec(), ""));
            }
            forklift.setLoadingType(LoadingTypeEnum.SUPPLEMENT.getCode());
            forklift.setStatus(ForkliftStatusEnum.PENDING_ORDERS.getCode());
            forklift.setWaybillAcceptTime(waybillOrder.getCreateTime());

            // 任务量
            KwtWaybillOrderSubtask waybillSubtask = getWaybillSubtask(waybillOrder.getId());
            forklift.setEntrustAmount(waybillSubtask.getEntrustAmount());
            // 车辆类型
            RTruckVo truckVo = remoteFleetService.findTruckByTruckNo(waybillOrder.getTruckNo());
            if (truckVo != null) {
                forklift.setTruckType(truckVo.getTruckType());
                forklift.setCarAxis(truckVo.getCarAxis());
            }
            forklift.setCreateTime(new Date());
            forklift.setCreateUser(waybillOrder.getDriverId());
            forklift.setUpdateUser(waybillOrder.getDriverId());

            forkliftWaybillOrderRepository.save(forklift);
            log.debug("铲车司机数据保存成功");
        } catch (Exception e) {
            throw new BusinessPlatfromException(ErrorCodeEnum.DATA_SAVE_FAIL, "保存铲车司机数据失败！");
        }
    }

    /**
     * 获取企业id
     * @param waybillOrder
     * @return
     */
    private Long getEntId(KwtWaybillOrder waybillOrder) {
        log.info("[创建补货铲车]开始查询企业id，入参参数：{}", JSON.toJSONString(waybillOrder));
        Long entId;
        KwtLogisticsOrder logOrder = getLogisticsOrder(waybillOrder.getLOrderId());
        KwtLogisticsOrderUnit kwtLogisticsOrderUnit = logisticsOrderUnitRepository.queryByLOrderIdAndUnitType(logOrder.getId(), 1);
        if (kwtLogisticsOrderUnit == null) {
            throw new BusinessPlatfromException(ErrorCodeEnum.LOGISTICS_ORDER_NOT_FOUND, "[接单]物流企业信息数据不存在");
        }
        // 原矿运输山上、上下门卫企业id
        List<Long> mockEntIds = Arrays.asList(538039617157337089L, 538040297439891457L);
        if (Objects.equals(1, logOrder.getOrderType()) && mockEntIds.contains(kwtLogisticsOrderUnit.getEntId())) {
            entId = mockEntIds.get(0);
        } else {
            List<OrderUnitInfoDetailVO> unitInfoDetailVOS = tradeOrderInfoService.queryOrderUnitByTradeOrderId(logOrder.getTOrderId());
            OrderUnitInfoDetailVO unitInfoDetailVO = unitInfoDetailVOS.stream()
                    .filter(unit -> Objects.equals(unit.getUnitType(), "2"))
                    .findFirst().orElse(new OrderUnitInfoDetailVO());
            entId = unitInfoDetailVO.getEntId();
        }
        log.info("[创建补货铲车]查询企业id完成，入参参数：{}", JSON.toJSONString(entId));
        return entId;
    }

    @Override
    protected void calculateAutoDispatchScore(WaybillOrderReplenishParam param, KwtWaybillOrder waybillOrder) {

    }

    @Override
    protected String getProcessName() {
        return "补货";
    }

    @Override
    protected void getStatus(KwtWaybillOrder waybillOrder) {
        // 1. 修改运单状态
        waybillOrder.setStatus(CarWaybillV1Enum.REPLENISHING.getCode());
        waybillOrderRepository.updateById(waybillOrder);

        // 2. 修改子运单状态
        KwtWaybillOrderSubtask waybillSubtask = getWaybillSubtask(waybillOrder.getId());
        waybillSubtask.setStatus(CarWaybillV1Enum.REPLENISHING.getCode());
        waybillOrderSubtaskRepository.updateById(waybillSubtask);
    }

    @Override
    protected String getRemark(WaybillOrderReplenishParam param, KwtWaybillOrder waybillOrder) {
        return "司机[" + waybillOrder.getDriverName() + "]返场补货";
    }
}
