package com.sckw.transport.service.dubbo;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sckw.core.common.enums.NumberConstant;
import com.sckw.core.model.enums.LogisticsOrderEnum;
import com.sckw.core.utils.CollectionUtils;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.core.web.response.HttpResult;
import com.sckw.mongo.enums.BusinessTypeEnum;
import com.sckw.mongo.model.SckwLogisticsOrder;
import com.sckw.stream.model.SckwBusSum;
import com.sckw.system.api.RemoteSystemService;
import com.sckw.transport.api.dubbo.TransportDubboService;
import com.sckw.transport.api.model.dto.AddressResDTO;
import com.sckw.transport.api.model.param.LogisticsOrderParam;
import com.sckw.transport.api.model.vo.KwtLogisticsOrderVO;
import com.sckw.transport.api.model.vo.LogisticsOrderVO;
import com.sckw.transport.dao.KwtLogisticsOrderGoodsMapper;
import com.sckw.transport.dao.KwtLogisticsOrderMapper;
import com.sckw.transport.dao.KwtLogisticsOrderUnitMapper;
import com.sckw.transport.dao.KwtWaybillOrderMapper;
import com.sckw.transport.model.KwtLogisticsOrder;
import com.sckw.transport.model.KwtLogisticsOrderUnit;
import com.sckw.transport.model.KwtWaybillOrder;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author lfdc
 * @description 运输服务dubbo接口
 * @date 2023-07-11 14:07:28
 */
@Slf4j
@Service
@DubboService(group = "design", version = "2.0.0", timeout = 50000)
public class TransportDubboServiceImpl implements TransportDubboService {

    @Resource
    private StreamBridge streamBridge;

    @DubboReference(version = "2.0.0", group = "design", check = false)
    RemoteSystemService remoteSystemService;

    @Autowired
    private KwtLogisticsOrderMapper logisticsOrderMapper;

    @Autowired
    private KwtLogisticsOrderUnitMapper logisticsOrderUnitMapper;

    @Autowired
    private KwtLogisticsOrderGoodsMapper logisticsOrderGoodsMapper;

    @Autowired
    private KwtWaybillOrderMapper waybillOrderMapper;

    /**
     * 对账管理-ids查询
     *
     * @param ids
     * @return
     */
    public List<KwtLogisticsOrderVO> getAcceptCarriageOrderDetail(List<String> ids) {
        List<KwtLogisticsOrderVO> list = new ArrayList<>();
        List<KwtLogisticsOrder> kwtLogisticsOrders = logisticsOrderMapper.selectList(new LambdaQueryWrapper<KwtLogisticsOrder>().in(KwtLogisticsOrder::getId, ids));
        if (CollectionUtils.isNotEmpty(kwtLogisticsOrders)) {
            for (KwtLogisticsOrder kwtLogisticsOrder : kwtLogisticsOrders) {
                KwtLogisticsOrderVO vo = new KwtLogisticsOrderVO();
                BeanUtils.copyProperties(kwtLogisticsOrder, vo);
                list.add(vo);
            }
        }
        return list;
    }

    /**
     * 对账页面数据接口
     *
     * @param ids
     * @return
     */
    @Override
    public List<LogisticsOrderVO> getAcceptCarriageOrderList(List<String> ids) {
        List<LogisticsOrderVO> list = logisticsOrderMapper.selectLogisticOrderList(ids);
        if (CollectionUtils.isNotEmpty(list)) {
            for (LogisticsOrderVO logisticsOrderVO : list) {
                KwtLogisticsOrderUnit orderUnit = logisticsOrderUnitMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderUnit>()
                        .eq(KwtLogisticsOrderUnit::getLOrderId, logisticsOrderVO.getLOrderId())
                        .eq(KwtLogisticsOrderUnit::getUnitType, NumberConstant.ONE));
                KwtLogisticsOrderUnit orderUnit1 = logisticsOrderUnitMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderUnit>()
                        .eq(KwtLogisticsOrderUnit::getLOrderId, logisticsOrderVO.getLOrderId())
                        .eq(KwtLogisticsOrderUnit::getUnitType, NumberConstant.TWO));
                logisticsOrderVO.setCarrierCompany(orderUnit1 == null ? null : orderUnit1.getFirmName());
                logisticsOrderVO.setConsignCompany(orderUnit == null ? null : orderUnit.getFirmName());
                logisticsOrderVO.setCount(waybillOrderMapper.selectCount(new LambdaQueryWrapper<KwtWaybillOrder>().eq(KwtWaybillOrder::getLOrderId, logisticsOrderVO.getLOrderId())));
            }
        }
        return list;
    }

    /**
     * 获取当前企业下物流订单地址信息
     *
     * @return
     */
    @Override
    public List<Integer> getLogisticsOrderAddressList() {
        return logisticsOrderMapper.getAddressList(LoginUserHolder.getEntId());
    }

    /**
     * 根据企业id 获取物流订单相关地址信息
     *
     * @param entId 企业id
     * @return
     */
    @Override
    public List<AddressResDTO> getLogisticsOrderAddressListByEntId(Long entId) {
        return null;
    }

    /**
     * 贸易订单验证物流订单是否已完成
     *
     * @param tOrderId 贸易订单id
     * @return false 无操作中的物流订单  ture 存在操作中的物流订单
     */
    @Override
    public boolean checkLogisticsOrderByTradeOrderId(Long tOrderId) {
        boolean flag = false;
        List<Integer> statusList = new ArrayList<>();
        statusList.add(LogisticsOrderEnum.TO_BE_PLANNED.getCode());
        statusList.add(LogisticsOrderEnum.PENDING_ORDER.getCode());
        statusList.add(LogisticsOrderEnum.WAIT_DELIVERY.getCode());
        statusList.add(LogisticsOrderEnum.IN_TRANSIT.getCode());
        List<KwtLogisticsOrder> logisticsOrders = logisticsOrderMapper.selectList(
                new LambdaQueryWrapper<KwtLogisticsOrder>()
                        .eq(KwtLogisticsOrder::getTOrderId, tOrderId)
                        .eq(KwtLogisticsOrder::getDelFlag, NumberConstant.ZERO)
                        .in(KwtLogisticsOrder::getStatus, statusList)
        );
        if (!org.springframework.util.CollectionUtils.isEmpty(logisticsOrders)) {
            flag = true;
        }
        return flag;
    }

    /**
     * 对账修改物流订单信息
     *
     * @param logisticsOrderParam 请求物流订单数据
     * @return
     */
    @Override
    public HttpResult checkLogisticsOrderStatusById(LogisticsOrderParam logisticsOrderParam) {
        HttpResult httpResult = new HttpResult();
        log.info("对账修改物流订单参数:{}", JSONObject.toJSONString(logisticsOrderParam));
        Long lOrderId = logisticsOrderParam.getLOrderId();
        String status = logisticsOrderParam.getStatus();
        if (lOrderId == null) {
            httpResult.setMsg("物流订单不能为空!");
            httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
            return httpResult;
        }

        LambdaQueryWrapper<KwtLogisticsOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(KwtLogisticsOrder::getId, lOrderId);
        wrapper.eq(KwtLogisticsOrder::getDelFlag, NumberConstant.ZERO);
        KwtLogisticsOrder kwtLogisticsOrder = logisticsOrderMapper.selectOne(wrapper);
        if (kwtLogisticsOrder == null) {
            httpResult.setMsg("物流订单不存在!");
            httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
            return httpResult;
        }

        if (LogisticsOrderEnum.HAVE_RECONCILED.getStatus().equals(status)) {
            if (!LogisticsOrderEnum.HAVE_FINISHED.getStatus().equals(status)) {
                httpResult.setMsg("物流单据状态有误,不能修改");
                httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
                return httpResult;
            }
        } else if (LogisticsOrderEnum.HAVE_ALREADY_SETTLED.getStatus().equals(status)) {
            if (!LogisticsOrderEnum.HAVE_RECONCILED.getStatus().equals(status)) {
                httpResult.setMsg("物流单据状态有误,不能修改");
                httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
                return httpResult;
            }
        } else {
            httpResult.setMsg("物流单据状态有误");
            httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
            return httpResult;
        }
        //修改单据状态
        kwtLogisticsOrder.setStatus(Integer.valueOf(status));
        kwtLogisticsOrder.setUpdateTime(new Date());
        kwtLogisticsOrder.setUpdateBy(LoginUserHolder.getUserId());
        logisticsOrderMapper.updateById(kwtLogisticsOrder);
        //修改mongodb状态
        SckwLogisticsOrder order = new SckwLogisticsOrder();
        order.set_id(kwtLogisticsOrder.getId());
        order.setLOrderId(kwtLogisticsOrder.getId());
        order.setStatus(status);
        order.setUpdateTime(new Date());
        order.setUpdateByName(LoginUserHolder.getUserName());
        SckwBusSum busSum = new SckwBusSum();
        busSum.setBusSumType(BusinessTypeEnum.LOGISTICS_ORDER_TYPE.getName());
        busSum.setMethod(NumberConstant.ONE);
        busSum.setObject(order);
        streamBridge.send("sckw-busSum", com.alibaba.fastjson2.JSON.toJSONString(busSum));
        return HttpResult.ok();
    }

    /**
     * 根据企业id 获取物流订单相关地址信息
     *
     * @param entIds 企业id集合
     * @return
     */
    @Override
    public Map<Long, List<AddressResDTO>> getLogisticsOrderAddressListByEntId(List<Long> entIds) {
        Map<Long, List<AddressResDTO>> map = new HashMap<>(entIds.size());
        for (Long entId : entIds) {
            List<AddressResDTO> list = logisticsOrderMapper.getAddressDetailListByEntId(entId);
            if (Objects.nonNull(list)) {
                map.put(entId, list);
            }
        }
        return map;
    }
}
