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.DictEnum;
import com.sckw.core.exception.BusinessException;
import com.sckw.core.model.constant.Global;
import com.sckw.core.model.page.PageRes;
import com.sckw.core.utils.IdWorker;
import com.sckw.core.utils.StringUtils;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.order.api.dubbo.TradeOrderInfoService;
import com.sckw.order.api.model.UpdateOrderStatusParam;
import com.sckw.payment.api.model.constant.ChannelEnum;
import com.sckw.payment.api.model.dto.WalletDto;
import com.sckw.payment.api.model.dto.common.R;
import com.sckw.payment.dao.KwpSettlementLogisticsMapper;
import com.sckw.payment.dao.KwpSettlementLogisticsTrackMapper;
import com.sckw.payment.dao.KwpSettlementWalletMapper;
import com.sckw.payment.model.*;
import com.sckw.payment.model.constant.*;
import com.sckw.payment.model.dto.LedgerUnitDto;
import com.sckw.payment.model.dto.SettlementLogisticsDto;
import com.sckw.payment.model.dto.SettlementTradeDto;
import com.sckw.payment.model.dto.SettlementWalletDto;
import com.sckw.payment.model.vo.req.OfflinePaymentReq;
import com.sckw.payment.model.vo.req.SettlementWalletReq;
import com.sckw.payment.model.vo.req.WalletPayReq;
import com.sckw.payment.model.vo.res.SettlementWalletVo;
import com.sckw.redis.config.RedisLockUtil;
import com.sckw.redis.constant.RedisConstant;
import com.sckw.system.api.RemoteSystemService;
import com.sckw.system.api.model.dto.res.UserCacheResDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Aick Spt
 * @date 2023-07-20 14:55
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class KwpSettlementWalletService {
    private final KwpSettlementWalletMapper settlementWalletMapper;
    private final KwpSettlementLogisticsMapper kwpSettlementLogisticsMapper;
    private final KwpLedgerTradeOrderService tradeOrderService;
    private final KwpSettlementLogisticsService kwpSettlementLogisticsService;
    private final KwpSettlementTradeService kwpSettlementTradeService;
    private final PayCenterService payCenterService;
    private final KwpWalletRelationService walletRelationService;
    private final RedisLockUtil redisLockUtil;
    private final KwpSettlementTradeTrackService settlementTradeTrackService;
    @DubboReference(version = "2.0.0", group = "design", check = false)
    private RemoteSystemService remoteSystemService;
    @DubboReference(version = "2.0.0", group = "design", check = false)
    private TradeOrderInfoService tradeOrderInfoService;
    private final KwpSettlementLogisticsTrackMapper kwpSettlementLogisticsTrackMapper;

    /**
     * 物流-电子钱包付款（货到付款）结算记录-列表
     *
     * @author Aick Spt
     * @date 2023-07-26 16:43
     */
    public PageRes<SettlementWalletVo> pageListLogisticsPayment(SettlementWalletReq settlementWalletReq) {
        settlementWalletReq.setPayType(SettlementPayTypeEnum.CASH_ON_DELIVERY.getStatus());//只筛选 货到付款
        PageHelper.startPage(settlementWalletReq.getPage(), settlementWalletReq.getPageSize());
        List<SettlementWalletDto> settlementWalletLogisticsList = settlementWalletMapper.pageListLogisticsPayment(settlementWalletReq);
        PageInfo<SettlementWalletDto> pageInfo = new PageInfo<>(settlementWalletLogisticsList);
        if (CollectionUtils.isEmpty(settlementWalletLogisticsList)) {
            return new PageRes<>();
        }
        //增加对应创建人和更新人名称
        for (SettlementWalletDto entity : settlementWalletLogisticsList) {
            entity.setCreateByText("创建人名称");
            entity.setUpdateByText("更新人名称");
        }

        Map<Long, UserCacheResDto> map = new HashMap<>();
        //指定返回值
        List<SettlementWalletVo> collect = settlementWalletLogisticsList.stream().map(a -> {
            SettlementWalletVo settlementWalletVo = new SettlementWalletVo();
            BeanUtils.copyProperties(a, settlementWalletVo);
            Long createBy = a.getCreateBy();
            Long updateBy = a.getUpdateBy();
            UserCacheResDto userCacheResDto = map.get(createBy);
            if (Objects.isNull(userCacheResDto)) {
                userCacheResDto = remoteSystemService.queryUserCacheById(createBy);
                map.put(createBy, userCacheResDto);
            }
            if (Objects.nonNull(userCacheResDto)) {
                settlementWalletVo.setCreateByText(userCacheResDto.getName());
            }
            userCacheResDto = map.get(updateBy);
            if (Objects.isNull(userCacheResDto)) {
                userCacheResDto = remoteSystemService.queryUserCacheById(updateBy);
                map.put(updateBy, userCacheResDto);
            }
            if (Objects.nonNull(userCacheResDto)) {
                settlementWalletVo.setUpdateByText(userCacheResDto.getName());
            }
            return settlementWalletVo;
        }).collect(Collectors.toList());

        return PageRes.build(pageInfo, collect);
    }


    /**
     * 结算-物流订单详情
     *
     * @param id 结算物流订单id
     * @author Aick Spt
     * @date 2023-07-19 09:11
     */
    public SettlementWalletDto detailLogisticsPayment(Long id) {
        return settlementWalletMapper.detailLogisticsPayment(id);
    }

    /**
     * 物流-电子钱包付款（货到付款）结算记录-新增
     *
     * @return InsertId
     * @author Aick Spt
     * @date 2023-07-20 14:23
     * <p>
     * Transactional// isolation:事务的隔离级别，此处使用后端数据库的默认隔离级别, propagation: 如果当前没有事务，就新建一个事务，如果已经存在一个事务中，加入到这个事务中(常见)。(rollbackFor = Exception.class, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED)
     */
    @Transactional
    public Integer confirmLogisticsPayment(OfflinePaymentReq offlinePaymentReq) {
        Long id = offlinePaymentReq.getIdLong();
        BigDecimal price = offlinePaymentReq.getPrice();
        if (id == 0) {
            throw new BusinessException("结算参数ID必填");
        }
        if (price == null || price.compareTo(BigDecimal.ZERO) == 0) {
            throw new BusinessException("结算参数金额必填");
        }

        //先查询出结算单情况
        SettlementLogisticsDto settlementLogisticsDto = kwpSettlementLogisticsService.detailPayment(id);
        //检查结算单状态和所差金额
        if (settlementLogisticsDto == null) {
            log.error("非法请求，查无数据：" + id);
            throw new BusinessException("非法请求运费结算参数ID");
        }
        if (settlementLogisticsDto.getStatus() == SettlementEnum.ALL_PAYMENT.getStatus()) {
            log.error("非法请求，该订单已结算完成：" + id);
            throw new BusinessException("该订单已结算完成，无法操作");
        }
        BigDecimal remainingReceivables = settlementLogisticsDto.getTotalPrice();
        if (settlementLogisticsDto.getActualPrice() != null) {//剩余金额
            remainingReceivables = settlementLogisticsDto.getTotalPrice().subtract(settlementLogisticsDto.getActualPrice());
        }

        if (remainingReceivables.compareTo(price) < 0) {//-1表示小于,0是等于,1是大于
            log.error("本次结算输入金额比剩余付款金额大：ID：" + id + " 剩余金额：" + remainingReceivables + " 本次输入金额：" + price);
            throw new BusinessException("参数错误：输入金额过大 " + price + " 剩余金额最大值：" + remainingReceivables);
        }
        //累加入库结算单
        KwpSettlementLogistics settlementLogistics = new KwpSettlementLogistics();
        settlementLogistics.setId(settlementLogisticsDto.getId());
        settlementLogistics.setUpdateTime(LocalDateTime.now());
        if (remainingReceivables.compareTo(price) == 0) {//全部结算
            settlementLogistics.setStatus(SettlementEnum.ALL_PAYMENT.getStatus());
        }
        if (remainingReceivables.compareTo(price) > 0) {//部分结算
            settlementLogistics.setStatus(SettlementEnum.PARTIAL_PAYMENT.getStatus());
        }
        BigDecimal actualPrice = settlementLogisticsDto.getActualPrice();
        settlementLogistics.setActualPrice((actualPrice == null) ? price : actualPrice.add(price));
        int upInt = kwpSettlementLogisticsMapper.updateById(settlementLogistics);
        if (upInt > 0) {
            //新增一条修改记录
            String remark = LoginUserHolder.getUserName() + "[" + LoginUserHolder.getUserId() + "]" + "结算[" + settlementLogistics.getId() + "]" + settlementLogistics.getActualPrice() + "(" + SettlementEnum.getStatusDesc(settlementLogistics.getStatus()) + ")";
            KwpSettlementLogisticsTrack kwpSettlementLogisticsTrack = new KwpSettlementLogisticsTrack();
            kwpSettlementLogisticsTrack.setId(new IdWorker(1).nextId());
            kwpSettlementLogisticsTrack.setLSettlementId(settlementLogistics.getId());
            kwpSettlementLogisticsTrack.setRemark(remark);
            kwpSettlementLogisticsTrack.setStatus(settlementLogistics.getStatus());
            kwpSettlementLogisticsTrack.setCreateBy(LoginUserHolder.getUserId());
            kwpSettlementLogisticsTrack.setCreateTime(LocalDateTime.now());
            kwpSettlementLogisticsTrack.setUpdateBy(LoginUserHolder.getUserId());
            kwpSettlementLogisticsTrack.setUpdateTime(LocalDateTime.now());
            kwpSettlementLogisticsTrack.setDelFlag(0);
            kwpSettlementLogisticsTrackMapper.insert(kwpSettlementLogisticsTrack);

            //新增一条电子钱包结算记录
            remainingReceivables = remainingReceivables.subtract(price);
            KwpSettlementWallet kwpSettlementWallet = new KwpSettlementWallet();
            kwpSettlementWallet.setId(new IdWorker(1).nextId());
            kwpSettlementWallet.setEntId(settlementLogisticsDto.getEntId());
            kwpSettlementWallet.setSettlementId(settlementLogisticsDto.getId());
            kwpSettlementWallet.setOrderType(SettlementOrderTypeEnum.LOGISTICS.getStatus());
            kwpSettlementWallet.setChannel(WalletChannelEnum.getValue(settlementLogisticsDto.getLedgerTrading()));//先用数字默认定义为1
            kwpSettlementWallet.setPayTime(LocalDateTime.now());
            kwpSettlementWallet.setPayPrice(price);
            kwpSettlementWallet.setTopayPrice(remainingReceivables);
            kwpSettlementWallet.setType(SettlementPayTypeEnum.CASH_ON_DELIVERY.getStatus());
            kwpSettlementWallet.setRemark(Global.EMPTY_STRING);
            kwpSettlementWallet.setStatus(1);
            kwpSettlementWallet.setCreateBy(LoginUserHolder.getUserId());
            kwpSettlementWallet.setCreateTime(LocalDateTime.now());
            kwpSettlementWallet.setUpdateBy(LoginUserHolder.getUserId());
            kwpSettlementWallet.setUpdateTime(LocalDateTime.now());
            kwpSettlementWallet.setDelFlag(0);
            Integer insertKwpSettlementWallet = settlementWalletMapper.insert(kwpSettlementWallet);

            //物流货到付款电子钱包逻辑
            //todo 待处理费电子钱包逻辑

            return insertKwpSettlementWallet;
        }
        return null;
    }

    public PageRes<SettlementWalletVo> pageListTradePayment(SettlementWalletReq settlementWalletReq) {
//        //todo 查询缓存，获取客户企业id
//        String keywords = settlementReq.getKeywords();
//        if (StringUtils.isNotBlank(keywords)) {
//            System.out.println("关键之：" + keywords);
//        }
        PageHelper.startPage(settlementWalletReq.getPage(), settlementWalletReq.getPageSize());

        List<SettlementWalletDto> settlementWalletLogisticsList = settlementWalletMapper.pageListLogisticsPayment(settlementWalletReq);
        for (SettlementWalletDto entity : settlementWalletLogisticsList) {
            entity.setCreateByText("创建人名称");
            entity.setUpdateByText("更新人名称");
        }

        if (CollectionUtils.isEmpty(settlementWalletLogisticsList)) {
            return new PageRes<>(new PageInfo<>());
        }

        //指定返回值
        List<SettlementWalletVo> collect = settlementWalletLogisticsList.stream().map(a -> {
            SettlementWalletVo settlementWalletVo = new SettlementWalletVo();
            BeanUtils.copyProperties(a, settlementWalletVo);
            return settlementWalletVo;
        }).collect(Collectors.toList());

        return new PageRes<>(new PageInfo<>(collect));
    }


    /**
     * 销售-付款确认-货到付款
     *
     * @author Aick Spt
     * @date 2023-07-27 16:13
     */
    public String confirmTradePayment(WalletPayReq walletPayReq) {
        String key = String.format(RedisConstant.SETTLEMENT_KEY, walletPayReq.getId());
        if (redisLockUtil.tryLock(key)) {
            try {
                SettlementTradeDto byId = kwpSettlementTradeService.getById(walletPayReq.getIdLong(), TradeUnitType.SELL);
                if (Objects.isNull(byId)) {
                    throw new BusinessException("结算单不存在");
                }
                if (StringUtils.isNotBlank(byId.getTrading()) && !byId.getTrading().startsWith(TradingEnum.RECEIVE_PAY.getValue())) {
                    throw new BusinessException("只支持货货到付款方式订单进行当前操作");
                }
                List<LedgerUnitDto> listById = kwpSettlementTradeService.getListById(walletPayReq.getIdLong());
                if (CollectionUtils.isEmpty(listById) || listById.size() != NumberConstant.TWO) {
                    throw new BusinessException("对账单交易企业双方不存在或缺少");
                }
                Long uid = null;
                Long filter = null;
                for (LedgerUnitDto ledgerUnitDto : listById) {
                    Integer unitType = ledgerUnitDto.getUnitType();
                    if (TradeUnitType.PURCHASE.equals(unitType)) {
                        uid = ledgerUnitDto.getTopEntId();
                        continue;
                    }
                    if (TradeUnitType.SELL.equals(unitType)) {
                        filter = ledgerUnitDto.getTopEntId();
                    }
                }
                String relation = walletRelationService.getRelation(uid);
                String filterUser = walletRelationService.getRelation(filter);
                if (StringUtils.isBlank(relation) || StringUtils.isBlank(filterUser)) {
                    throw new BusinessException("顶级企业未开通电子钱包");
                }
                //付款金额
                BigDecimal price = walletPayReq.getPrice();
                //todo-xcq-完善

//        R<List<WalletDto>> wallet = payCenterService.wallet(relation, ChannelEnum.getByCode(byId.getTrading()), filterUser);
//        if (CollectionUtils.isEmpty(wallet.getData())) {
//            throw new BusinessException("暂未开通电子钱包");
//        }
//        List<WalletDto> data = wallet.getData();
//        BigDecimal bigDecimal = BigDecimal.valueOf(data.get(0).getMoney()).divide(new BigDecimal("100.0"), RoundingMode.UNNECESSARY);
//
//        if (bigDecimal.compareTo(price) < 0) {
//            throw new BusinessException("钱包可用余额不足");
//        }
                //待付款金额-本次付款金额= 剩余待付款金额
                BigDecimal subtract = byId.getWaitPrice().subtract(walletPayReq.getPrice());
                if (subtract.compareTo(new BigDecimal("0.0")) < NumberConstant.ZERO) {
                    throw new BusinessException("付款金额不能大于待付款金额");
                }
                //新增电子钱包结算记录
                KwpSettlementWallet kwpSettlementWallet = new KwpSettlementWallet();
                kwpSettlementWallet.setId(new IdWorker(NumberConstant.ONE).nextId());
                kwpSettlementWallet.setEntId(LoginUserHolder.getEntId());
                kwpSettlementWallet.setSettlementId(walletPayReq.getIdLong());
                kwpSettlementWallet.setOrderType(SettlementOrderTypeEnum.TRADE.getStatus());
                kwpSettlementWallet.setChannel(WalletChannelEnum.getValue(byId.getTrading()));
                kwpSettlementWallet.setPayTime(LocalDateTime.now());
                kwpSettlementWallet.setPayPrice(walletPayReq.getPrice());
                kwpSettlementWallet.setTopayPrice(subtract);
                kwpSettlementWallet.setType(SettlementWalletPayTypeEnum.CASH_ON_DELIVERY.getStatus());
                kwpSettlementWallet.setRemark(Global.EMPTY_STRING);
                kwpSettlementWallet.setStatus(NumberConstant.ZERO);
                kwpSettlementWallet.setCreateBy(LoginUserHolder.getUserId());
                kwpSettlementWallet.setCreateTime(LocalDateTime.now());
                kwpSettlementWallet.setUpdateBy(LoginUserHolder.getUserId());
                kwpSettlementWallet.setUpdateTime(LocalDateTime.now());
                kwpSettlementWallet.setDelFlag(Global.UN_DELETED);
                settlementWalletMapper.insert(kwpSettlementWallet);

                //更新交易结算单状态和金额
                KwpSettlementTrade kwpSettlementTrade = new KwpSettlementTrade();
                kwpSettlementTrade.setId(byId.getId());
                kwpSettlementTrade.setActualPrice(byId.getActualPrice().add(price));
                int status = subtract.compareTo(new BigDecimal("0.0")) == NumberConstant.ZERO ? SettlementEnum.ALL_PAYMENT.getStatus()
                        : SettlementEnum.PARTIAL_PAYMENT.getStatus();
                kwpSettlementTrade.setStatus(status);
                kwpSettlementTrade.setUpdateBy(LoginUserHolder.getUserId());
                kwpSettlementTrade.setUpdateTime(LocalDateTime.now());
                kwpSettlementTradeService.updateById(kwpSettlementTrade);

                settlementTradeTrackService.save(KwpSettlementTradeTrack.build(byId.getId(), SettlementTrackEnum.RECEIVE_PAY.getStatus()));
                //更新贸易订单状态
                if (status == SettlementEnum.ALL_PAYMENT.getStatus()) {
                    //查询对账单关联的订单
                    List<KwpLedgerTradeOrder> kwpLedgerTradeOrders = tradeOrderService.queryList(byId.getLedgerId());
                    if (CollectionUtils.isEmpty(kwpLedgerTradeOrders)) {
                        throw new BusinessException("未找到关联的贸易订单");
                    }
                    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_7.getValue()));
                        updateOrderStatusParam.setUpdateBy(LoginUserHolder.getUserId());
                        updateOrderStatusParam.setUpdateByName(LoginUserHolder.getUserName());
                        tradeOrderInfoService.updateOrderStatus(updateOrderStatusParam);
                    }
                }
                //todo-xcq 调用中台接口

                return "付款确认成功";
            } finally {
                redisLockUtil.unlock(key);
            }
        }
        return "请勿重复提交!";
    }

    /**
     * 预付款、货到付款记录
     * 前端接口分开
     *
     * @param settlementWalletReq 请求参数
     * @return
     */
    public PageRes<SettlementWalletVo> pageList(SettlementWalletReq settlementWalletReq) {
        PageHelper.startPage(settlementWalletReq.getPage(), settlementWalletReq.getPageSize());
        List<SettlementWalletDto> settlementWalletDto = settlementWalletMapper.pageList(settlementWalletReq);

        if (CollectionUtils.isEmpty(settlementWalletDto)) {
            return new PageRes<>();
        }
        //增加对应创建人和更新人名称
        Map<Long, UserCacheResDto> map = new HashMap<>();
        PageInfo<SettlementWalletDto> pageInfo = new PageInfo<>(settlementWalletDto);
        //指定返回值
        List<SettlementWalletVo> collect = settlementWalletDto.stream().map(a -> {
            SettlementWalletVo settlementWalletVo = new SettlementWalletVo();
            BeanUtils.copyProperties(a, settlementWalletVo);
            Long createBy = a.getCreateBy();
            Long updateBy = a.getUpdateBy();
            UserCacheResDto userCacheResDto = map.get(createBy);
            if (Objects.isNull(userCacheResDto)) {
                userCacheResDto = remoteSystemService.queryUserCacheById(createBy);
                map.put(createBy, userCacheResDto);
            }
            if (Objects.nonNull(userCacheResDto)) {
                settlementWalletVo.setCreateByText(userCacheResDto.getName());
            }
            userCacheResDto = map.get(updateBy);
            if (Objects.isNull(userCacheResDto)) {
                userCacheResDto = remoteSystemService.queryUserCacheById(updateBy);
                map.put(updateBy, userCacheResDto);
            }
            if (Objects.nonNull(userCacheResDto)) {
                settlementWalletVo.setUpdateByText(userCacheResDto.getName());
            }
            return settlementWalletVo;
        }).collect(Collectors.toList());
        return PageRes.build(pageInfo, collect);
    }

    public PageRes<SettlementWalletVo> pageListTradeCollection(SettlementWalletReq settlementWalletReq) {
        PageHelper.startPage(settlementWalletReq.getPage(), settlementWalletReq.getPageSize());

        List<SettlementWalletDto> settlementWalletLogisticsList = settlementWalletMapper.pageListLogisticsPayment(settlementWalletReq);
        for (SettlementWalletDto entity : settlementWalletLogisticsList) {
            entity.setCreateByText("创建人名称");
            entity.setUpdateByText("更新人名称");
        }

        if (CollectionUtils.isEmpty(settlementWalletLogisticsList)) {
            return new PageRes<>(new PageInfo<>());
        }

        Map<Long, UserCacheResDto> map = new HashMap<>();
        //指定返回值
        List<SettlementWalletVo> collect = settlementWalletLogisticsList.stream().map(a -> {
            SettlementWalletVo settlementWalletVo = new SettlementWalletVo();
            BeanUtils.copyProperties(a, settlementWalletVo);
            Long createBy = a.getCreateBy();
            Long updateBy = a.getUpdateBy();
            UserCacheResDto userCacheResDto = map.get(createBy);
            if (Objects.isNull(userCacheResDto)) {
                userCacheResDto = remoteSystemService.queryUserCacheById(createBy);
                map.put(createBy, userCacheResDto);
            }
            if (Objects.nonNull(userCacheResDto)) {
                settlementWalletVo.setCreateByText(userCacheResDto.getName());
            }
            userCacheResDto = map.get(updateBy);
            if (Objects.isNull(userCacheResDto)) {
                userCacheResDto = remoteSystemService.queryUserCacheById(updateBy);
                map.put(updateBy, userCacheResDto);
            }
            if (Objects.nonNull(userCacheResDto)) {
                settlementWalletVo.setUpdateByText(userCacheResDto.getName());
            }
            return settlementWalletVo;
        }).collect(Collectors.toList());

        return new PageRes<>(new PageInfo<>(collect));
    }

    /**
     * 销售-预付款
     *
     * @param id 结算单id
     * @return
     */
    public String confirmTradeCollection(Long id) {
        String key = String.format(RedisConstant.SETTLEMENT_KEY, id);

        if (redisLockUtil.tryLock(key)) {
            try {
                SettlementTradeDto byId = kwpSettlementTradeService.getById(id, TradeUnitType.PURCHASE);
                if (Objects.isNull(byId)) {
                    throw new BusinessException("结算单不存在");
                }
                if (StringUtils.isNotBlank(byId.getTrading()) && !byId.getTrading().startsWith(TradingEnum.PRE_PAY.getValue())) {
                    throw new BusinessException("只支持预付款交易方式进行预付款确认操作");
                }
                //更新交易结算单状态和金额
                KwpSettlementTrade kwpSettlementTrade = new KwpSettlementTrade();
                kwpSettlementTrade.setId(byId.getId());
                kwpSettlementTrade.setActualPrice(byId.getTotalPrice());
                kwpSettlementTrade.setStatus(SettlementEnum.ALL_PAYMENT.getStatus());
                kwpSettlementTrade.setUpdateBy(LoginUserHolder.getUserId());
                kwpSettlementTrade.setUpdateTime(LocalDateTime.now());
                kwpSettlementTradeService.updateById(kwpSettlementTrade);
                //新增电子钱包结算记录
                KwpSettlementWallet kwpSettlementWallet = new KwpSettlementWallet();
                kwpSettlementWallet.setId(new IdWorker(1).nextId());
                kwpSettlementWallet.setEntId(LoginUserHolder.getEntId());
                kwpSettlementWallet.setSettlementId(byId.getId());
                kwpSettlementWallet.setOrderType(SettlementOrderTypeEnum.TRADE.getStatus());
                kwpSettlementWallet.setChannel(WalletChannelEnum.getValue(byId.getTrading()));
                kwpSettlementWallet.setPayTime(LocalDateTime.now());
                kwpSettlementWallet.setPayPrice(byId.getTotalPrice());
                kwpSettlementWallet.setTopayPrice(new BigDecimal("0.0"));
                kwpSettlementWallet.setType(SettlementWalletPayTypeEnum.ADVANCE_PAYMENT.getStatus());
                kwpSettlementWallet.setRemark(Global.EMPTY_STRING);
                kwpSettlementWallet.setStatus(NumberConstant.ZERO);
                kwpSettlementWallet.setCreateBy(LoginUserHolder.getUserId());
                kwpSettlementWallet.setCreateTime(LocalDateTime.now());
                kwpSettlementWallet.setUpdateBy(LoginUserHolder.getUserId());
                kwpSettlementWallet.setUpdateTime(LocalDateTime.now());
                kwpSettlementWallet.setDelFlag(Global.UN_DELETED);
                settlementWalletMapper.insert(kwpSettlementWallet);
                settlementTradeTrackService.save(KwpSettlementTradeTrack.build(byId.getId(), SettlementTrackEnum.PRE_PAY.getStatus()));
                //todo-xcq 调用中台接口
                //todo-xcq 调用订单接口，更新订单状态
                return "确认回款成功";
            } finally {
                redisLockUtil.unlock(key);
            }
        }
        return "请勿重复提交！";

    }

    /**
     * 货到付款-查询钱包余额
     *
     * @param id 结算单id
     * @return
     */
    public BigDecimal getConfirmTradePayment(Long id) {
        SettlementTradeDto byId = kwpSettlementTradeService.getById(id, TradeUnitType.SELL);
        if (Objects.isNull(byId)) {
            throw new BusinessException("结算单不存在");
        }
        if (StringUtils.isNotBlank(byId.getTrading()) && !byId.getTrading().startsWith(TradingEnum.RECEIVE_PAY.getValue())) {
            throw new BusinessException("只支持货货到付款方式订单进行当前操作");
        }
        List<LedgerUnitDto> listById = kwpSettlementTradeService.getListById(id);
        if (CollectionUtils.isEmpty(listById) || listById.size() != NumberConstant.TWO) {
            throw new BusinessException("对账单交易企业双方不存在或缺少");
        }
        Long uid = null;
        Long filter = null;
        for (LedgerUnitDto ledgerUnitDto : listById) {
            Integer unitType = ledgerUnitDto.getUnitType();
            if (TradeUnitType.PURCHASE.equals(unitType)) {
                uid = ledgerUnitDto.getTopEntId();
                continue;
            }
            if (TradeUnitType.SELL.equals(unitType)) {
                filter = ledgerUnitDto.getTopEntId();
            }
        }
        String relation = walletRelationService.getRelation(uid);
        String filterUser = walletRelationService.getRelation(filter);
        if (StringUtils.isBlank(relation) || StringUtils.isBlank(filterUser)) {
            throw new BusinessException("顶级企业未开通电子钱包");
        }
        R<List<WalletDto>> wallet = payCenterService.wallet(relation, ChannelEnum.getByCode(byId.getTrading()), filterUser);
        if (CollectionUtils.isEmpty(wallet.getData())) {
            throw new BusinessException("暂未开通电子钱包");
        }
        List<WalletDto> data = wallet.getData();
        return BigDecimal.valueOf(data.get(NumberConstant.ZERO).getMoney() / 100.0);
    }
}

