package com.sckw.payment.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sckw.core.common.enums.NumberConstant;
import com.sckw.core.common.enums.enums.DictTypeEnum;
import com.sckw.core.exception.BusinessException;
import com.sckw.core.model.constant.Global;
import com.sckw.core.model.page.PageRes;
import com.sckw.core.model.vo.TableTop;
import com.sckw.core.utils.CollectionUtils;
import com.sckw.core.utils.IdWorker;
import com.sckw.core.utils.OrderGenerateUtils;
import com.sckw.core.utils.StringTimeUtil;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.payment.dao.KwpLedgerLogisticsMapper;
import com.sckw.payment.model.*;
import com.sckw.payment.model.constant.LedgerEnum;
import com.sckw.payment.model.constant.LedgerTrackEnum;
import com.sckw.payment.model.constant.LogisticsUnitType;
import com.sckw.payment.model.constant.SettlementEnum;
import com.sckw.payment.model.dto.ILedger;
import com.sckw.payment.model.dto.LedgerCarrierDto;
import com.sckw.payment.model.dto.LedgerLogisticsDto;
import com.sckw.payment.model.dto.LedgerShipperDto;
import com.sckw.payment.model.vo.req.*;
import com.sckw.payment.model.vo.res.LedgerLogisticsDetailVo;
import com.sckw.system.api.RemoteSystemService;
import com.sckw.system.api.model.dto.res.EntCacheResDto;
import com.sckw.system.api.model.dto.res.SysDictResDto;
import com.sckw.transport.api.dubbo.TransportDubboService;
import com.sckw.transport.api.model.vo.KwtLogisticsOrderVO;
import com.sckw.transport.api.model.vo.LogisticsOrderVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author xucaiqin
 * @date 2023-07-10 16:38:36
 */
@Service
@Slf4j
public class KwpLedgerLogisticsService extends AbsLedger {
    @Resource
    private KwpLedgerLogisticsTrackService logisticsTrackService;
    @Resource
    private KwpSettlementLogisticsService settlementLogisticsService;
    @Resource
    private KwpLedgerLogisticsUnitService logisticsUnitService;
    @Resource
    private KwpLedgerLogisticsOrderService logisticsOrderService;
    @Resource
    private KwpLedgerLogisticsMapper logisticsMapper;
    @DubboReference(version = "2.0.0", group = "design", check = false)
    private RemoteSystemService remoteSystemService;
    @DubboReference(version = "2.0.0", group = "design", check = false)
    private TransportDubboService transportDubboService;

    private void changeDict(List<ILedger> list) {
        List<SysDictResDto> taxRateDict = remoteSystemService.queryDictByType(DictTypeEnum.TAX_RATE.getType());
        Map<String, String> taxRateMap = new HashMap<>();
        Map<String, String> tradingMap = new HashMap<>();

        if (!CollectionUtils.isEmpty(taxRateDict)) {
            taxRateMap = taxRateDict.stream().collect(Collectors.toMap(SysDictResDto::getValue, SysDictResDto::getLabel, (a, b) -> a));
        }
        List<SysDictResDto> tradingDict = remoteSystemService.queryDictByType(DictTypeEnum.TRADE_TYPE.getType());
        if (!CollectionUtils.isEmpty(tradingDict)) {
            tradingMap = tradingDict.stream().collect(Collectors.toMap(SysDictResDto::getValue, SysDictResDto::getLabel, (a, b) -> a));
        }
        for (ILedger logisticsDto : list) {
            String trading = logisticsDto.getTrading();
            logisticsDto.setTradingLabel(tradingMap.get(trading));
            Integer taxRate = logisticsDto.getTaxRate();
            logisticsDto.setTaxRateLabel(taxRateMap.get(String.valueOf(taxRate)));

            logisticsDto.setStatusLabel(LedgerEnum.getDesc(logisticsDto.getStatus()));
        }
    }

    private void fillPara(LogisticsReq logisticsReq) {
        logisticsReq.setEntId(LoginUserHolder.getEntId());
        if (StringUtils.isNotBlank(logisticsReq.getStartCreateTime())) {
            logisticsReq.setStartCreateTime(StringTimeUtil.fillStart(logisticsReq.getStartCreateTime()));
        }
        if (StringUtils.isNotBlank(logisticsReq.getEndCreateTime())) {
            logisticsReq.setEndCreateTime(StringTimeUtil.fillEnd(logisticsReq.getEndCreateTime()));
        }
    }

    public PageRes<ILedger> shipperList(LogisticsReq logisticsReq) {
        fillPara(logisticsReq);
        logisticsReq.setUnitType(LogisticsUnitType.CARRIER);
        logisticsReq.setUnitTypeTwo(LogisticsUnitType.SHIPPER);
        PageHelper.startPage(logisticsReq.getPage(), logisticsReq.getPageSize());
        List<LedgerShipperDto> kwpLedgerLogisticsList = logisticsMapper.shipperSelect(logisticsReq);
        PageInfo<ILedger> ledgerShipperDtoPageInfo = new PageInfo<>(kwpLedgerLogisticsList);
        //字典转换
        if (!CollectionUtils.isEmpty(kwpLedgerLogisticsList)) {
            changeDict(ledgerShipperDtoPageInfo.getList());
            return new PageRes<>(ledgerShipperDtoPageInfo);
        }
        return new PageRes<>();
    }

    public PageRes<ILedger> carrierList(LogisticsReq logisticsReq) {
        fillPara(logisticsReq);
        logisticsReq.setUnitType(LogisticsUnitType.SHIPPER);
        logisticsReq.setUnitTypeTwo(LogisticsUnitType.CARRIER);
        PageHelper.startPage(logisticsReq.getPage(), logisticsReq.getPageSize());
        List<LedgerCarrierDto> kwpLedgerLogisticsList = logisticsMapper.carrierSelect(logisticsReq);
        PageInfo<ILedger> ledgerShipperDtoPageInfo = new PageInfo<>(kwpLedgerLogisticsList);
        //字典转换
        if (!CollectionUtils.isEmpty(kwpLedgerLogisticsList)) {
            changeDict(ledgerShipperDtoPageInfo.getList());
            return new PageRes<>(ledgerShipperDtoPageInfo);
        }
        return new PageRes<>();
    }

    /**
     * 保存物流对账单
     *
     * @param logisticsReq
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String sendLedger(LogisticsSendReq logisticsReq) {
        String id = logisticsReq.getId();
        if (StringUtils.isBlank(id)) {
            //新增
            logisticsReq.setGenerateTime(LocalDateTime.now());
            logisticsReq.setStatus(LedgerEnum.TO_LEDGER.getStatus());
            Long aLong = saveDraft(logisticsReq);
            logisticsTrackService.saveTrack(aLong, Global.EMPTY_STRING, LedgerTrackEnum.TO_LEDGER);
        } else {
            removeDraft(Long.parseLong(id));
            logisticsReq.setGenerateTime(LocalDateTime.now());
            logisticsReq.setStatus(LedgerEnum.TO_LEDGER.getStatus());
            Long aLong = saveDraft(logisticsReq);
            logisticsTrackService.saveTrack(aLong, Global.EMPTY_STRING, LedgerTrackEnum.TO_LEDGER);

        }
        return "保存对账单成功";
    }

    /**
     * 删除物流对账单相关联的其它数据
     *
     * @param id 物流对账单id
     */
    private void removeDraft(Long id) {
        //删除 kwp_ledger_logistics_order
        logisticsOrderService.remove(id);
        //删除 kwp_ledger_logistics_track
        logisticsTrackService.remove(id);
        //删除 kwp_ledger_logistics_unit
        logisticsUnitService.remove(id);
    }

    /**
     * 物流对账单保存草稿
     *
     * @param logisticsSendReq 物流对账单新增参数
     * @return
     */
    private Long saveDraft(LogisticsSendReq logisticsSendReq) {
        KwpLedgerLogistics kwpLedgerLogistics = new KwpLedgerLogistics();
        kwpLedgerLogistics.setId(Objects.isNull(logisticsSendReq.getIdLong()) ? new IdWorker(1).nextId() : logisticsSendReq.getIdLong());
        kwpLedgerLogistics.setEntId(LoginUserHolder.getEntId());
        kwpLedgerLogistics.setName(logisticsSendReq.getName());
        if (StringUtils.isNotBlank(logisticsSendReq.getStartTime())) {
            kwpLedgerLogistics.setStartTime(StringTimeUtil.startDateTime(logisticsSendReq.getStartTime()));
        }
        if (StringUtils.isNotBlank(logisticsSendReq.getEndTime())) {
            kwpLedgerLogistics.setEndTime(StringTimeUtil.endDateTime(logisticsSendReq.getEndTime()));
        }
        kwpLedgerLogistics.setTaxRate(logisticsSendReq.getTaxRate());
        kwpLedgerLogistics.setTrading(logisticsSendReq.getTrading());
        kwpLedgerLogistics.setTotalPrice(logisticsSendReq.getTotalPrice());
        kwpLedgerLogistics.setExTaxPrice(logisticsSendReq.getTotalPrice());//todo-xcq 不含税金额计算方式：订单含税金额总和/1.13(税率)
        kwpLedgerLogistics.setSettlePrice(logisticsSendReq.getSettlePrice());
        kwpLedgerLogistics.setActualPrice(new BigDecimal("0.0"));
        kwpLedgerLogistics.setAuditUser(Global.EMPTY_STRING);
        kwpLedgerLogistics.setAuditPhone(Global.EMPTY_STRING);
        kwpLedgerLogistics.setReceiptTime(null);
        kwpLedgerLogistics.setOrderCount(logisticsSendReq.getIdList().size());
        kwpLedgerLogistics.setUrl(Global.EMPTY_STRING);
        kwpLedgerLogistics.setGenerateTime(logisticsSendReq.getGenerateTime());
        kwpLedgerLogistics.setRemark(logisticsSendReq.getRemark());
        kwpLedgerLogistics.setStatus(logisticsSendReq.getStatus());
        kwpLedgerLogistics.setDelFlag(Global.UN_DELETED);
        //id为空，新增对账单
        if (Objects.isNull(logisticsSendReq.getId())) {
            kwpLedgerLogistics.setCreateBy(LoginUserHolder.getUserId());
            kwpLedgerLogistics.setCreateTime(LocalDateTime.now());
            kwpLedgerLogistics.setUpdateBy(LoginUserHolder.getUserId());
            kwpLedgerLogistics.setUpdateTime(LocalDateTime.now());
            kwpLedgerLogistics.setLLedgerNo(OrderGenerateUtils.generateOrderNo("LL"));
            logisticsMapper.insert(kwpLedgerLogistics);
        } else {
            //校验是否可以修改对账单
            KwpLedgerLogistics ledgerLogistics = logisticsMapper.selectById(logisticsSendReq.getIdLong());
            orderCheck(ledgerLogistics);
            updateCheck(ledgerLogistics.getStatus());
            //修改对账单
            kwpLedgerLogistics.setUpdateBy(LoginUserHolder.getUserId());
            kwpLedgerLogistics.setUpdateTime(LocalDateTime.now());
            logisticsMapper.updateById(kwpLedgerLogistics);
        }
        /*保存物流订单关联数据*/
        List<Long> ids = logisticsSendReq.getIdList();
        //验当前订单是否已存在绑定的对账单
        logisticsOrderService.check(ids);
        List<KwtLogisticsOrderVO> acceptCarriageOrderDetail = transportDubboService.getAcceptCarriageOrderDetail(logisticsSendReq.getIdsList());
        if (CollectionUtils.isEmpty(acceptCarriageOrderDetail) || acceptCarriageOrderDetail.size() < ids.size()) {
            throw new BusinessException("未找到物流订单!");
        }
        List<KwpLedgerLogisticsOrder> collect = acceptCarriageOrderDetail.stream().map(a -> {
            KwpLedgerLogisticsOrder logisticsOrder = new KwpLedgerLogisticsOrder();
            logisticsOrder.setId(new IdWorker(NumberConstant.ONE).nextId());
            logisticsOrder.setLLedgerId(kwpLedgerLogistics.getId());
            logisticsOrder.setLOrderId(a.getId());
            logisticsOrder.setLOrderNo(a.getLOrderNo());
            logisticsOrder.setRemark(Global.EMPTY_STRING);
            logisticsOrder.setStatus(NumberConstant.ZERO);
            logisticsOrder.setCreateBy(LoginUserHolder.getUserId());
            logisticsOrder.setCreateTime(LocalDateTime.now());
            logisticsOrder.setUpdateBy(LoginUserHolder.getUserId());
            logisticsOrder.setUpdateTime(LocalDateTime.now());
            logisticsOrder.setDelFlag(Global.UN_DELETED);
            return logisticsOrder;
        }).collect(Collectors.toList());

        logisticsOrderService.saveList(collect);
        /*保存企业相关信息*/
        Long checkEntId = Long.parseLong(logisticsSendReq.getCheckEntId());

        Map<Long, EntCacheResDto> entMap = remoteSystemService.queryEntTreeByIds(Collections.singletonList(checkEntId));
        EntCacheResDto entCacheResDto = entMap.get(checkEntId);
        if (Objects.isNull(entCacheResDto)) {
            entCacheResDto = new EntCacheResDto();
        }

        List<KwpLedgerLogisticsUnit> logisticsUnits = new ArrayList<>();
        KwpLedgerLogisticsUnit kwpLedgerLogisticsUnit = new KwpLedgerLogisticsUnit();
        kwpLedgerLogisticsUnit.setId(new IdWorker(NumberConstant.ONE).nextId());
        kwpLedgerLogisticsUnit.setLLedgerId(kwpLedgerLogistics.getId());
        kwpLedgerLogisticsUnit.setLLedgerNo(kwpLedgerLogistics.getLLedgerNo());
        kwpLedgerLogisticsUnit.setUnitType(LogisticsUnitType.SHIPPER);
        kwpLedgerLogisticsUnit.setEntId(checkEntId);
        kwpLedgerLogisticsUnit.setTopEntId(entCacheResDto.getId());
        kwpLedgerLogisticsUnit.setFirmName(entCacheResDto.getFirmName());
        kwpLedgerLogisticsUnit.setContacts(entCacheResDto.getContacts());
        kwpLedgerLogisticsUnit.setPhone(entCacheResDto.getPhone());
        kwpLedgerLogisticsUnit.setRemark(Global.EMPTY_STRING);
        kwpLedgerLogisticsUnit.setStatus(NumberConstant.ZERO);
        kwpLedgerLogisticsUnit.setCreateBy(LoginUserHolder.getUserId());
        kwpLedgerLogisticsUnit.setCreateTime(LocalDateTime.now());
        kwpLedgerLogisticsUnit.setUpdateBy(LoginUserHolder.getUserId());
        kwpLedgerLogisticsUnit.setUpdateTime(LocalDateTime.now());
        kwpLedgerLogisticsUnit.setDelFlag(Global.UN_DELETED);

        logisticsUnits.add(kwpLedgerLogisticsUnit);
        Long entId = LoginUserHolder.getEntId();
        Map<Long, EntCacheResDto> entCarrierMap = remoteSystemService.queryEntTreeByIds(Collections.singletonList(entId));
        EntCacheResDto entCacheResDto1 = entCarrierMap.get(entId);
        if (Objects.isNull(entCacheResDto1)) {
            entCacheResDto1 = new EntCacheResDto();
        }
        KwpLedgerLogisticsUnit carrierUnit = new KwpLedgerLogisticsUnit();
        carrierUnit.setId(new IdWorker(NumberConstant.ONE).nextId());
        carrierUnit.setLLedgerId(kwpLedgerLogistics.getId());
        carrierUnit.setLLedgerNo(kwpLedgerLogistics.getLLedgerNo());
        carrierUnit.setUnitType(LogisticsUnitType.CARRIER);
        carrierUnit.setEntId(entId);//顶级企业id
        carrierUnit.setTopEntId(entCacheResDto1.getId());//顶级企业id
        carrierUnit.setFirmName(entCacheResDto1.getFirmName());
        carrierUnit.setContacts(entCacheResDto1.getContacts());
        carrierUnit.setPhone(entCacheResDto1.getPhone());
        carrierUnit.setRemark(Global.EMPTY_STRING);
        carrierUnit.setStatus(NumberConstant.ZERO);
        carrierUnit.setCreateBy(LoginUserHolder.getUserId());
        carrierUnit.setCreateTime(LocalDateTime.now());
        carrierUnit.setUpdateBy(LoginUserHolder.getUserId());
        carrierUnit.setUpdateTime(LocalDateTime.now());
        carrierUnit.setDelFlag(Global.UN_DELETED);

        logisticsUnits.add(carrierUnit);
        logisticsUnitService.saveList(logisticsUnits);
        return kwpLedgerLogistics.getId();
    }

    /**
     * 保存物流对账单草稿
     *
     * @param logisticsReq 物流对账单保存的参数
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String sendLedgerDraft(LogisticsSendReq logisticsReq) {
        logisticsReq.setGenerateTime(null);
        logisticsReq.setStatus(LedgerEnum.SAVE.getStatus());
        Long aLong = saveDraft(logisticsReq);
        logisticsTrackService.saveTrack(aLong, Global.EMPTY_STRING, LedgerTrackEnum.SAVE);
        return "草稿保存成功";
    }

    /**
     * 删除物流对账单
     *
     * @param id 物流对账单id
     * @return
     */
    public String remove(Long id) {
        KwpLedgerLogistics kwpLedgerLogistics = logisticsMapper.selectById(id);
        if (Objects.isNull(kwpLedgerLogistics)) {
            throw new BusinessException("对账单不存在!");
        }
        deleteCheck(kwpLedgerLogistics.getStatus());
        kwpLedgerLogistics.setDelFlag(Global.DELETED);
        logisticsMapper.updateById(kwpLedgerLogistics);
        logisticsTrackService.saveTrack(id, Global.EMPTY_STRING, LedgerTrackEnum.DELETE);
        return "删除成功";
    }

    /**
     * 撤回物流对账单
     *
     * @param id 物流对账单id
     * @return
     */
    public String backOrder(Long id) {
        KwpLedgerLogistics kwpLedgerLogistics = logisticsMapper.selectById(id);
        if (Objects.isNull(kwpLedgerLogistics)) {
            throw new BusinessException("对账单不存在!");
        }
        revokeCheck(kwpLedgerLogistics.getStatus());

        kwpLedgerLogistics.setStatus(LedgerEnum.REVOCATION.getStatus());
        kwpLedgerLogistics.setUpdateBy(LoginUserHolder.getUserId());
        kwpLedgerLogistics.setUpdateTime(LocalDateTime.now());
        logisticsMapper.updateById(kwpLedgerLogistics);
        logisticsTrackService.saveTrack(id, Global.EMPTY_STRING, LedgerTrackEnum.REVOKE);
        return "撤回成功";
    }

    /**
     * 查询物流对账单驳回记录
     *
     * @param id 物流对账单id
     * @return 物流对账单驳回记录
     */
    public KwpLedgerLogisticsTrack queryBack(Long id) {
        KwpLedgerLogistics kwpLedgerLogistics = logisticsMapper.selectById(id);
        orderCheck(kwpLedgerLogistics);
        backQueryCheck(kwpLedgerLogistics.getStatus());
        return logisticsTrackService.selectOne(id, LedgerTrackEnum.REJECT);
    }

    /**
     * 驳回物流对账单
     *
     * @param ledgerReq 驳回参数
     * @return
     */
    public String doBack(LedgerReq ledgerReq) {
        KwpLedgerLogistics kwpLedgerLogistics = logisticsMapper.selectById(ledgerReq.getIdLong());
        if (Objects.isNull(kwpLedgerLogistics)) {
            throw new BusinessException("对账单不存在!");
        }
        backCheck(kwpLedgerLogistics.getStatus());
        kwpLedgerLogistics.setStatus(LedgerEnum.BACK.getStatus());
        kwpLedgerLogistics.setUpdateBy(LoginUserHolder.getUserId());
        kwpLedgerLogistics.setUpdateTime(LocalDateTime.now());
        logisticsMapper.updateById(kwpLedgerLogistics);
        logisticsTrackService.saveTrack(ledgerReq.getIdLong(), ledgerReq.getRemark(), LedgerTrackEnum.REJECT);
        return "驳回成功";
    }

    /**
     * 对账确认
     * 订单变更为已对账
     *
     * @param confirmReq 对账确认请求参数
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String confirmOrder(LedgerConfirmReq confirmReq) {
        KwpLedgerLogistics kwpLedgerLogistics = logisticsMapper.selectById(confirmReq.getIdLong());
        orderCheck(kwpLedgerLogistics);
        confirmCheck(kwpLedgerLogistics.getStatus());
        kwpLedgerLogistics.setStatus(LedgerEnum.LEDGERED.getStatus());
        kwpLedgerLogistics.setAuditPhone(confirmReq.getAuditPhone());
        kwpLedgerLogistics.setAuditUser(confirmReq.getAuditUser());
        kwpLedgerLogistics.setUrl(confirmReq.getUrl());
        kwpLedgerLogistics.setUpdateTime(LocalDateTime.now());
        kwpLedgerLogistics.setUpdateBy(LoginUserHolder.getUserId());
        logisticsMapper.updateById(kwpLedgerLogistics);
        logisticsTrackService.saveTrack(confirmReq.getIdLong(), Global.EMPTY_STRING, LedgerTrackEnum.CONFIRM);
        return "对账确认成功";
    }

    /**
     * 对账完成
     *
     * @param ledgerReq 对账完成参数
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String orderSuccess(LedgerSuccessReq ledgerReq) {
        KwpLedgerLogistics kwpLedgerLogistics = logisticsMapper.selectById(ledgerReq.getIdLong());
        orderCheck(kwpLedgerLogistics);

        successCheck(kwpLedgerLogistics.getStatus());
        //更新对账单状态
        LocalDateTime receiptTime = null;

        if (Objects.nonNull(ledgerReq.getReceiptTime())) {
            receiptTime = LocalDateTime.of(ledgerReq.getReceiptTime(), LocalTime.MIN);
            kwpLedgerLogistics.setReceiptTime(receiptTime);
        }
        kwpLedgerLogistics.setStatus(LedgerEnum.SUCCESS.getStatus());
        kwpLedgerLogistics.setUpdateBy(LoginUserHolder.getUserId());
        kwpLedgerLogistics.setUpdateTime(LocalDateTime.now());
        logisticsMapper.updateById(kwpLedgerLogistics);
        //生成结算单
        KwpSettlementLogistics kwpSettlementLogistics = new KwpSettlementLogistics();
        kwpSettlementLogistics.setId(new IdWorker(NumberConstant.ONE).nextId());
        kwpSettlementLogistics.setEntId(LoginUserHolder.getEntId());
        kwpSettlementLogistics.setLLedgerId(kwpLedgerLogistics.getId());
        kwpSettlementLogistics.setSlOrderNo(OrderGenerateUtils.generateOrderNo("SL"));
        kwpSettlementLogistics.setName(kwpLedgerLogistics.getName());//取物流对账单名称
        kwpSettlementLogistics.setTotalPrice(kwpLedgerLogistics.getTotalPrice());
        kwpSettlementLogistics.setActualPrice(kwpLedgerLogistics.getActualPrice());
        kwpSettlementLogistics.setRemark(Global.EMPTY_STRING);
        kwpSettlementLogistics.setAuditUser(kwpLedgerLogistics.getAuditUser());
        kwpSettlementLogistics.setAuditPhone(kwpLedgerLogistics.getAuditPhone());
        kwpSettlementLogistics.setSuccessUser(ledgerReq.getSuccessUser());
        kwpSettlementLogistics.setSuccessPhone(ledgerReq.getSuccessPhone());
        kwpSettlementLogistics.setReceiptTime(receiptTime);
        kwpSettlementLogistics.setStatus(SettlementEnum.WAITING_PAYMENT.getStatus());//1-待结算
        kwpSettlementLogistics.setCreateBy(LoginUserHolder.getUserId());
        kwpSettlementLogistics.setCreateTime(LocalDateTime.now());
        kwpSettlementLogistics.setUpdateBy(LoginUserHolder.getUserId());
        kwpSettlementLogistics.setUpdateTime(LocalDateTime.now());
        kwpSettlementLogistics.setDelFlag(Global.UN_DELETED);

        settlementLogisticsService.save(kwpSettlementLogistics);

        logisticsTrackService.saveTrack(ledgerReq.getIdLong(), Global.EMPTY_STRING, LedgerTrackEnum.SUCCESS);
        return "对账完成";
    }

    /**
     * 按类型统计表头的数据
     * 1-托运方 2-承运方
     *
     * @param logisticsReq 查询参数
     * @return 统计数据
     */
    public List<TableTop> orderCount(LogisticsReq logisticsReq) {
        logisticsReq.setEntId(LoginUserHolder.getEntId());
        Map<String, Long> map = logisticsMapper.countOrder(logisticsReq);
        TableTop ledgerCountVo;
        /*统计数据转换*/
        List<TableTop> res = new ArrayList<>();
        for (LedgerEnum value : LedgerEnum.values()) {
            ledgerCountVo = new TableTop();
            ledgerCountVo.setTotal(Math.toIntExact(map.get(value.getLabel())));
            ledgerCountVo.setName(value.getDesc());
            ledgerCountVo.setValue(value.getStatus());
            res.add(ledgerCountVo);
        }
        return res;
    }

    /**
     * 托运方 查询物流对账单
     *
     * @param ids 对账单id列表
     * @return 物流对账单列表
     */
    public List<ILedger> selectShipperList(List<Long> ids) {
        List<LedgerShipperDto> ledgerLogisticsDto = logisticsMapper.selectShipperIds(ids);
        List<ILedger> ledgerLogistics = new ArrayList<>(ledgerLogisticsDto);
        changeDict(ledgerLogistics);
        return ledgerLogistics;
    }

    /**
     * 承运方 查询物流对账单
     *
     * @param ids 对账单id列表
     * @return 物流对账单列表
     */
    public List<ILedger> selectCarrierList(List<Long> ids) {
        List<LedgerCarrierDto> ledgerLogisticsDto = logisticsMapper.selectCarrierIds(ids);
        List<ILedger> ledgerLogistics = new ArrayList<>(ledgerLogisticsDto);
        changeDict(ledgerLogistics);
        return ledgerLogistics;
    }

    /**
     * 根据物流订单id查询对账单详情
     *
     * @param id 物流对账单id
     * @return
     */
    public LedgerLogisticsDetailVo queryUpdate(Long id) {
        LedgerLogisticsDto ledgerLogisticsDto = logisticsMapper.selectId(id, LogisticsUnitType.SHIPPER);
        orderCheck(ledgerLogisticsDto);
        updateCheck(ledgerLogisticsDto.getStatus());
        return getLedgerLogisticsDetailVo(ledgerLogisticsDto);
    }

    /**
     * 查询物流对账单详情
     *
     * @param id       物流对账单id
     * @param unitType 企业单位类型
     * @return
     */
    public LedgerLogisticsDetailVo queryDetail(Long id, Integer unitType) {
        LedgerLogisticsDto ledgerLogisticsDto = logisticsMapper.selectId(id, unitType);
        orderCheck(ledgerLogisticsDto);
        return getLedgerLogisticsDetailVo(ledgerLogisticsDto);
    }

    /**
     * 转换物流对账单详情数据
     *
     * @param ledgerLogisticsDto
     * @return
     */
    private LedgerLogisticsDetailVo getLedgerLogisticsDetailVo(LedgerLogisticsDto ledgerLogisticsDto) {
        /*获取物流对账单关联的物流订单*/
        List<KwpLedgerLogisticsOrder> kwpLedgerLogisticsOrders = logisticsOrderService.queryList(ledgerLogisticsDto.getId());
        LedgerLogisticsDetailVo ledgerLogisticsDetailVo = new LedgerLogisticsDetailVo();
        SysDictResDto trading = remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.TRADE_TYPE.getType(), ledgerLogisticsDto.getTrading());
        SysDictResDto taxRate = remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.TRADE_TYPE.getType(), String.valueOf(ledgerLogisticsDto.getTaxRate()));

        ledgerLogisticsDetailVo.setId(ledgerLogisticsDto.getId());
        ledgerLogisticsDetailVo.setCheckEntId(ledgerLogisticsDto.getCheckEntId());
        ledgerLogisticsDetailVo.setLLedgerNo(ledgerLogisticsDto.getLLedgerNo());
        ledgerLogisticsDetailVo.setName(ledgerLogisticsDto.getName());
        ledgerLogisticsDetailVo.setFirmName(ledgerLogisticsDto.getFirmName());
        ledgerLogisticsDetailVo.setTrading(ledgerLogisticsDto.getTrading());
        ledgerLogisticsDetailVo.setTradingLabel(Objects.nonNull(trading) ? trading.getLabel() : "");

        ledgerLogisticsDetailVo.setTaxRate(ledgerLogisticsDto.getTaxRate());
        ledgerLogisticsDetailVo.setTaxRateLabel(Objects.nonNull(taxRate) ? taxRate.getLabel() : "");
        ledgerLogisticsDetailVo.setTotalPrice(ledgerLogisticsDto.getTotalPrice());
        ledgerLogisticsDetailVo.setSettlePrice(ledgerLogisticsDto.getSettlePrice());
        ledgerLogisticsDetailVo.setActualPrice(ledgerLogisticsDto.getActualPrice());
        ledgerLogisticsDetailVo.setStartTime(ledgerLogisticsDto.getStartTime());
        ledgerLogisticsDetailVo.setEndTime(ledgerLogisticsDto.getEndTime());
        ledgerLogisticsDetailVo.setRemark(ledgerLogisticsDto.getRemark());
        /*查询物流订单详情*/
        if (!CollectionUtils.isEmpty(kwpLedgerLogisticsOrders)) {
            List<LogisticsOrderVO> acceptCarriageOrderList = transportDubboService.getAcceptCarriageOrderList(kwpLedgerLogisticsOrders.stream().map(a -> Long.toString(a.getLOrderId())).collect(Collectors.toList()));
            if (CollectionUtils.isEmpty(acceptCarriageOrderList)) {
                ledgerLogisticsDetailVo.setOrderList(new ArrayList<>());
            } else {
                ledgerLogisticsDetailVo.setOrderList(acceptCarriageOrderList);
            }
        }
        return ledgerLogisticsDetailVo;
    }

    public PageRes<LogisticsOrderVO> orderList(LedgerListReq ledgerListReq) {
        PageHelper.startPage(ledgerListReq.getPage(), ledgerListReq.getPageSize());
        List<KwpLedgerLogisticsOrder> kwpLedgerLogisticsOrders = logisticsOrderService.queryList(ledgerListReq.getIdLong());
        if (CollectionUtils.isEmpty(kwpLedgerLogisticsOrders)) {
            return new PageRes<>();
        }
        PageInfo<KwpLedgerLogisticsOrder> pageInfo = new PageInfo<>(kwpLedgerLogisticsOrders);
        List<LogisticsOrderVO> acceptCarriageOrderList = transportDubboService.getAcceptCarriageOrderList(kwpLedgerLogisticsOrders.stream().map(a -> String.valueOf(a.getLOrderId())).toList());
        return PageRes.build(pageInfo, acceptCarriageOrderList);
    }

}
