package com.sckw.payment.service;

import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sckw.core.model.constant.NumberConstant;
import com.sckw.core.common.enums.enums.DictEnum;
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.enums.OrderRuleEnum;
import com.sckw.core.model.enums.RedisOrderGenerateEnum;
import com.sckw.core.model.page.PageRes;
import com.sckw.core.model.vo.TableTop;
import com.sckw.core.utils.*;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.order.api.dubbo.TradeOrderInfoService;
import com.sckw.order.api.model.*;
import com.sckw.payment.dao.KwpLedgerTradeMapper;
import com.sckw.payment.model.*;
import com.sckw.payment.model.constant.*;
import com.sckw.payment.model.dto.*;
import com.sckw.payment.model.vo.req.*;
import com.sckw.payment.model.vo.res.LedgerCountSumVo;
import com.sckw.payment.model.vo.res.LedgerTradeDetailVo;
import com.sckw.stream.enums.MessageEnum;
import com.sckw.stream.model.UserInfo;
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.system.api.model.dto.res.UserCacheResDto;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
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
@RequiredArgsConstructor
public class KwpLedgerTradeService extends AbsLedger {
    private final KwpLedgerTradeMapper tradeMapper;
    private final KwpLedgerTradeTrackService tradeTrackService;
    private final KwpLedgerTradeOrderService tradeOrderService;
    private final KwpLedgerTradeUnitService tradeUnitService;
    private final KwpTradeFreezeService kwpTradeFreezeService;
    private final MessageSender messageSender;
    @Resource
    private KwpSettlementTradeService kwpSettlementTradeService;
    @DubboReference(version = "1.0.0", group = "design", check = false)
    private RemoteSystemService remoteSystemService;
    @DubboReference(version = "1.0.0", group = "design", check = false)
    private TradeOrderInfoService tradeOrderInfoService;

    /**
     * 转换字典数据
     *
     * @param list
     */
    private void changeDict(List<? extends ILedger> list) {
        List<SysDictResDto> taxRateDict = remoteSystemService.queryDictByType(DictTypeEnum.TAX_RATE.getType());
        Map<String, String> taxRateMap = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        Map<String, String> tradingMap = new HashMap<>(Global.NUMERICAL_SIXTEEN);

        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 tradeDto : list) {
            String trading = tradeDto.getTrading();
            tradeDto.setTradingLabel(tradingMap.get(trading));
            Integer taxRate = tradeDto.getTaxRate();
            tradeDto.setTaxRateLabel(taxRateMap.get(String.valueOf(taxRate)));

            tradeDto.setStatusLabel(LedgerEnum.getDesc(tradeDto.getStatus()));
            UserCacheResDto userCacheResDto = remoteSystemService.queryUserCacheById(tradeDto.getCreateBy());
            if (Objects.nonNull(userCacheResDto)) {
                tradeDto.setCreateByName(userCacheResDto.getName());
            }
        }
    }

    /**
     * 填充时间等参数
     *
     * @param tradeReq 请求参数
     */
    private void fillPara(TradeReq tradeReq) {
        tradeReq.setEntId(LoginUserHolder.getEntId());
        if (StringUtils.isNotBlank(tradeReq.getStartCreateTime())) {
            tradeReq.setStartCreateTime(StringTimeUtil.fillStart(tradeReq.getStartCreateTime()));
        }
        if (StringUtils.isNotBlank(tradeReq.getEndCreateTime())) {
            tradeReq.setEndCreateTime(StringTimeUtil.fillEnd(tradeReq.getEndCreateTime()));
        }
    }

    /**
     * 销售方
     *
     * @param tradeReq
     * @return
     */
    public PageRes<LedgerSellDto> sellList(TradeReq tradeReq) {
        fillPara(tradeReq);
        if (tradeReq.getPage() != 0 && tradeReq.getPageSize() != 0) {
            PageHelper.startPage(tradeReq.getPage(), tradeReq.getPageSize());
        }
        tradeReq.setUnitType(TradeUnitType.PURCHASE);
        tradeReq.setUnitTypeTwo(TradeUnitType.SELL);
        List<LedgerSellDto> ledgerTradeDto = tradeMapper.sellList(tradeReq, LoginUserHolder.getAuthUserIdList());
        //字典转换
        if (!CollectionUtils.isEmpty(ledgerTradeDto)) {
            changeDict(ledgerTradeDto);
            return new PageRes<>(ledgerTradeDto);
        }
        return new PageRes<>();
    }

    /**
     * app端统计对账数据
     *
     * @param tradeReq
     * @return 总应收、对账单数
     */
    public LedgerCountSumVo sellSum(TradeReq tradeReq) {
        fillPara(tradeReq);
        tradeReq.setUnitType(TradeUnitType.PURCHASE);
        tradeReq.setUnitTypeTwo(TradeUnitType.SELL);
        List<Integer> status = new ArrayList<>();

        Long aLong = tradeMapper.countSum(tradeReq, status);
        BigDecimal bigDecimal = tradeMapper.countSumMoney(tradeReq, status);
        return new LedgerCountSumVo(bigDecimal, aLong);
    }

    /**
     * 采购方
     *
     * @param tradeReq
     * @return
     */
    public PageRes<LedgerPurchaseDto> purchaseList(TradeReq tradeReq) {
        fillPara(tradeReq);
        if (tradeReq.getPage() != 0 && tradeReq.getPageSize() != 0) {
            PageHelper.startPage(tradeReq.getPage(), tradeReq.getPageSize());
        }
        tradeReq.setUnitType(TradeUnitType.SELL);
        tradeReq.setUnitTypeTwo(TradeUnitType.PURCHASE);
        List<LedgerPurchaseDto> ledgerTradeDto = tradeMapper.purchaseList(tradeReq, LoginUserHolder.getAuthUserIdList());
        //字典转换
        if (!CollectionUtils.isEmpty(ledgerTradeDto)) {
            changeDict(ledgerTradeDto);
            return new PageRes<>(ledgerTradeDto);
        }
        return new PageRes<>(new PageInfo<>());
    }

    public LedgerCountSumVo purchaseSum(TradeReq tradeReq) {
        fillPara(tradeReq);
        tradeReq.setUnitType(TradeUnitType.SELL);
        tradeReq.setUnitTypeTwo(TradeUnitType.PURCHASE);
        List<Integer> status = new ArrayList<>() {{
            add(LedgerEnum.SAVE.getStatus());
            add(LedgerEnum.REVOCATION.getStatus());
        }};
        Long aLong = tradeMapper.countSum(tradeReq, status);
        BigDecimal bigDecimal = tradeMapper.countSumMoney(tradeReq, status);
        return new LedgerCountSumVo(bigDecimal, aLong);
    }

    private void removeDraft(Long id) {
        //删除kwp_ledger_trade_order
        tradeOrderService.remove(id);
        //删除kwp_ledger_trade_track
        tradeTrackService.remove(id);
        //删除kwp_ledger_trade_unit
        tradeUnitService.remove(id);
    }

    /**
     * 保存草稿
     *
     * @param tradeSendReq
     * @return 对账单id
     */
    private IdNo saveDraft(TradeSendReq tradeSendReq) {
        KwpLedgerTrade kwpLedgerTrade = new KwpLedgerTrade();
        kwpLedgerTrade.setId(Objects.isNull(tradeSendReq.getId()) ? new IdWorker(1).nextId() : tradeSendReq.getIdLong());
        kwpLedgerTrade.setEntId(LoginUserHolder.getEntId());
        kwpLedgerTrade.setName(tradeSendReq.getName());
        if (StringUtils.isNotBlank(tradeSendReq.getStartTime())) {
            kwpLedgerTrade.setStartTime(StringTimeUtil.startDateTime(tradeSendReq.getStartTime()));
        }
        if (StringUtils.isNotBlank(tradeSendReq.getEndTime())) {
            kwpLedgerTrade.setEndTime(StringTimeUtil.endDateTime(tradeSendReq.getEndTime()));
        }
        kwpLedgerTrade.setTaxRate(tradeSendReq.getTaxRate());
        kwpLedgerTrade.setTrading(tradeSendReq.getTrading());
        kwpLedgerTrade.setTotalPrice(tradeSendReq.getTotalPrice());
        //todo-xcq 不含税金额计算方式：订单含税金额总和/1.13(税率)
        kwpLedgerTrade.setExTaxPrice(tradeSendReq.getTotalPrice());
        kwpLedgerTrade.setSettlePrice(tradeSendReq.getSettlePrice());
        kwpLedgerTrade.setActualPrice(new BigDecimal("0.0"));
        kwpLedgerTrade.setDeductPrice(tradeSendReq.getDeductPrice());
        kwpLedgerTrade.setAuditUser(Global.EMPTY_STRING);
        kwpLedgerTrade.setAuditPhone(Global.EMPTY_STRING);
        kwpLedgerTrade.setGenerateTime(tradeSendReq.getGenerateTime());
        kwpLedgerTrade.setReceiptTime(null);
        kwpLedgerTrade.setOrderCount(tradeSendReq.getIdList().size());
        kwpLedgerTrade.setUrl(Global.EMPTY_STRING);
        kwpLedgerTrade.setRemark(tradeSendReq.getRemark());
        kwpLedgerTrade.setStatus(tradeSendReq.getStatus());

        kwpLedgerTrade.setDelFlag(Global.UN_DELETED);
        if (Objects.isNull(tradeSendReq.getId())) {
            kwpLedgerTrade.setTLedgerNo(OrderGenerateSeqNoUtils.getOtherSeqNo(RedisOrderGenerateEnum.LEDGER_CHECKING, OrderRuleEnum.LEDGER_TRADE_ORDER));
            kwpLedgerTrade.setCreateBy(LoginUserHolder.getUserId());
            kwpLedgerTrade.setCreateTime(LocalDateTime.now());
            kwpLedgerTrade.setUpdateBy(LoginUserHolder.getUserId());
            kwpLedgerTrade.setUpdateTime(LocalDateTime.now());
            tradeMapper.insert(kwpLedgerTrade);
        } else {
            KwpLedgerTrade ledgerTrade = tradeMapper.selectById(tradeSendReq.getId());
            orderCheck(ledgerTrade);
            updateCheck(ledgerTrade.getStatus());
            kwpLedgerTrade.setTLedgerNo(ledgerTrade.getTLedgerNo());
            kwpLedgerTrade.setUpdateBy(LoginUserHolder.getUserId());
            kwpLedgerTrade.setUpdateTime(LocalDateTime.now());
            tradeMapper.updateById(kwpLedgerTrade);
        }

        /*保存贸易订单关联数据*/
        List<Long> ids = tradeSendReq.getIdList();
        //校验当前订单是否已存在绑定的对账单
        tradeOrderService.check(ids);
        List<OrderDetailRes> resList = new ArrayList<>();
        Map<Long, String> map = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        String trading = tradeSendReq.getTrading();
        for (Long id : ids) {
            OrderDetailRes orderDetailById = tradeOrderInfoService.getOrderDetailById(id);
            if (Objects.isNull(orderDetailById)) {
                throw new BusinessException("订单未找到");
            }
            //1x 预付款 2x 货到付款 3x 线下付款
            Integer prefix = TradingEnum.getPrefix(trading);
            //仅预付款需要校验冻结单号
            if (Objects.nonNull(prefix) && prefix == TradingEnum.PRE_PAY.getStatus()) {
                KwpTradeFreeze byTOrderId = kwpTradeFreezeService.getByTOrderId(id);
                if (Objects.isNull(byTOrderId)) {
                    throw new BusinessException("未找到关联的冻结单");
                }
                map.put(id, byTOrderId.getOrderNo());
            }
            resList.add(orderDetailById);
        }
        for (Long id : ids) {
            //dubbo 更新关联订单状态为已绑定
            UpdateAssociateStatementParam updateAssociateStatementParam = new UpdateAssociateStatementParam();
            updateAssociateStatementParam.setTOrderId(id);
            updateAssociateStatementParam.setAssociateStatement(1);
            updateAssociateStatementParam.setUpdateBy(LoginUserHolder.getUserId());
            updateAssociateStatementParam.setUpdateByName(LoginUserHolder.getUserName());
            tradeOrderInfoService.updateAssociateStatement(updateAssociateStatementParam);
        }
        List<KwpLedgerTradeOrder> collect = resList.stream().map(a -> {
            KwpLedgerTradeOrder kwpLedgerTradeOrder = new KwpLedgerTradeOrder();
            kwpLedgerTradeOrder.setId(new IdWorker(NumberConstant.ONE).nextId());
            kwpLedgerTradeOrder.setOrderNo(map.get(a.getId()));
            kwpLedgerTradeOrder.setTLedgerId(kwpLedgerTrade.getId());
            kwpLedgerTradeOrder.setTOrderId(a.getId());
            kwpLedgerTradeOrder.setTOrderNo(a.getTOrderNo());
            kwpLedgerTradeOrder.setRemark(Global.EMPTY_STRING);
            kwpLedgerTradeOrder.setStatus(NumberConstant.ZERO);
            kwpLedgerTradeOrder.setCreateBy(LoginUserHolder.getUserId());
            kwpLedgerTradeOrder.setCreateTime(LocalDateTime.now());
            kwpLedgerTradeOrder.setUpdateBy(LoginUserHolder.getUserId());
            kwpLedgerTradeOrder.setUpdateTime(LocalDateTime.now());
            kwpLedgerTradeOrder.setDelFlag(Global.UN_DELETED);
            return kwpLedgerTradeOrder;
        }).collect(Collectors.toList());
        tradeOrderService.saveList(collect);
        /*保存企业单位相关信息*/
        // dubbo拿取采购客户单位的信息
        Long purchaseEntId = Long.parseLong(tradeSendReq.getPurchaseEntId());
        Map<Long, EntCacheResDto> entMap = remoteSystemService.queryEntTreeByIds(Collections.singletonList(purchaseEntId));
        EntCacheResDto entCacheResDto = entMap.get(purchaseEntId);
        if (Objects.isNull(entCacheResDto)) {
            entCacheResDto = new EntCacheResDto();
        }
        //保存双方企业信息
        List<KwpLedgerTradeUnit> list = new ArrayList<>();
        KwpLedgerTradeUnit kwpLedgerTradeUnit = new KwpLedgerTradeUnit();
        kwpLedgerTradeUnit.setId(new IdWorker(NumberConstant.ONE).nextId());
        kwpLedgerTradeUnit.setTLedgerId(kwpLedgerTrade.getId());
        kwpLedgerTradeUnit.setTLedgerNo(kwpLedgerTrade.getTLedgerNo());
        kwpLedgerTradeUnit.setUnitType(TradeUnitType.PURCHASE);
        kwpLedgerTradeUnit.setEntId(purchaseEntId);
        kwpLedgerTradeUnit.setTopEntId(entCacheResDto.getId());
        kwpLedgerTradeUnit.setFirmName(entCacheResDto.getFirmName());
        kwpLedgerTradeUnit.setContacts(entCacheResDto.getContacts());
        kwpLedgerTradeUnit.setContactsId(entCacheResDto.getContactsId());
        kwpLedgerTradeUnit.setPhone(entCacheResDto.getPhone());
        kwpLedgerTradeUnit.setRemark(Global.EMPTY_STRING);
        kwpLedgerTradeUnit.setStatus(NumberConstant.ZERO);
        kwpLedgerTradeUnit.setCreateBy(LoginUserHolder.getUserId());
        kwpLedgerTradeUnit.setCreateTime(LocalDateTime.now());
        kwpLedgerTradeUnit.setUpdateBy(LoginUserHolder.getUserId());
        kwpLedgerTradeUnit.setUpdateTime(LocalDateTime.now());
        kwpLedgerTradeUnit.setDelFlag(Global.UN_DELETED);

        list.add(kwpLedgerTradeUnit);
        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();
        }
        //非客户企业方，通过登录用户获取顶级企业
        KwpLedgerTradeUnit sellLedgerTradeUnit = new KwpLedgerTradeUnit();
        sellLedgerTradeUnit.setId(new IdWorker(NumberConstant.ONE).nextId());
        sellLedgerTradeUnit.setTLedgerId(kwpLedgerTrade.getId());
        sellLedgerTradeUnit.setTLedgerNo(kwpLedgerTrade.getTLedgerNo());
        sellLedgerTradeUnit.setUnitType(TradeUnitType.SELL);
        sellLedgerTradeUnit.setEntId(entId);
        sellLedgerTradeUnit.setTopEntId(entCacheResDto1.getId());
        sellLedgerTradeUnit.setFirmName(entCacheResDto1.getFirmName());
        sellLedgerTradeUnit.setContacts(entCacheResDto1.getContacts());
        sellLedgerTradeUnit.setContactsId(entCacheResDto1.getContactsId());
        sellLedgerTradeUnit.setPhone(entCacheResDto1.getPhone());
        sellLedgerTradeUnit.setRemark(Global.EMPTY_STRING);
        sellLedgerTradeUnit.setStatus(NumberConstant.ZERO);
        sellLedgerTradeUnit.setCreateBy(LoginUserHolder.getUserId());
        sellLedgerTradeUnit.setCreateTime(LocalDateTime.now());
        sellLedgerTradeUnit.setUpdateBy(LoginUserHolder.getUserId());
        sellLedgerTradeUnit.setUpdateTime(LocalDateTime.now());
        sellLedgerTradeUnit.setDelFlag(Global.UN_DELETED);
        list.add(sellLedgerTradeUnit);

        tradeUnitService.saveList(list);
        return new IdNo(kwpLedgerTrade.getId(), kwpLedgerTrade.getTLedgerNo());
    }

    /**
     * 保存对账单
     *
     * @param tradeSendReq
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String sendLedger(TradeSendReq tradeSendReq) {
        log.info("保存对账单入参：{}", JSONObject.toJSONString(tradeSendReq));
        if (Objects.nonNull(tradeSendReq.getIdLong())) {
            //先删除
            removeDraft(tradeSendReq.getIdLong());
        }
        tradeSendReq.setGenerateTime(LocalDateTime.now());
        tradeSendReq.setStatus(LedgerEnum.TO_LEDGER.getStatus());
        IdNo idNo = saveDraft(tradeSendReq);
        tradeTrackService.saveTrack(idNo.id(), Global.EMPTY_STRING, LedgerEnum.TO_LEDGER);

        //推送消息
        KwpLedgerTradeUnit kwpLedgerTradeUnit = tradeUnitService.queryCustomerEnt(idNo.id(), TradeUnitType.PURCHASE);
        //推送创建人
        messageSender.sendCreate(LoginUserHolder.getUserId(), new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
            put("company", kwpLedgerTradeUnit.getFirmName());
            put("number", idNo.no());
            put("name", tradeSendReq.getName());
        }}, new UserInfo().setUserId(LoginUserHolder.getUserId()).setEntId(LoginUserHolder.getEntId()), MessageEnum.LEDGER_SELL);

        //推送系统管理员
        KwpLedgerTradeUnit kwpLedgerTradeUnit2 = tradeUnitService.queryCustomerEnt(idNo.id(), TradeUnitType.SELL);
        messageSender.sendManager(LoginUserHolder.getUserId(), new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
            put("company", kwpLedgerTradeUnit2.getFirmName());
            put("number", idNo.no());
            put("name", tradeSendReq.getName());
        }}, kwpLedgerTradeUnit.getEntId(), MessageEnum.LEDGER_PURCHASE);
        return "保存对账单成功";
    }

    /**
     * 保存草稿
     *
     * @param tradeSendReq
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String sendLedgerDraft(TradeSendReq tradeSendReq) {
        log.info("贸易对账单保存草稿：{}", JSONObject.toJSONString(tradeSendReq));
        tradeSendReq.setGenerateTime(null);
        tradeSendReq.setStatus(LedgerEnum.SAVE.getStatus());
        IdNo idNo = saveDraft(tradeSendReq);
        tradeTrackService.saveTrack(idNo.id(), Global.EMPTY_STRING, LedgerEnum.SAVE);
        return "草稿保存成功";
    }

    /**
     * 删除对账单
     *
     * @param id 对账单id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String remove(Long id) {
        log.info("删除贸易对账单：{}", id);
        KwpLedgerTrade kwpLedgerTrade = tradeMapper.selectById(id);
        orderCheck(kwpLedgerTrade);
        deleteCheck(kwpLedgerTrade.getStatus());

        List<KwpLedgerTradeOrder> kwpLedgerTradeOrders = tradeOrderService.queryList(id);
        if (CollectionUtils.isEmpty(kwpLedgerTradeOrders)) {
            throw new BusinessException("未找到关联订单！");
        }
        kwpLedgerTrade.setDelFlag(Global.DELETED);
        kwpLedgerTrade.setUpdateBy(LoginUserHolder.getUserId());
        kwpLedgerTrade.setUpdateTime(LocalDateTime.now());
        tradeMapper.updateById(kwpLedgerTrade);
        tradeOrderService.remove(id);
        //更新贸易订单状态为未绑定对账单
        for (KwpLedgerTradeOrder kwpLedgerTradeOrder : kwpLedgerTradeOrders) {
            UpdateAssociateStatementParam updateAssociateStatementParam = new UpdateAssociateStatementParam();
            updateAssociateStatementParam.setTOrderId(kwpLedgerTradeOrder.getTOrderId());
            updateAssociateStatementParam.setAssociateStatement(0);
            updateAssociateStatementParam.setUpdateBy(LoginUserHolder.getUserId());
            updateAssociateStatementParam.setUpdateByName(LoginUserHolder.getUserName());
            tradeOrderInfoService.updateAssociateStatement(updateAssociateStatementParam);
        }
        return "删除成功";
    }

    /**
     * 撤回对账单
     *
     * @param id 对账单id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String backOrder(Long id) {
        log.info("撤回贸易对账单：{}", id);
        KwpLedgerTrade kwpLedgerTrade = tradeMapper.selectById(id);
        orderCheck(kwpLedgerTrade);
        revokeCheck(kwpLedgerTrade.getStatus());
        kwpLedgerTrade.setStatus(LedgerEnum.REVOCATION.getStatus());
        kwpLedgerTrade.setUpdateBy(LoginUserHolder.getUserId());
        kwpLedgerTrade.setUpdateTime(LocalDateTime.now());
        tradeMapper.updateById(kwpLedgerTrade);

        tradeTrackService.saveTrack(id, Global.EMPTY_STRING, LedgerEnum.REVOCATION);
        //推送消息
        KwpLedgerTradeUnit kwpLedgerTradeUnit = tradeUnitService.queryCustomerEnt(id, TradeUnitType.PURCHASE);
        //推送创建人
        messageSender.sendCreate(LoginUserHolder.getUserId(), new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
            put("company", kwpLedgerTradeUnit.getFirmName());
            put("number", kwpLedgerTrade.getTLedgerNo());
            put("name", kwpLedgerTrade.getName());
        }}, new UserInfo().setUserId(kwpLedgerTrade.getCreateBy()).setEntId(kwpLedgerTrade.getEntId()), MessageEnum.LEDGER_REVOCATION_SELL);

        //推送系统管理员
        KwpLedgerTradeUnit kwpLedgerTradeUnit2 = tradeUnitService.queryCustomerEnt(id, TradeUnitType.SELL);
        messageSender.sendManager(LoginUserHolder.getUserId(), new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
            put("company", kwpLedgerTradeUnit2.getFirmName());
            put("number", kwpLedgerTrade.getTLedgerNo());
            put("name", kwpLedgerTrade.getName());
        }}, kwpLedgerTradeUnit.getEntId(), MessageEnum.LEDGER_REVOCATION_PURCHASE);
        return "撤回成功";
    }

    /**
     * 查询贸易对账单驳回记录
     *
     * @param id 对账单id
     * @return
     */
    public KwpLedgerTradeTrack queryBack(Long id) {
        KwpLedgerTrade kwpLedgerTrade = tradeMapper.selectById(id);
        orderCheck(kwpLedgerTrade);
        backQueryCheck(kwpLedgerTrade.getStatus());
        return tradeTrackService.selectOne(id, LedgerEnum.BACK);
    }

    /**
     * 驳回贸易对账单
     *
     * @param ledgerReq
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String doBack(LedgerReq ledgerReq) {
        log.info("驳回贸易对账单：{}", JSONObject.toJSONString(ledgerReq));
        KwpLedgerTrade kwpLedgerTrade = tradeMapper.selectById(ledgerReq.getIdLong());
        orderCheck(kwpLedgerTrade);
        backCheck(kwpLedgerTrade.getStatus());
        kwpLedgerTrade.setStatus(LedgerEnum.BACK.getStatus());
        kwpLedgerTrade.setUpdateBy(LoginUserHolder.getUserId());
        kwpLedgerTrade.setUpdateTime(LocalDateTime.now());
        tradeMapper.updateById(kwpLedgerTrade);
        tradeTrackService.saveTrack(ledgerReq.getIdLong(), ledgerReq.getRemark(), LedgerEnum.BACK);

        //推送消息
        KwpLedgerTradeUnit kwpLedgerTradeUnit = tradeUnitService.queryCustomerEnt(ledgerReq.getIdLong(), TradeUnitType.PURCHASE);
        //推送创建人
        messageSender.sendCreate(LoginUserHolder.getUserId(), new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
            put("company", kwpLedgerTradeUnit.getFirmName());
            put("number", kwpLedgerTrade.getTLedgerNo());
            put("name", kwpLedgerTrade.getName());
        }}, new UserInfo().setUserId(kwpLedgerTrade.getCreateBy()).setEntId(kwpLedgerTrade.getEntId()), MessageEnum.LEDGER_BACK_SELL);

        //推送系统管理员和变更人
        KwpLedgerTradeUnit kwpLedgerTradeUnit2 = tradeUnitService.queryCustomerEnt(ledgerReq.getIdLong(), TradeUnitType.SELL);
        messageSender.sendSellBoth(LoginUserHolder.getUserId(), new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
            put("company", kwpLedgerTradeUnit2.getFirmName());
            put("number", kwpLedgerTrade.getTLedgerNo());
            put("name", kwpLedgerTrade.getName());
        }}, ledgerReq.getIdLong(), kwpLedgerTradeUnit.getEntId(), MessageEnum.LEDGER_BACK_PURCHASE);
        return "驳回成功";
    }

    /**
     * 对账确认
     *
     * @param confirmReq 对账确认参数
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String confirmOrder(LedgerConfirmReq confirmReq) {
        log.info("贸易对账单对账确认：{}", JSONObject.toJSONString(confirmReq));
        KwpLedgerTrade kwpLedgerTrade = tradeMapper.selectById(confirmReq.getIdLong());
        orderCheck(kwpLedgerTrade);
        confirmCheck(kwpLedgerTrade.getStatus());
        kwpLedgerTrade.setStatus(LedgerEnum.LEDGERED.getStatus());
        kwpLedgerTrade.setAuditPhone(confirmReq.getAuditPhone());
        kwpLedgerTrade.setAuditUser(confirmReq.getAuditUser());
        kwpLedgerTrade.setAuditUserId(confirmReq.getAuditUserId());
        kwpLedgerTrade.setUrl(confirmReq.getUrl());
        kwpLedgerTrade.setUpdateBy(LoginUserHolder.getUserId());
        kwpLedgerTrade.setUpdateTime(LocalDateTime.now());
        tradeMapper.updateById(kwpLedgerTrade);
        tradeTrackService.saveTrack(confirmReq.getIdLong(), Global.EMPTY_STRING, LedgerEnum.LEDGERED);

        //推送消息
        KwpLedgerTradeUnit kwpLedgerTradeUnit = tradeUnitService.queryCustomerEnt(confirmReq.getIdLong(), TradeUnitType.PURCHASE);
        //推送创建人
        messageSender.sendCreate(LoginUserHolder.getUserId(), new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
            put("company", kwpLedgerTradeUnit.getFirmName());
            put("number", kwpLedgerTrade.getTLedgerNo());
            put("name", kwpLedgerTrade.getName());
        }}, new UserInfo().setUserId(kwpLedgerTrade.getCreateBy()).setEntId(kwpLedgerTrade.getEntId()), MessageEnum.LEDGER_CONFIRM_SELL);

        //推送系统管理员和变更人
        KwpLedgerTradeUnit kwpLedgerTradeUnit2 = tradeUnitService.queryCustomerEnt(confirmReq.getIdLong(), TradeUnitType.SELL);
        messageSender.sendSellBoth(LoginUserHolder.getUserId(), new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
            put("company", kwpLedgerTradeUnit2.getFirmName());
            put("number", kwpLedgerTrade.getTLedgerNo());
            put("name", kwpLedgerTrade.getName());
        }}, confirmReq.getIdLong(), kwpLedgerTradeUnit.getEntId(), MessageEnum.LEDGER_CONFIRM_PURCHASE);
        return "对账确认成功";
    }

    /**
     * 对账完成
     *
     * @param ledgerReq 对账完成参数
     * @return
     */
    @GlobalTransactional(name = "default_tx_group", rollbackFor = Exception.class)
    public String orderSuccess(LedgerSuccessReq ledgerReq) {
        log.info("贸易对账单对账完成：{}", JSONObject.toJSONString(ledgerReq));
        Long id = ledgerReq.getIdLong();
        //校验对账单状态
        KwpLedgerTrade kwpLedgerTrade = tradeMapper.selectById(id);
        orderCheck(kwpLedgerTrade);
        successCheck(kwpLedgerTrade.getStatus());
        //查询对账单关联的订单
        List<KwpLedgerTradeOrder> kwpLedgerTradeOrders = tradeOrderService.queryList(id);
        if (CollectionUtils.isEmpty(kwpLedgerTradeOrders)) {
            throw new BusinessException("未找到关联的贸易订单");
        }
        //更新对账单
        LocalDateTime receiptTime = null;
        if (Objects.nonNull(ledgerReq.getReceiptTime())) {
            receiptTime = LocalDateTime.of(ledgerReq.getReceiptTime(), LocalTime.MIN);
            kwpLedgerTrade.setReceiptTime(receiptTime);
        }
        kwpLedgerTrade.setSuccessPhone(ledgerReq.getSuccessPhone());
        kwpLedgerTrade.setSuccessUser(ledgerReq.getSuccessUser());
        kwpLedgerTrade.setSuccessUserId(ledgerReq.getSuccessUserId());
        kwpLedgerTrade.setStatus(LedgerEnum.SUCCESS.getStatus());
        kwpLedgerTrade.setUpdateTime(LocalDateTime.now());
        tradeMapper.updateById(kwpLedgerTrade);
        //生成结算单
        KwpSettlementTrade kwpSettlementTrade = new KwpSettlementTrade();
        kwpSettlementTrade.setId(new IdWorker(NumberConstant.ONE).nextId());
        kwpSettlementTrade.setEntId(LoginUserHolder.getEntId());
        kwpSettlementTrade.setTLedgerId(kwpLedgerTrade.getId());
        kwpSettlementTrade.setStOrderNo(OrderGenerateSeqNoUtils.getOtherSeqNo(RedisOrderGenerateEnum.LEDGER_CHECKING, OrderRuleEnum.SETTLEMENT_TRADE_ORDER));
        kwpSettlementTrade.setName(kwpLedgerTrade.getName());
        kwpSettlementTrade.setTotalPrice(kwpLedgerTrade.getSettlePrice());
        kwpSettlementTrade.setActualPrice(kwpLedgerTrade.getActualPrice());
        kwpSettlementTrade.setRemark(Global.EMPTY_STRING);
        kwpSettlementTrade.setTrading(kwpLedgerTrade.getTrading());
        kwpSettlementTrade.setAuditUserId(kwpLedgerTrade.getAuditUserId());
        kwpSettlementTrade.setAuditUser(kwpLedgerTrade.getAuditUser());
        kwpSettlementTrade.setAuditPhone(kwpLedgerTrade.getAuditPhone());
        kwpSettlementTrade.setSuccessUserId(ledgerReq.getSuccessUserId());
        kwpSettlementTrade.setSuccessUser(ledgerReq.getSuccessUser());
        kwpSettlementTrade.setSuccessPhone(ledgerReq.getSuccessPhone());
        kwpSettlementTrade.setReceiptTime(receiptTime);
        //1-待结算
        kwpSettlementTrade.setStatus(SettlementEnum.WAITING_PAYMENT.getStatus());
        kwpSettlementTrade.setCreateBy(LoginUserHolder.getUserId());
        kwpSettlementTrade.setCreateTime(LocalDateTime.now());
        kwpSettlementTrade.setUpdateBy(LoginUserHolder.getUserId());
        kwpSettlementTrade.setUpdateTime(LocalDateTime.now());
        kwpSettlementTrade.setDelFlag(Global.UN_DELETED);
        kwpSettlementTradeService.save(kwpSettlementTrade);

        //更新贸易订单状态
        List<Long> list = kwpLedgerTradeOrders.stream().map(KwpLedgerTradeOrder::getTOrderId).toList();
        for (Long aLong : list) {
            UpdateOrderStatusParam updateOrderStatusParam = new UpdateOrderStatusParam();
            updateOrderStatusParam.setTOrderId(aLong);
            updateOrderStatusParam.setStatus(Integer.valueOf(DictEnum.TORDER_STATUS_6.getValue()));
            updateOrderStatusParam.setUpdateBy(LoginUserHolder.getUserId());
            updateOrderStatusParam.setUpdateByName(LoginUserHolder.getUserName());
            tradeOrderInfoService.updateOrderStatus(updateOrderStatusParam);
        }
        //保存操作记录
        tradeTrackService.saveTrack(id, Global.EMPTY_STRING, LedgerEnum.SUCCESS);


        //推送消息
        KwpLedgerTradeUnit kwpLedgerTradeUnit = tradeUnitService.queryCustomerEnt(ledgerReq.getIdLong(), TradeUnitType.PURCHASE);
        //推送创建人
        messageSender.sendCreate(LoginUserHolder.getUserId(), new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
            put("company", kwpLedgerTradeUnit.getFirmName());
            put("number", kwpLedgerTrade.getTLedgerNo());
            put("name", kwpLedgerTrade.getName());
        }}, new UserInfo().setUserId(kwpLedgerTrade.getCreateBy()).setEntId(kwpLedgerTrade.getEntId()), MessageEnum.LEDGER_SUCCESS_SELL);

        //推送系统管理员和变更人
        KwpLedgerTradeUnit kwpLedgerTradeUnit2 = tradeUnitService.queryCustomerEnt(ledgerReq.getIdLong(), TradeUnitType.SELL);
        messageSender.sendSellBoth(LoginUserHolder.getUserId(), new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
            put("company", kwpLedgerTradeUnit2.getFirmName());
            put("number", kwpLedgerTrade.getTLedgerNo());
            put("name", kwpLedgerTrade.getName());
        }}, ledgerReq.getIdLong(), kwpLedgerTradeUnit.getEntId(), MessageEnum.LEDGER_SUCCESS_PURCHASE);

        //推送双方系统管理员
        messageSender.sendManager(LoginUserHolder.getUserId(), new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
            put("company", kwpLedgerTradeUnit.getFirmName());
            put("number", kwpSettlementTrade.getStOrderNo());
        }}, kwpLedgerTradeUnit2.getEntId(), MessageEnum.SETTLEMENT_SELL);
        messageSender.sendManager(LoginUserHolder.getUserId(), new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
            put("company", kwpLedgerTradeUnit2.getFirmName());
            put("number", kwpSettlementTrade.getStOrderNo());
        }}, kwpLedgerTradeUnit.getEntId(), MessageEnum.SETTLEMENT_PURCHASE);

        return "对账完成";
    }

    /**
     * 按分类统计对账单表头数量
     *
     * @param tradeReq 查询参数
     * @return
     */
    public List<TableTop> orderCount(TradeReq tradeReq) {
        tradeReq.setEntId(LoginUserHolder.getEntId());
        Map<String, Long> map;
        List<Long> authUserIdList = LoginUserHolder.getAuthUserIdList();
        if (Objects.equals(tradeReq.getUnitTypeTwo(), TradeUnitType.SELL)) {
            map = tradeMapper.countSellOrder(tradeReq, authUserIdList);
        } else {
            map = tradeMapper.countPurchaseOrder(tradeReq, authUserIdList);
        }
        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;
    }

    /**
     * 根据id查询对账单列表
     *
     * @param ids 对账单id列表
     * @return 对账单数据
     */
    public List<LedgerSellDto> selectSellList(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return new ArrayList<>();
        }
        List<LedgerSellDto> ledgerTradeDto = tradeMapper.selectSellIds(ids);
        changeDict(ledgerTradeDto);
        return ledgerTradeDto;
    }

    /**
     * 根据id查询对账单列表
     *
     * @param ids 对账单id列表
     * @return 对账单数据
     */
    public List<LedgerPurchaseDto> selectPurchaseList(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return new ArrayList<>();
        }
        List<LedgerPurchaseDto> ledgerTradeDto = tradeMapper.selectPurchaseIds(ids);
        changeDict(ledgerTradeDto);
        return ledgerTradeDto;
    }

    /**
     * 更新对账单查询
     *
     * @param id 对账单id
     * @return 对账单详情数据
     */
    public LedgerTradeDetailVo queryUpdate(Long id) {
        LedgerTradeDto ledgerTradeDto = tradeMapper.selectId(id, TradeUnitType.PURCHASE);
        orderCheck(ledgerTradeDto);
        updateCheck(ledgerTradeDto.getStatus());
        //查询对账单关联的订单
        return getDetail(ledgerTradeDto);
    }

    private LedgerTradeDetailVo getDetail(LedgerTradeDto ledgerTradeDto) {
        List<KwpLedgerTradeOrder> kwpLedgerTradeOrders = tradeOrderService.queryList(ledgerTradeDto.getId());
        LedgerTradeDetailVo ledgerTradeDetailVo = new LedgerTradeDetailVo();
        ledgerTradeDetailVo.setId(ledgerTradeDto.getId());
        ledgerTradeDetailVo.setPurchaseEntId(ledgerTradeDto.getPurchaseEntId());
        ledgerTradeDetailVo.setTLedgerNo(ledgerTradeDto.getTLedgerNo());
        ledgerTradeDetailVo.setName(ledgerTradeDto.getName());
        ledgerTradeDetailVo.setFirmName(ledgerTradeDto.getFirmName());
        SysDictResDto trading = remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.TRADE_TYPE.getType(), ledgerTradeDto.getTrading());
        ledgerTradeDetailVo.setTrading(ledgerTradeDto.getTrading());
        ledgerTradeDetailVo.setTradingLabel(Objects.nonNull(trading) ? trading.getLabel() : "");
        SysDictResDto taxRate = remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.TAX_RATE.getType(), String.valueOf(ledgerTradeDto.getTaxRate()));
        ledgerTradeDetailVo.setTaxRate(ledgerTradeDto.getTaxRate());
        ledgerTradeDetailVo.setTaxRateLabel(Objects.nonNull(taxRate) ? taxRate.getLabel() : "");
        ledgerTradeDetailVo.setTotalPrice(ledgerTradeDto.getTotalPrice());
        ledgerTradeDetailVo.setSettlePrice(ledgerTradeDto.getSettlePrice());
        ledgerTradeDetailVo.setActualPrice(ledgerTradeDto.getActualPrice());
        ledgerTradeDetailVo.setDeductPrice(ledgerTradeDto.getDeductPrice());
        ledgerTradeDetailVo.setStartTime(ledgerTradeDto.getStartTime());
        ledgerTradeDetailVo.setEndTime(ledgerTradeDto.getEndTime());
        ledgerTradeDetailVo.setRemark(ledgerTradeDto.getRemark());
        List<Long> collect = kwpLedgerTradeOrders.stream().map(KwpLedgerTradeOrder::getTOrderId).toList();
        List<OrderDto> detailRes = new ArrayList<>();
        OrderDetailRes orderDetailById;
        //查询贸易订单详情
        for (Long aLong : collect) {
            orderDetailById = tradeOrderInfoService.getOrderDetailById(aLong);
            detailRes.add(changeOrder(orderDetailById));
        }
        ledgerTradeDetailVo.setOrderList(detailRes);
        return ledgerTradeDetailVo;
    }

    private OrderDto changeOrder(OrderDetailRes orderDetailRes) {
        OrderDto orderDto = new OrderDto();
        BeanUtils.copyProperties(orderDetailRes, orderDto);
        List<UnitInfoDetailRes> unitInfo = orderDetailRes.getUnitInfo();
        if (!CollectionUtils.isEmpty(unitInfo)) {
            for (UnitInfoDetailRes unitInfoDetailRes : unitInfo) {
                //2-销售
                if (StringUtils.equals(unitInfoDetailRes.getUnitType(), "2")) {
                    orderDto.setSupplyEntId(unitInfoDetailRes.getEntId());
                    orderDto.setSupplyFirmName(unitInfoDetailRes.getFirmName());
                }
                //1-采购
                if (StringUtils.equals(unitInfoDetailRes.getUnitType(), "1")) {
                    orderDto.setProcureEntId(unitInfoDetailRes.getEntId());
                    //采购企业名称
                    orderDto.setProcureFirmName(unitInfoDetailRes.getFirmName());
                }
            }
        }
        ContractInfo contractInfo = orderDetailRes.getContractInfo();
        if (Objects.nonNull(contractInfo)) {
            orderDto.setContractId(contractInfo.getContractId());
            orderDto.setContractNo(contractInfo.getContractNo());
            orderDto.setContractName(contractInfo.getContractName());
            orderDto.setContractSigningWay(contractInfo.getContractSigningWay());
        }
        GoodsInfoDetailRes goodsInfo = orderDetailRes.getGoodsInfo();
        if (Objects.nonNull(goodsInfo)) {
            orderDto.setGoodsId(goodsInfo.getGoodsId());
            orderDto.setGoodsSpec(goodsInfo.getSpec());
            orderDto.setGoodsName(goodsInfo.getName());
            orderDto.setGoodsType(goodsInfo.getGoodsType());
            orderDto.setGoodsTypeLabel(goodsInfo.getGoodsTypeLabel());
            orderDto.setUnit(goodsInfo.getUnit());
            orderDto.setUnitLabel(goodsInfo.getUnitLabel());
            orderDto.setUnitPrice(goodsInfo.getUnitPrice());
            orderDto.setGoodsAmount(goodsInfo.getGoodsAmount());
            orderDto.setTaxRate(goodsInfo.getTaxRate());
            orderDto.setTaxRateLabel(goodsInfo.getTaxRateLabel());
        }
        List<AddressInfoDetail> addressInfo = orderDetailRes.getAddressInfo();
        if (!CollectionUtils.isEmpty(addressInfo)) {
            for (AddressInfoDetail addressInfoDetail : addressInfo) {
                if (StringUtils.equals(addressInfoDetail.getAddressType(), "1")) {
                    orderDto.setLoadName(addressInfoDetail.getName());
                    orderDto.setLoadDetailAddressInfo(addressInfoDetail.getDetailAddress());
                }
                if (StringUtils.equals(addressInfoDetail.getAddressType(), "2")) {
                    orderDto.setUnloadName(addressInfoDetail.getName());
                    orderDto.setUnloadDetailAddressInfo(addressInfoDetail.getDetailAddress());
                }
            }
        }
        orderDto.setTOrderId(orderDetailRes.getId());
        return orderDto;
    }

    /**
     * 查询对账单详情
     *
     * @param id       对账单id
     * @param unitType 企业单位类型
     * @return 对账单详情
     */
    public LedgerTradeDetailVo queryDetail(Long id, Integer unitType) {
        LedgerTradeDto ledgerTradeDto = tradeMapper.selectId(id, unitType);
        orderCheck(ledgerTradeDto);
        //查询对账单关联的贸易订单
        LedgerTradeDetailVo detail = getDetail(ledgerTradeDto);
        //1-采购(销售方查询数据，展示)
        if (unitType == 1) {
            detail.setUser(ledgerTradeDto.getAuditUser());
            detail.setPhone(ledgerTradeDto.getAuditPhone());
        } else {
            detail.setUser(ledgerTradeDto.getSuccessUser());
            detail.setPhone(ledgerTradeDto.getSuccessPhone());
        }
        return detail;
    }

    public PageRes<OrderDto> orderList(LedgerListReq ledgerListReq) {
        PageHelper.startPage(ledgerListReq.getPage(), ledgerListReq.getPageSize());
        List<KwpLedgerTradeOrder> kwpLedgerLogisticsOrders = tradeOrderService.queryList(ledgerListReq.getIdLong());
        if (CollectionUtils.isEmpty(kwpLedgerLogisticsOrders)) {
            return new PageRes<>();
        }
        PageInfo<KwpLedgerTradeOrder> pageInfo = new PageInfo<>(kwpLedgerLogisticsOrders);
        List<OrderDto> detailRes = new ArrayList<>();
        for (KwpLedgerTradeOrder kwpLedgerLogisticsOrder : kwpLedgerLogisticsOrders) {
            OrderDetailRes orderDetailById = tradeOrderInfoService.getOrderDetailById(kwpLedgerLogisticsOrder.getTOrderId());
            log.info("销售订单：{}", JSONObject.toJSONString(orderDetailById));
            detailRes.add(changeOrder(orderDetailById));
        }
        return PageRes.build(pageInfo, detailRes);
    }

    /**
     * 查询对账单关联订单 可通过商品名称、订单编号搜索
     *
     * @param ledgerListReq
     * @return
     */
    public List<OrderDto> queryOrderList(LedgerListReq ledgerListReq) {
        List<KwpLedgerTradeOrder> kwpLedgerLogisticsOrders = tradeOrderService.queryList(ledgerListReq.getIdLong());
        if (CollectionUtils.isEmpty(kwpLedgerLogisticsOrders)) {
            return new ArrayList<>();
        }
        List<OrderDto> detailRes = new ArrayList<>();
        for (KwpLedgerTradeOrder kwpLedgerLogisticsOrder : kwpLedgerLogisticsOrders) {
            OrderDetailRes orderDetailById = tradeOrderInfoService.getOrderDetailById(kwpLedgerLogisticsOrder.getTOrderId());
            detailRes.add(changeOrder(orderDetailById));
        }
        //过滤筛选条件
        if (StringUtils.isNotBlank(ledgerListReq.getKeywords())) {
            return detailRes.stream().filter(o -> StringUtils.contains(o.getTOrderNo(), ledgerListReq.getKeywords()) || StringUtils.contains(o.getGoodsName(), ledgerListReq.getKeywords())).toList();
        }
        return detailRes;
    }

    /**
     * 根据企业id查询关联的订单
     *
     * @param entId 采购单位
     * @return
     */
    public List<String> checkOrder(Long entId, Long entTarget) {
        return tradeMapper.selectJoin(entId, entTarget);
    }

    /**
     * 更新对账单已收款金额字段 累加更新
     *
     * @param id         对账单id
     * @param totalPrice 已收款金额
     */
    public void updateActualPrice(Long id, BigDecimal totalPrice) {
        tradeMapper.updatePrice(id, totalPrice);
    }

    public LedgerSize count(Long entId,List<Long> enterpriseIds) {
        enterpriseIds=enterpriseIds.stream().distinct().collect(Collectors.toList());
        return tradeMapper.countSize(entId,enterpriseIds);
    }

    public List<LedgerTradeDto> exportList(TradeReq tradeReq, List<Long> idList) {
        fillPara(tradeReq);
        List<LedgerTradeDto> ledgerTradeDtos = tradeMapper.exportList(tradeReq, idList, LoginUserHolder.getAuthUserIdList());
        changeDict(ledgerTradeDtos);
        return ledgerTradeDtos;
    }
}
