package com.dk.mdm.service.sale;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dk.common.exception.BaseBusinessException;
import com.dk.common.infrastructure.annotaiton.Pagination;
import com.dk.common.infrastructure.constant.Constant;
import com.dk.common.infrastructure.enums.ErrorCodeEnum;
import com.dk.common.model.pojo.PageList;
import com.dk.common.response.ResponseCodeEnum;
import com.dk.common.response.ResponseResultUtil;
import com.dk.common.response.ResponseResultVO;
import com.dk.mdm.infrastructure.convert.mac.RecPayItemConvert;
import com.dk.mdm.infrastructure.convert.sale.OrderConvert;
import com.dk.mdm.infrastructure.convert.sale.OrderItemConvert;
import com.dk.mdm.infrastructure.convert.sale.OutBoundDtoConvert;
import com.dk.mdm.infrastructure.util.AuthUtils;
import com.dk.mdm.mapper.common.CommonMapper;
import com.dk.mdm.mapper.ivt.OutboundItemMapper;
import com.dk.mdm.mapper.ivt.OutboundMapper;
import com.dk.mdm.mapper.mac.AccountItemMapper;
import com.dk.mdm.mapper.mac.RecPayHandleItemMapper;
import com.dk.mdm.mapper.mac.RecPayItemMapper;
import com.dk.mdm.mapper.mac.RecPayMapper;
import com.dk.mdm.mapper.mst.CustomerMapper;
import com.dk.mdm.mapper.mst.MoneyAccountItemMapper;
import com.dk.mdm.mapper.mst.MoneyAccountMapper;
import com.dk.mdm.mapper.sale.MultiOwnerMapper;
import com.dk.mdm.mapper.sale.OrderItemMapper;
import com.dk.mdm.mapper.sale.OrderMapper;
import com.dk.mdm.model.pojo.mac.Account;
import com.dk.mdm.model.pojo.mac.AccountItem;
import com.dk.mdm.model.pojo.mac.RecPay;
import com.dk.mdm.model.pojo.mac.RecPayItem;
import com.dk.mdm.model.pojo.mst.Customer;
import com.dk.mdm.model.pojo.mst.MoneyAccount;
import com.dk.mdm.model.pojo.mst.MoneyAccountItem;
import com.dk.mdm.model.pojo.mst.Supplier;
import com.dk.mdm.model.pojo.sale.MultiOwner;
import com.dk.mdm.model.pojo.sale.Order;
import com.dk.common.service.BaseService;
import com.dk.common.mapper.BaseMapper;
import com.dk.mdm.model.pojo.sale.OrderItem;
import com.dk.mdm.model.query.ivt.OutboundItemQuery;
import com.dk.mdm.model.query.ivt.OutboundQuery;
import com.dk.mdm.model.query.mac.RecPayItemQuery;
import com.dk.mdm.model.query.mac.RecPayQuery;
import com.dk.mdm.model.query.sale.MultiOwnerQuery;
import com.dk.mdm.model.query.sale.OrderItemQuery;
import com.dk.mdm.model.query.sale.OrderQuery;
import com.dk.mdm.model.response.ivt.OutboundItemResponse;
import com.dk.mdm.model.response.ivt.OutboundResponse;
import com.dk.mdm.model.response.mac.RecPayItemResponse;
import com.dk.mdm.model.response.mac.RecPayResponse;
import com.dk.mdm.model.response.sale.MultiOwnerResponse;
import com.dk.mdm.model.response.sale.OrderItemResponse;
import com.dk.mdm.model.response.sale.OrderResponse;
import com.dk.mdm.model.vo.ivt.OutboundVO;
import com.dk.mdm.model.vo.mac.RecPayItemVO;
import com.dk.mdm.model.vo.mst.CustomerVO;
import com.dk.mdm.model.vo.mst.SupplierVo;
import com.dk.mdm.model.vo.sale.OrderItemVO;
import com.dk.mdm.model.vo.sale.OrderVO;
import com.dk.mdm.service.common.CommonService;
import com.dk.mdm.service.ivt.outbound.OutboundSaleOrderService;
import com.dk.mdm.service.mac.AccountService;
import com.dk.mdm.service.mac.RecPayItemService;
import com.dk.mdm.service.mac.ReceiptService;
import com.dk.mdm.service.mst.CustomerService;
import com.dk.mdm.service.mst.MoneyAccountService;
import com.dk.mdm.service.mst.SupplierService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Transactional
public class OrderService extends BaseService<Order> {

    @Override
    public String getPrimaryKey() {
        return "order_id";
    }

    @Override
    public BaseMapper<Order> getRepository() {
        return orderMapper;
    }

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private CommonService commonService;

    @Autowired
    private CommonMapper commonMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    MultiOwnerMapper multiOwnerMapper;

    @Autowired
    private RecPayItemService recPayItemService;

    @Autowired
    ReceiptService receiptService;

    @Autowired
    private RecPayMapper recPayMapper;

    @Autowired
    private RecPayItemMapper recPayItemMapper;

    @Autowired
    private AccountService accountService;

    @Autowired
    private AccountItemMapper accountItemMapper;

    @Autowired
    private MoneyAccountService moneyAccountService;

    @Autowired
    private MoneyAccountMapper moneyAccountMapper;

    @Autowired
    private MoneyAccountItemMapper moneyAccountItemMapper;

    @Autowired
    RecPayHandleItemMapper recPayHandleItemMapper;

    @Autowired
    private OrderConvert orderConvert;

    @Autowired
    private OrderItemConvert orderItemConvert;

    @Autowired
    private RecPayItemConvert recPayItemConvert;

    @Autowired
    private OutboundSaleOrderService outboundSaleOrderService;

    @Autowired
    private OutBoundDtoConvert outBoundDtoConvert;

    @Autowired
    private OutboundItemMapper outboundItemMapper;

    @Autowired
    private OutboundMapper outboundMapper;

    @Autowired
    private SupplierService supplierService;

    @Autowired
    private AuthUtils authUtils;

    @Autowired
    private CustomerService customerService;

    /**
     * @desc : 条件查询
     * @author : 付斌
     * @date : 2023/1/9 10:40
     */
    @Pagination
    public ResponseResultVO<PageList<OrderResponse>> selectByCond(OrderQuery orderQuery) {
        return super.mergeListWithCount(orderQuery, orderMapper.selectByCond(orderQuery),
                orderMapper.countByCondForSelectByCond(orderQuery));
    }

    /**
     * @desc : 条件查询(数量）小程序使用
     * @author : 周兴
     * @date : 2024/4/10 10:40
     */
    public ResponseResultVO<?> countByCond(OrderQuery orderQuery) {
        return ResponseResultUtil.success(orderMapper.countByCond(orderQuery));
    }

    /**
     * @desc : 以销定采 查询
     * @author : 王英杰
     * @date : 2023/3/14 10:36
     */
    @Pagination
    public ResponseResultVO<PageList<Map<String, Object>>> purSaleSelectByCond(OrderQuery orderQuery) {
        return super.mergeListWithCount(orderQuery, orderMapper.purSaleSelectByCond(orderQuery),
                orderMapper.countByCond(orderQuery));
    }

    /**
     * @desc : 查询订单明细（货物、收款、附件）
     * @author : 付斌
     * @date : 2024-02-28 13:25
     */
    @Pagination
    public ResponseResultVO<Map<String, Object>> selectOrderInfoById(String id) {
        Map<String, Object> result = new HashMap<>();
        // 商品明细
        List<OrderItemResponse> orderItem = orderItemMapper.selectByCond(new OrderItemQuery().setOrderId(id));
        result.put("orderItem", orderItem);

        // 收款明细
        List<RecPayResponse> recPayList = recPayMapper.selectByCond(new RecPayQuery().setBiznisId(id).setFlgOrderHandle(false));
        if (recPayList != null && recPayList.size() > 0) {
            List<RecPayItemResponse> receiptItem = recPayItemMapper.selectByCond(new RecPayItemQuery().setRpId(recPayList.get(0).getRpId()));
            result.put("receiptItem", receiptItem);
        } else {
            result.put("receiptItem", new ArrayList<RecPayResponse>());
        }
        return ResponseResultUtil.success(result);
    }

    /**
     * @desc : 新建方法
     * @author : 付斌
     * @date : 2023/1/9 10:49
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public ResponseResultVO<?> insert(OrderVO orderVO) {

        // 如果没有客户id，要新建
        if (orderVO.getCusId() == null) {
            List<Customer> listCustomer = customerMapper.selectByCond(new Customer().setCpId(orderVO.getCpId()).setCusPhone(orderVO.getCusPhone()));
            // 如果客户电话已存在
            if (listCustomer.size() > 0) {
                throw new BaseBusinessException(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.ISEXISTS_CUSPHONE.getMessage());
            }
            // 创建客户,获取编码和主键UuId
            Map<String, Object> codeMap = commonService.getUniqueNoteCode(Constant.docNameConstant.CUSTOMER.getName(), true);
            Customer customer = new Customer();
            // 增加跟进人，用于权限分配
            List<String> followStaffs = new ArrayList<>();
            followStaffs.add(orderVO.getMakeStaff());
            customer.setCusId(codeMap.get("outId").toString()).setCusCode(codeMap.get("outNote").toString()).setCusName(orderVO.getCusName())
                    .setCusPhone(orderVO.getCusPhone()).setAddressArea(orderVO.getAddressArea()).setAddressName(orderVO.getAddressName())
                    .setAddressNo(orderVO.getAddressNo()).setAddressGcj02(orderVO.getAddressGcj02()).setAddressFull(orderVO.getAddressFull())
                    .setContactName(orderVO.getContactName()).setContactPhone(orderVO.getContactPhone()).setCusFrom(orderVO.getCusFrom())
                    .setChannelId(orderVO.getSalesChannel()).setOrgId(orderVO.getOrgId()).setStaffId(orderVO.getStaffId())
                    .setFollowStaffs(followStaffs)
                    .setReportStaff(orderVO.getMakeStaff()).setSaleStatus(Constant.SaleStatus.CHENGJIAO.getName()).setCpId(orderVO.getCpId());
            customerMapper.insert(customer);
            orderVO.setCusId(customer.getCusId());
        } else {
            // 如果当前跟进人
            Customer cus = customerMapper.selectByIdForUpdate(orderVO.getCusId());
            List<String> followStaffs = cus.getFollowStaffs();
            Boolean updateFollowFlag = false;
            if (followStaffs == null) {
                followStaffs.add(orderVO.getMakeStaff());
                updateFollowFlag = true;
            } else {
                if (!followStaffs.contains(orderVO.getMakeStaff())) {
                    followStaffs.add(orderVO.getMakeStaff());
                    updateFollowFlag = true;
                }
            }
            if (updateFollowFlag) {
                // 更新当前跟进人
                customerMapper.updateFollowStaffs(new Customer().setCusId(orderVO.getCusId())
                        .setFollowStaffs(followStaffs));
            }
            //更新总单客户状态为成交
            customerService.update(new CustomerVO().setCusId(orderVO.getCusId()).setSaleStatus(Constant.SaleStatus.CHENGJIAO.getName()) );
        }

        // 获取单号
        Map<String, Object> codeMap = commonService.getUniqueNoteCode(Constant.docNameConstant.ORDER.getName(), false);
        orderVO.setOrderId(codeMap.get("outId").toString()).setOrderNo(codeMap.get("outNote").toString())
                .setOrderType(Constant.DocumentType.ORDER.getName());
        // 转化实体
        Order order = orderConvert.convertToPo(orderVO);
        // 订单总单保存
        super.insert(order);

        // 业务部门业绩保存
        if (orderVO.getOrgList() != null && orderVO.getOrgList().size() > 0) {
            for (Map<String, Object> map : orderVO.getOrgList()) {
                MultiOwner multiOwner = new MultiOwner();
                multiOwner.setOrderId(order.getOrderId()).setOwnerId(map.get("orgId").toString())
                        .setAllocationRatio(new BigDecimal(map.get("allocationRatio").toString())).setCpId(order.getCpId());
                if (Boolean.parseBoolean(map.get("ownerFlag").toString())) {
                    multiOwner.setOwnerType(Constant.OwnerType.Z_ORG.getName());
                } else {
                    multiOwner.setOwnerType(Constant.OwnerType.C_ORG.getName());
                }
                multiOwnerMapper.insert(multiOwner);
            }
        }

        // 业务员业绩保存
        if (orderVO.getStaffList() != null && orderVO.getStaffList().size() > 0) {
            for (Map<String, Object> map : orderVO.getStaffList()) {
                MultiOwner multiOwner = new MultiOwner();
                multiOwner.setOrderId(order.getOrderId()).setOwnerId(map.get("staffId").toString())
                        .setAllocationRatio(new BigDecimal(map.get("allocationRatio").toString())).setCpId(order.getCpId());
                if (Boolean.parseBoolean(map.get("ownerFlag").toString())) {
                    multiOwner.setOwnerType(Constant.OwnerType.Z_STAFF.getName());
                } else {
                    multiOwner.setOwnerType(Constant.OwnerType.C_STAFF.getName());
                }
                multiOwnerMapper.insert(multiOwner);
            }
        }

        // 订单明细保存
        if (orderVO.getItemList() != null && orderVO.getItemList().size() > 0) {
            // 使用HashMap来存储SupName到SupId的映射
            Map<String, String> supNameToSupIdMap = new HashMap<>();
            for (OrderItemVO orderItemVO : orderVO.getItemList()) {
                // 如果SKU ID为空，表示外协品
                if (orderItemVO.getSkuId() == null) {
                    // 如果SupId为空，表示在库中不存在这个供应商
                    if (orderItemVO.getSupId() == null) {
                        // 检查是否已经为这个SupName创建了供应商
                        String existingSupId = supNameToSupIdMap.get(orderItemVO.getSupName());
                        if (existingSupId == null) {
                            // 尚未创建，新建供应商
                            SupplierVo supplierVo = new SupplierVo()
                                    .setSupName(orderItemVO.getSupName())
                                    .setSupType("供应商类别-外协")
                                    .setCpId(authUtils.getStaff().getCpId());
                            Supplier supplier = supplierService.saleinsert(supplierVo);
                            // 将新创建的SupId存入映射
                            supNameToSupIdMap.put(orderItemVO.getSupName(), supplier.getSupId());
                            // 设置orderItemVO的SupId
                            orderItemVO.setSupId(supplier.getSupId());
                        } else {
                            // 已经创建，直接设置orderItemVO的SupId
                            orderItemVO.setSupId(existingSupId);
                        }
                    }
                }

                OrderItem orderItem = orderItemConvert.convertToPo(orderItemVO);
                orderItem.setOrderId(order.getOrderId()).setCpId(order.getCpId()).setOutStatus(Constant.OutStatus.DAICHUKU.getName());
                if (orderItem.getPriceStd() == null) {
                    orderItem.setPriceStd(BigDecimal.ZERO);
                }
                if (orderItem.getAmtStd() == null) {
                    orderItem.setAmtStd(BigDecimal.ZERO);
                }
                orderItem.setItemId(UUID.randomUUID().toString());
                orderItemMapper.insert(orderItem);
                orderItemVO.setItemId(orderItem.getItemId());
            }
        }

        /**************************************** 客户收款begin ********************************/
        if (orderVO.getReceiptList() != null && orderVO.getReceiptList().size() > 0) {
            // 商户产品版本
            String gradeCode = "PRO";
            Map<String, Object> paramCompany = new HashMap<>();
            paramCompany.put("cpId", orderVO.getCpId());
            List<Map<String, Object>> listCompany = commonMapper.getCompany(paramCompany);
            if (listCompany.size() > 0) {
                gradeCode = listCompany.get(0).get("gradeCode").toString();
            }
            // 获取单号
            codeMap = commonService.getUniqueNoteCode(Constant.docNameConstant.RECPAY.getName(), false);
            RecPay recPay = new RecPay();

            // 专业版有定金
            if ("PRO".equals(gradeCode)) {
                recPay.setRpId(codeMap.get("outId").toString()).setRpNo(codeMap.get("outNote").toString())
                        .setRpType(Constant.RpType.SHOU_KUAN.getName()).setObjectId(orderVO.getCusId())
                        .setOrgId(orderVO.getOrgId()).setStaffId(orderVO.getStaffId()).setAccDate(LocalDate.now())
                        .setBiznisType(Constant.InventoryDocCode.ORDER.getTableName()).setBiznisId(orderVO.getOrderId()).setBiznisNo(orderVO.getOrderNo())
                        .setMakeStaff(orderVO.getMakeStaff()).setCpId(orderVO.getCpId()).setFlgLock(true);
                // 计算订单明细的出库中数量，金额合计
                RecPayItemVO itemSum = orderVO.getReceiptList().stream().reduce((x, y) -> {
                    RecPayItemVO item = new RecPayItemVO();
                    item.setAmtRec(x.getAmtRec().add(y.getAmtRec()));
                    return item;
                }).get();
                recPay.setSumAmtRec(itemSum.getAmtRec());

                // 总单保存
                recPayMapper.insert(recPay);

                // 明细保存
                for (RecPayItemVO recPayItemVO : orderVO.getReceiptList()) {
                    RecPayItem recPayItem = recPayItemConvert.convertToPo(recPayItemVO);
                    recPayItem.setRpId(recPay.getRpId()).setCpId(recPay.getCpId()).setMakeStaff(recPay.getMakeStaff()).setAccDate(recPay.getAccDate());
                    recPayItemMapper.insert(recPayItem);

                    // 插入账款明细
                    AccountItem accountItem = new AccountItem();
                    accountItem.setAccItemType(Constant.accItemType.SHOU_KUAN.getName())
                            .setObjectId(recPay.getObjectId()).setOrgId(recPay.getOrgId()).setStaffId(recPay.getStaffId())
                            .setAccDate(recPay.getAccDate()).setRecStatus(Constant.recStatuse.QUE_DING.getName()).setAmtRec(recPayItem.getAmtRec())
                            .setBiznisType(Constant.InventoryDocCode.REC_PAY_ITEM.getTableName()).setBiznisId(recPayItem.getItemId()).setBiznisNo(recPay.getRpNo())
                            .setMakeStaff(recPay.getMakeStaff()).setCpId(recPay.getCpId()).setFlgLock(true);
                    accountItemMapper.insert(accountItem);

                    // 更新收款单上的账款明细Id
                    RecPayItem recPayItemUpdate = new RecPayItem();
                    recPayItemUpdate.setAccItemId(accountItem.getItemId()).setItemId(recPayItem.getItemId());
                    recPayItemService.updateByUuid(recPayItemUpdate);

                    // 插入资金流水
                    MoneyAccountItem moneyAccountItem = new MoneyAccountItem();
                    moneyAccountItem.setMacId(recPayItem.getMacId()).setFlowType(Constant.FlowType.SHOU_FU_KUAN.getName())
                            .setInvoiceId(recPayItem.getItemId()).setAmtInflow(recPayItem.getAmtRec()).setAccDate(recPay.getAccDate())
                            .setMakeStaff(recPayItem.getMakeStaff()).setCpId(recPayItem.getCpId());
                    moneyAccountItemMapper.insert(moneyAccountItem);

                    // 更新资金账户
                    MoneyAccount moneyAccountForUpdate = moneyAccountMapper.selectByIdForUpdate(recPayItem.getMacId());
                    MoneyAccount moneyAccountUpdate = new MoneyAccount();
                    moneyAccountUpdate.setBalance(moneyAccountForUpdate.getBalance().add(recPayItem.getAmtRec()))
                            .setMacId(moneyAccountForUpdate.getMacId());
                    moneyAccountService.updateByUuid(moneyAccountUpdate);
                }

                // 插入账款总表
                Account accountForUpdate = accountService.getCusAccountForUpdate(recPay.getObjectId());
                // 更新账款总表上收款的相关字段
                Account accountUpdate = new Account();
                accountUpdate.setReceiptLock(accountForUpdate.getReceiptLock().add(recPay.getSumAmtRec()))//  锁定金额
                        .setObjectId(accountForUpdate.getObjectId());
                accountService.updateByUuid(accountUpdate);
            } else if ("STD".equals(gradeCode)) {
                recPay.setRpId(codeMap.get("outId").toString()).setRpNo(codeMap.get("outNote").toString())
                        .setRpType(Constant.RpType.SHOU_KUAN.getName()).setObjectId(orderVO.getCusId())
                        .setOrgId(orderVO.getOrgId()).setStaffId(orderVO.getStaffId()).setAccDate(LocalDate.now())
                        .setBiznisType(Constant.InventoryDocCode.ORDER.getTableName()).setBiznisId(orderVO.getOrderId()).setBiznisNo(orderVO.getOrderNo())
                        .setMakeStaff(orderVO.getMakeStaff()).setCpId(orderVO.getCpId());
                // 计算订单明细的出库中数量，金额合计
                RecPayItemVO itemSum = orderVO.getReceiptList().stream().reduce((x, y) -> {
                    RecPayItemVO item = new RecPayItemVO();
                    item.setAmtRec(x.getAmtRec().add(y.getAmtRec()));
                    return item;
                }).get();
                recPay.setSumAmtRec(itemSum.getAmtRec());

                // 总单保存
                recPayMapper.insert(recPay);

                // 明细保存
                for (RecPayItemVO recPayItemVO : orderVO.getReceiptList()) {
                    RecPayItem recPayItem = recPayItemConvert.convertToPo(recPayItemVO);
                    recPayItem.setRpId(recPay.getRpId()).setCpId(recPay.getCpId()).setMakeStaff(recPay.getMakeStaff()).setAccDate(recPay.getAccDate());
                    recPayItemMapper.insert(recPayItem);

                    // 插入账款明细
                    AccountItem accountItem = new AccountItem();
                    accountItem.setAccItemType(Constant.accItemType.SHOU_KUAN.getName())
                            .setObjectId(recPay.getObjectId()).setOrgId(recPay.getOrgId()).setStaffId(recPay.getStaffId())
                            .setAccDate(recPay.getAccDate()).setRecStatus(Constant.recStatuse.QUE_DING.getName()).setAmtRec(recPayItem.getAmtRec())
                            .setBiznisType(Constant.InventoryDocCode.REC_PAY_ITEM.getTableName()).setBiznisId(recPayItem.getItemId()).setBiznisNo(recPay.getRpNo())
                            .setMakeStaff(recPay.getMakeStaff()).setCpId(recPay.getCpId());
                    accountItemMapper.insert(accountItem);

                    // 更新收款单上的账款明细Id
                    RecPayItem recPayItemUpdate = new RecPayItem();
                    recPayItemUpdate.setAccItemId(accountItem.getItemId()).setItemId(recPayItem.getItemId());
                    recPayItemService.updateByUuid(recPayItemUpdate);

                    // 插入资金流水
                    MoneyAccountItem moneyAccountItem = new MoneyAccountItem();
                    moneyAccountItem.setMacId(recPayItem.getMacId()).setFlowType(Constant.FlowType.SHOU_FU_KUAN.getName())
                            .setInvoiceId(recPayItem.getItemId()).setAmtInflow(recPayItem.getAmtRec()).setAccDate(recPay.getAccDate())
                            .setMakeStaff(recPayItem.getMakeStaff()).setCpId(recPayItem.getCpId());
                    moneyAccountItemMapper.insert(moneyAccountItem);

                    // 更新资金账户
                    MoneyAccount moneyAccountForUpdate = moneyAccountMapper.selectByIdForUpdate(recPayItem.getMacId());
                    MoneyAccount moneyAccountUpdate = new MoneyAccount();
                    moneyAccountUpdate.setBalance(moneyAccountForUpdate.getBalance().add(recPayItem.getAmtRec()))
                            .setMacId(moneyAccountForUpdate.getMacId());
                    moneyAccountService.updateByUuid(moneyAccountUpdate);
                }

                // 插入账款总表
                Account accountForUpdate = accountService.getCusAccountForUpdate(recPay.getObjectId());
                // 更新账款总表上收款的相关字段
                Account accountUpdate = new Account();
                accountUpdate.setReceipt(accountForUpdate.getReceipt().add(recPay.getSumAmtRec()))//  总收款金额
                        .setReceiptResidue(accountForUpdate.getReceiptResidue().add(recPay.getSumAmtRec()))//  可退金额
                        .setObjectId(accountForUpdate.getObjectId());
                accountService.updateByUuid(accountUpdate);
            }

        }
        /**************************************** 客户收款end ********************************/
        //开单并出库办理
        if (orderVO.getOutboundProcessingFlag() != null && orderVO.getOutboundProcessingFlag()) {
            for (OrderItemVO orderItemVO : orderVO.getItemList()) {
                orderItemVO.setOutingQty(orderItemVO.getItemQty());
                orderItemVO.setOutingAmt(orderItemVO.getItemAmt());
                orderItemVO.setPriceOut(orderItemVO.getFactPrice());
                orderItemVO.setFromId(orderVO.getOrderId());
                orderItemVO.setFromItemId(orderItemVO.getItemId());
            }
            OutboundVO outboundVO = outBoundDtoConvert.convertToPo(orderVO);
            outboundVO.setOutDate(LocalDate.now());
            outboundVO.setOutingQty(orderVO.getSumQuantity());
            outboundVO.setOutingAmt(orderVO.getFactAmt());
            outboundVO.setFlgAutoHandle(orderVO.getFlgAutoHandle());
            outboundVO.setFlgHandleSetting(orderVO.getFlgHandleSetting());
            outboundVO.setFromId(order.getOrderId());
            outboundVO.setFromNo(order.getOrderNo());
            outboundVO.setOutDate(orderVO.getDeliveryDate());
            outboundVO.setFactAmt(orderVO.getFactAmt());
            outboundVO.setDiscount(orderVO.getDiscount());
            outboundVO.setDiscAmt(orderVO.getDiscAmt());
            outboundVO.setSumAmount(orderVO.getSumAmount());
            outboundSaleOrderService.inventoryOUtBond(outboundVO);
        }

        return ResponseResultUtil.success();
    }

    /**
     * @desc : 编辑方法
     * @author : 付斌
     * @date : 2023/1/9 10:49
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public ResponseResultVO<?> update(OrderVO orderVO) {
        Order orderForUpdate = orderMapper.selectByIdForUpdate(orderVO.getOrderId());
        // 并发校验
        if (!orderForUpdate.getFlgValid()) {
            throw new BaseBusinessException(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.ISFLGVALID_FALSE.getMessage());
        }
        // 如果全部出库了
        //标：之前沟通允许大编辑，目前订单开单已出库的单子进行编辑是不允许操作的（请确定一下，到底系统设计是否允许大编辑？）
        //bug 6933可查
//        if (orderForUpdate.getSumQuantity().compareTo(orderForUpdate.getOutQty()) == 0) {
//            throw new BaseBusinessException(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.ORDER_IS_OUT.getMessage());
//        }
        // 商户产品版本
        String gradeCode = "PRO";
        Map<String, Object> paramCompany = new HashMap<>();
        paramCompany.put("cpId", orderVO.getCpId());
        List<Map<String, Object>> listCompany = commonMapper.getCompany(paramCompany);
        if (listCompany.size() > 0) {
            gradeCode = listCompany.get(0).get("gradeCode").toString();
        }

        //更新总单客户信息
        customerService.update(new CustomerVO().setCusId(orderVO.getCusId()).setCusCode(orderVO.getCusCode())
                .setCusName(orderVO.getCusName()).setCusPhone(orderVO.getCusPhone()).setAddressArea(orderVO.getAddressArea())
                .setAddressFull(orderVO.getAddressFull()).setAddressName(orderVO.getAddressName())
                .setAddressNo(orderVO.getAddressNo()).setAddressGcj02(orderVO.getAddressGcj02())
                .setContactName(orderVO.getContactName()).setContactPhone(orderVO.getContactPhone())
                .setChannelId(orderVO.getSalesChannel()).setSaleStatus(Constant.SaleStatus.CHENGJIAO.getName()));

        // 明细实体（避免并发，需要再查一遍）
        OrderItem orderItemForUpdate;
        // 转化实体
        Order order = orderConvert.convertToPo(orderVO);
        //删除的
        if (orderVO.getDeleteItemList() != null) {
            List<OrderItemVO> deleteOrderItemVOList = orderVO.getDeleteItemList().stream().filter(it -> it.getItemId() != null).collect(Collectors.toList());
            if (deleteOrderItemVOList.size() > 0) {
                for (OrderItemVO orderItemVO : deleteOrderItemVOList) {
                    orderItemForUpdate = orderItemMapper.selectByIdForUpdate(orderItemVO.getItemId());
                    //当gradeCode为"STD"时，无论outStatus是什么，都直接删除；而当gradeCode不是"STD"时，只有outStatus为DAICHUKU时才允许删除
                    if (Constant.GradeCode.STD.getName().equals(gradeCode) ||
                            (Constant.OutStatus.DAICHUKU.getName().equals(orderItemForUpdate.getOutStatus()))) {
                        orderItemMapper.deleteById(orderItemVO.getItemId());
                    } else {
                        throw new BaseBusinessException(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.NO_WAIT_INTO.getMessage());
                    }
                }
            }
        }

        // 编辑的
        List<OrderItemVO> editOrderItemVOList = orderVO.getItemList().stream().filter(it -> it.getItemId() != null).collect(Collectors.toList());
        for (OrderItemVO orderItemVO : editOrderItemVOList) {
            orderItemForUpdate = orderItemMapper.selectByIdForUpdate(orderItemVO.getItemId());
            // 出库数量
            BigDecimal outintOrOutQty = orderItemForUpdate.getOutingQty().add(orderItemForUpdate.getOutQty());
            if (!Constant.GradeCode.STD.getName().equals(gradeCode)) {
                // 商品数量不能小于（出库中数量+已出库数量）
                if (orderItemVO.getItemQty().compareTo(outintOrOutQty) == -1) {
                    throw new BaseBusinessException(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.ITEMQTY_NO_LESS_OUTQTY.getMessage());
                }
            }
            // 如果出库数量不是0，则不能改仓库
            if (outintOrOutQty.compareTo(BigDecimal.ZERO) != 0) {
                if (orderItemForUpdate.getSkuId() != null) { //过滤外协品
                    if (!orderItemForUpdate.getWhId().equals(orderItemVO.getWhId())) {
                        throw new BaseBusinessException(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.ORDER_ISOUT.getMessage());
                    }
                }
            }
            OrderItem orderItem = orderItemConvert.convertToPo(orderItemVO);
            orderItemService.updateByUuid(orderItem);
            // 免费版：
            // 订单编辑钱保存，要更改对应出库单的钱
            // 订单编辑数量保存，要更改对应出库单数量，并且更新库存；更改后数量不能小于退货数量；
            // 专业版：编辑保持原逻辑
            if ("STD".equals(gradeCode)) {  //免費版特加逻辑
                //更改后数量不能小于退货数量；
                if (orderItemVO.getItemQty().compareTo(orderItemForUpdate.getReturnQty()) == -1) {
                    throw new BaseBusinessException(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.GOODSQTY_NO_LESS_RETURNQTY.getMessage());
                }

            }
        }

        // 新增的
        List<OrderItemVO> insertOrderItemVOList = orderVO.getItemList().stream().filter(it -> it.getItemId() == null).collect(Collectors.toList());
        // 使用HashMap来存储SupName到SupId的映射
        Map<String, String> supNameToSupIdMap = new HashMap<>();
        for (OrderItemVO orderItemVO : insertOrderItemVOList) {
            // 如果SKU ID为空，表示外协品
            if (orderItemVO.getSkuId() == null) {
                // 如果SupId为空，表示在库中不存在这个供应商
                if (orderItemVO.getSupId() == null) {
                    // 检查是否已经为这个SupName创建了供应商
                    String existingSupId = supNameToSupIdMap.get(orderItemVO.getSupName());
                    if (existingSupId == null) {
                        // 尚未创建，新建供应商
                        SupplierVo supplierVo = new SupplierVo()
                                .setSupName(orderItemVO.getSupName())
                                .setSupType("供应商类别-外协")
                                .setCpId(authUtils.getStaff().getCpId());
                        Supplier supplier = supplierService.saleinsert(supplierVo);
                        // 将新创建的SupId存入映射
                        supNameToSupIdMap.put(orderItemVO.getSupName(), supplier.getSupId());
                        // 设置orderItemVO的SupId
                        orderItemVO.setSupId(supplier.getSupId());
                    } else {
                        // 已经创建，直接设置orderItemVO的SupId
                        orderItemVO.setSupId(existingSupId);
                    }
                }
            }

            OrderItem orderItem = orderItemConvert.convertToPo(orderItemVO);
            orderItem.setOrderId(order.getOrderId()).setCpId(order.getCpId()).setOutStatus(Constant.OutStatus.DAICHUKU.getName());
            orderItem.setItemId(UUID.randomUUID().toString());
            orderItemMapper.insert(orderItem);
            orderItemVO.setItemId(orderItem.getItemId());
            orderItemVO.setOrderId(orderVO.getOrderId());
        }

        // 删除业绩信息
        multiOwnerMapper.deleteByOrderId(order.getOrderId());

        // 重新保存业绩信息
        // 业务部门业绩保存
        if (orderVO.getOrgList() != null && orderVO.getOrgList().size() > 0) {
            for (Map<String, Object> map : orderVO.getOrgList()) {
                MultiOwner multiOwner = new MultiOwner();
                multiOwner.setOrderId(order.getOrderId()).setOwnerId(map.get("orgId").toString())
                        .setAllocationRatio(new BigDecimal(map.get("allocationRatio").toString())).setCpId(order.getCpId());
                if (Boolean.parseBoolean(map.get("ownerFlag").toString())) {
                    multiOwner.setOwnerType(Constant.OwnerType.Z_ORG.getName());
                } else {
                    multiOwner.setOwnerType(Constant.OwnerType.C_ORG.getName());
                }
                multiOwnerMapper.insert(multiOwner);
            }
        }

        // 业务员业绩保存
        if (orderVO.getStaffList() != null && orderVO.getStaffList().size() > 0) {
            for (Map<String, Object> map : orderVO.getStaffList()) {
                MultiOwner multiOwner = new MultiOwner();
                multiOwner.setOrderId(order.getOrderId()).setOwnerId(map.get("staffId").toString())
                        .setAllocationRatio(new BigDecimal(map.get("allocationRatio").toString())).setCpId(order.getCpId());
                if (Boolean.parseBoolean(map.get("ownerFlag").toString())) {
                    multiOwner.setOwnerType(Constant.OwnerType.Z_STAFF.getName());
                } else {
                    multiOwner.setOwnerType(Constant.OwnerType.C_STAFF.getName());
                }
                multiOwnerMapper.insert(multiOwner);
            }
        }
        // 更新总单
        super.update(order, new UpdateWrapper<Order>().lambda().eq(Order::getOrderId,
                UUID.fromString(order.getOrderId())));

        /**************************************** 客户收款begin ********************************/
        // 需要重新计算的资金账户
        List<String> macList = new ArrayList<>();
        // 收款明细
        RecPay recPayForUpdate = recPayMapper.selectByBiznisIdForUpdate(orderVO.getOrderId(), false);
        if (recPayForUpdate != null) {
            // 将之前的明细全部删除
            List<RecPayItem> recPayItemOriginalList = recPayItemMapper.selectByZIdForUpdate(recPayForUpdate.getRpId());
            for (RecPayItem recPayItem : recPayItemOriginalList) {
                // 删除收付款明细
                recPayItemMapper.deleteById(recPayItem.getItemId());
                // 删除账款明细
                accountItemMapper.deleteById(recPayItem.getAccItemId());
                // 删除账户流水
                moneyAccountItemMapper.deleteByInvoiceId(recPayItem.getItemId());

                if (!macList.contains(recPayItem.getMacId())) {
                    macList.add(recPayItem.getMacId());
                }
            }
        }


        // 专业版有定金
        if ("PRO".equals(gradeCode)) {
            if (orderVO.getReceiptList() != null && orderVO.getReceiptList().size() > 0) {
                // 计算订单明细的出库中数量，金额合计
                RecPayItemVO itemSum = orderVO.getReceiptList().stream().reduce((x, y) -> {
                    RecPayItemVO item = new RecPayItemVO();
                    item.setAmtRec(x.getAmtRec().add(y.getAmtRec()));
                    return item;
                }).get();

                RecPay recPay = null;
                if (recPayForUpdate == null) {
                    recPay = new RecPay();
                    // 获取单号
                    Map<String, Object> codeMap = commonService.getUniqueNoteCode(Constant.docNameConstant.RECPAY.getName(), false);
                    recPay.setRpId(codeMap.get("outId").toString()).setRpNo(codeMap.get("outNote").toString())
                            .setRpType(Constant.RpType.SHOU_KUAN.getName()).setObjectId(orderVO.getCusId())
                            .setOrgId(orderVO.getOrgId()).setStaffId(orderVO.getStaffId()).setAccDate(LocalDate.now())
                            .setBiznisType(Constant.InventoryDocCode.ORDER.getTableName()).setBiznisId(orderVO.getOrderId()).setBiznisNo(orderVO.getOrderNo())
                            .setMakeStaff(orderVO.getMakeStaff()).setCpId(orderVO.getCpId()).setFlgLock(true);

                    recPay.setSumAmtRec(itemSum.getAmtRec());
                    recPayMapper.insert(recPay);
                    recPayForUpdate = recPay;
                } else {
                    // 更新收款总额
                    RecPay recPayUpdate = new RecPay();
                    recPayUpdate.setSumAmtRec(itemSum.getAmtRec()).setRpId(recPayForUpdate.getRpId());
                    receiptService.updateByUuid(recPayUpdate);

                    // 赋值recPay，下面要用
                    recPay = recPayForUpdate;
                }

                // 明细保存
                for (RecPayItemVO recPayItemVO : orderVO.getReceiptList()) {
                    RecPayItem recPayItem = recPayItemConvert.convertToPo(recPayItemVO);
                    recPayItem.setItemId(null).setRpId(recPay.getRpId()).setCpId(recPay.getCpId()).setMakeStaff(recPay.getMakeStaff()).setAccDate(recPay.getAccDate());
                    recPayItemMapper.insert(recPayItem);

                    // 插入账款明细
                    AccountItem accountItem = new AccountItem();
                    accountItem.setAccItemType(Constant.accItemType.SHOU_KUAN.getName())
                            .setObjectId(recPay.getObjectId()).setOrgId(recPay.getOrgId()).setStaffId(recPay.getStaffId())
                            .setAccDate(recPay.getAccDate()).setRecStatus(Constant.recStatuse.QUE_DING.getName()).setAmtRec(recPayItem.getAmtRec())
                            .setBiznisType(Constant.InventoryDocCode.REC_PAY_ITEM.getTableName()).setBiznisId(recPayItem.getItemId()).setBiznisNo(recPay.getRpNo())
                            .setMakeStaff(recPay.getMakeStaff()).setCpId(recPay.getCpId()).setFlgLock(true);
                    accountItemMapper.insert(accountItem);

                    // 更新收款单上的账款明细Id
                    RecPayItem recPayItemUpdate = new RecPayItem();
                    recPayItemUpdate.setAccItemId(accountItem.getItemId()).setItemId(recPayItem.getItemId());
                    recPayItemService.updateByUuid(recPayItemUpdate);

                    // 插入资金流水
                    MoneyAccountItem moneyAccountItem = new MoneyAccountItem();
                    moneyAccountItem.setMacId(recPayItem.getMacId()).setFlowType(Constant.FlowType.SHOU_FU_KUAN.getName())
                            .setInvoiceId(recPayItem.getItemId()).setAmtInflow(recPayItem.getAmtRec()).setAccDate(recPay.getAccDate())
                            .setMakeStaff(recPayItem.getMakeStaff()).setCpId(recPayItem.getCpId());
                    moneyAccountItemMapper.insert(moneyAccountItem);

                    if (!macList.contains(recPayItem.getMacId())) {
                        macList.add(recPayItem.getMacId());
                    }
                }
            }
            if (recPayForUpdate != null) {
                // 更新总账表的锁定金额
                accountService.updateReceiptLock(recPayForUpdate.getObjectId());
            }
        } else if (Constant.GradeCode.STD.getName().equals(gradeCode)) {
            if (orderVO.getReceiptList() != null && orderVO.getReceiptList().size() > 0) {
                // 计算订单明细的出库中数量，金额合计
                RecPayItemVO itemSum = orderVO.getReceiptList().stream().reduce((x, y) -> {
                    RecPayItemVO item = new RecPayItemVO();
                    item.setAmtRec(x.getAmtRec().add(y.getAmtRec()));
                    return item;
                }).get();

                RecPay recPay = null;
                if (recPayForUpdate == null) {
                    recPay = new RecPay();
                    // 获取单号
                    Map<String, Object> codeMap = commonService.getUniqueNoteCode(Constant.docNameConstant.RECPAY.getName(), false);
                    recPay.setRpId(codeMap.get("outId").toString()).setRpNo(codeMap.get("outNote").toString())
                            .setRpType(Constant.RpType.SHOU_KUAN.getName()).setObjectId(orderVO.getCusId())
                            .setOrgId(orderVO.getOrgId()).setStaffId(orderVO.getStaffId()).setAccDate(LocalDate.now())
                            .setBiznisType(Constant.InventoryDocCode.ORDER.getTableName()).setBiznisId(orderVO.getOrderId()).setBiznisNo(orderVO.getOrderNo())
                            .setMakeStaff(orderVO.getMakeStaff()).setCpId(orderVO.getCpId());

                    recPay.setSumAmtRec(itemSum.getAmtRec());
                    recPayMapper.insert(recPay);
                    recPayForUpdate = recPay;
                } else {
                    // 更新收款总额
                    RecPay recPayUpdate = new RecPay();
                    recPayUpdate.setSumAmtRec(itemSum.getAmtRec()).setRpId(recPayForUpdate.getRpId());
                    receiptService.updateByUuid(recPayUpdate);

                    // 赋值recPay，下面要用
                    recPay = recPayForUpdate;
                }

                // 明细保存
                for (RecPayItemVO recPayItemVO : orderVO.getReceiptList()) {
                    RecPayItem recPayItem = recPayItemConvert.convertToPo(recPayItemVO);
                    recPayItem.setItemId(null).setRpId(recPay.getRpId()).setCpId(recPay.getCpId()).setMakeStaff(recPay.getMakeStaff()).setAccDate(recPay.getAccDate());
                    recPayItemMapper.insert(recPayItem);

                    // 插入账款明细
                    AccountItem accountItem = new AccountItem();
                    accountItem.setAccItemType(Constant.accItemType.SHOU_KUAN.getName())
                            .setObjectId(recPay.getObjectId()).setOrgId(recPay.getOrgId()).setStaffId(recPay.getStaffId())
                            .setAccDate(recPay.getAccDate()).setRecStatus(Constant.recStatuse.QUE_DING.getName()).setAmtRec(recPayItem.getAmtRec())
                            .setBiznisType(Constant.InventoryDocCode.REC_PAY_ITEM.getTableName()).setBiznisId(recPayItem.getItemId()).setBiznisNo(recPay.getRpNo())
                            .setMakeStaff(recPay.getMakeStaff()).setCpId(recPay.getCpId());
                    accountItemMapper.insert(accountItem);

                    // 更新收款单上的账款明细Id
                    RecPayItem recPayItemUpdate = new RecPayItem();
                    recPayItemUpdate.setAccItemId(accountItem.getItemId()).setItemId(recPayItem.getItemId());
                    recPayItemService.updateByUuid(recPayItemUpdate);

                    // 插入资金流水
                    MoneyAccountItem moneyAccountItem = new MoneyAccountItem();
                    moneyAccountItem.setMacId(recPayItem.getMacId()).setFlowType(Constant.FlowType.SHOU_FU_KUAN.getName())
                            .setInvoiceId(recPayItem.getItemId()).setAmtInflow(recPayItem.getAmtRec()).setAccDate(recPay.getAccDate())
                            .setMakeStaff(recPayItem.getMakeStaff()).setCpId(recPayItem.getCpId());
                    moneyAccountItemMapper.insert(moneyAccountItem);

                    if (!macList.contains(recPayItem.getMacId())) {
                        macList.add(recPayItem.getMacId());
                    }
                }
            }
            if (recPayForUpdate != null) {
                // 更新总账表的总收款额和可用额
                accountService.updateReceipt(recPayForUpdate.getObjectId());
            }
        }


        // 更新账户余额
        for (String macId : macList) {
            accountService.updateMac(macId);
        }
        /**************************************** 客户收款end ********************************/

        if (Constant.GradeCode.STD.getName().equals(gradeCode)) { //订单 转 出库数据
            // 合并两个列表
            List<OrderItemVO> combinedList = Stream.concat(insertOrderItemVOList.stream(), editOrderItemVOList.stream())
                    .collect(Collectors.toList());
            if (combinedList.size() > 0) { //编辑时新选的数据生成出库单
                //开单并出库办理
                if (orderVO.getOutboundProcessingFlag() != null && orderVO.getOutboundProcessingFlag()) {
                    //标准版 只有一个出库单  所以get0 就可以 且 编辑销售订单得时候 一定是有出库单的
                    List<OutboundResponse> outboundList = outboundMapper.selectByCond(new OutboundQuery().setFromId(orderVO.getOrderId()));
                    if (outboundList.size() > 0) { //有订单有出库单后续才编辑 没有就不用编辑
                        OutboundResponse outboundResponsejson = outboundList.get(0);
                        for (OrderItemVO orderItemVO : combinedList) {
                            //拿到 订单明细对应的出库明细   订单明细id 和 出库单来源明细 是一 一 对应的 所以 get0 也是不会有问题的
                            List<OutboundItemResponse> outboundItemList = outboundItemMapper.selectByCond(new OutboundItemQuery().setFromItemId(orderItemVO.getItemId()));
                            OutboundItemResponse outboundItemjson = null;
                            if (outboundItemList.size() != 0) { //没查到库存数据说明是新增的品 还没出库呢
                                outboundItemjson = outboundItemList.get(0);
                            }
                            orderItemVO.setOutingQty(orderItemVO.getItemQty());
                            orderItemVO.setOutingAmt(orderItemVO.getItemAmt());
                            orderItemVO.setFactAmt(orderItemVO.getItemAmt());
                            orderItemVO.setFactPrice(orderItemVO.getFactPrice());
                            orderItemVO.setPriceOut(orderItemVO.getFactPrice());
                            orderItemVO.setFromId(orderVO.getOrderId());
                            orderItemVO.setFromItemId(orderItemVO.getItemId());
                            orderItemVO.setOutId(outboundResponsejson.getOutId());
                            orderItemVO.setItemId(outboundItemjson == null ? null : outboundItemjson.getItemId());
                        }
                        if (orderVO.getDeleteItemList() != null) { //删除list
                            List<OrderItemVO> deleteOrderItemVOList = orderVO.getDeleteItemList().stream().filter(it -> it.getItemId() != null).collect(Collectors.toList());
                            if (deleteOrderItemVOList.size() > 0) {
                                for (OrderItemVO orderItemVO : deleteOrderItemVOList) {
                                    //拿到 订单明细对应的出库明细   订单明细id 和 出库单来源明细 是一 一 对应的 所以 get0 也是不会有问题的
                                    List<OutboundItemResponse> outboundItemList = outboundItemMapper.selectByCond(new OutboundItemQuery().setFromItemId(orderItemVO.getItemId()));
                                    OutboundItemResponse outboundItemjson = null;
                                    if (outboundItemList.size() != 0) { //没查到库存数据说明是新增的品 还没出库呢
                                        outboundItemjson = outboundItemList.get(0);
                                    }
                                    orderItemVO.setOutId(outboundResponsejson.getOutId());
                                    orderItemVO.setPriceOut(orderItemVO.getFactPrice());
                                    orderItemVO.setItemId(outboundItemjson == null ? null : outboundItemjson.getItemId());
                                }
                                orderVO.setDeleteItemList(deleteOrderItemVOList);
                            }
                        }
                        orderVO.setItemList(combinedList);
                        OutboundVO outboundVO = outBoundDtoConvert.convertToPo(orderVO);
                        outboundVO.setOutDate(LocalDate.now());
                        outboundVO.setOutingQty(orderVO.getSumQuantity());
                        outboundVO.setOutingAmt(orderVO.getFactAmt());
                        outboundVO.setFlgAutoHandle(orderVO.getFlgAutoHandle());
                        outboundVO.setFlgHandleSetting(orderVO.getFlgHandleSetting());
                        outboundVO.setFromId(order.getOrderId());
                        outboundVO.setFromNo(order.getOrderNo());
                        outboundVO.setOutDate(orderVO.getDeliveryDate());
                        outboundVO.setFactAmt(orderVO.getFactAmt());
                        outboundVO.setDiscount(orderVO.getDiscount());
                        outboundVO.setDiscAmt(orderVO.getDiscAmt());
                        outboundVO.setSumAmount(orderVO.getSumAmount());
                        outboundVO.setOutId(outboundResponsejson.getOutId());
                        outboundVO.setReceivableId(outboundResponsejson.getReceivableId());
                        outboundVO.setLimitEdit(true);
                        outboundSaleOrderService.saleOutboundUpdate(outboundVO);
                    }

                }
            }
        }
        return ResponseResultUtil.success();
    }

    /**
     * @desc : 作废
     * @author : 付斌
     * @date : 2024-03-08 16:38
     */
    public ResponseResultVO<?> invalid(String id) {
        Order orderForUpdate = orderMapper.selectByIdForUpdate(id);
        // 并发校验
        if (!orderForUpdate.getFlgValid()) {
            throw new BaseBusinessException(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.ISFLGVALID_FALSE.getMessage());
        }

        // 如果出库中数量或已出库数量不是0，不能作废
        if (orderForUpdate.getOutingQty().compareTo(BigDecimal.ZERO) != 0 || orderForUpdate.getOutQty().compareTo(BigDecimal.ZERO) != 0) {
            throw new BaseBusinessException(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.ISEXISTS_AFTER_OPERATE.getMessage());
        }
        // 作废
        Order orderUpdate = new Order();
        orderUpdate.setFlgValid(false).setOrderId(id);
        super.update(orderUpdate, new UpdateWrapper<Order>().lambda().eq(Order::getOrderId,
                UUID.fromString(orderUpdate.getOrderId())));


        // 需要重新计算的资金账户
        List<String> macList = new ArrayList<>();
        // 收款明细
        RecPay recPayForUpdate = recPayMapper.selectByBiznisIdForUpdate(id, false);
        if (recPayForUpdate != null) {
            // 将之前的明细全部删除
            List<RecPayItem> recPayItemOriginalList = recPayItemMapper.selectByZIdForUpdate(recPayForUpdate.getRpId());
            for (RecPayItem recPayItem : recPayItemOriginalList) {
                // 删除收付款明细 240627
//                recPayItemMapper.deleteById(recPayItem.getItemId());
                //            改为更新false
                RecPayItem recPayItemNew = new RecPayItem();
                recPayItemNew.setItemId(recPayItem.getItemId()).setFlgValid(false);
                recPayItemService.updateByUuid(recPayItemNew);
                // 删除账款明细
                accountItemMapper.deleteById(recPayItem.getAccItemId());
                // 删除账户流水
                moneyAccountItemMapper.deleteByInvoiceId(recPayItem.getItemId());

                if (!macList.contains(recPayItem.getMacId())) {
                    macList.add(recPayItem.getMacId());
                }
            }

            // 更新总账表的总收款额和可用额
            accountService.updateReceiptLock(recPayForUpdate.getObjectId());

            // 更新账户余额
            for (String macId : macList) {
                accountService.updateMac(macId);
            }

            // 作废
            RecPay recPayUpdate = new RecPay();
            recPayUpdate.setFlgValid(false).setRpId(recPayForUpdate.getRpId());
            receiptService.updateByUuid(recPayUpdate);
        }
        return ResponseResultUtil.success();
    }

    /**
     * @desc : 获取订单信息（编辑用）
     * @author : 付斌
     * @date : 2024-03-02 17:27
     */
    public ResponseResultVO<?> getOrderForUpdate(String id) {
        Map<String, Object> dataInfo = new HashMap<>();
        OrderResponse orderResponse = orderMapper.selectById(id);
        //查出订单对应的收款单
        List<RecPayResponse> RecPayResponseList = recPayMapper.selectByCond(new RecPayQuery().setBiznisId(id).setCpId(authUtils.getStaff().getCpId()));
        if (RecPayResponseList.size() > 0) { //因为收付款单要挂订单 只有在新建订单的时候才会挂 所以一张订单 对应一个收付款单
            RecPayResponse recPayResponse = RecPayResponseList.get(0);
            orderResponse.setSumAmtRec(recPayResponse.getSumAmtRec());
        }
        dataInfo.put("data", orderResponse);

        // 商品明细
        List<OrderItemResponse> orderItemResponse = orderItemMapper.selectByCond(new OrderItemQuery().setOrderId(id));
        dataInfo.put("dataItem", orderItemResponse);

        //查询主从业务员
        List<String> staffList = new ArrayList<>();
        staffList.add(Constant.OwnerType.Z_STAFF.getName());
        staffList.add(Constant.OwnerType.C_STAFF.getName());
        List<MultiOwnerResponse> multiOwnersStaff = multiOwnerMapper.selectByType(new MultiOwnerQuery().setOrderId(id).setOwnerTypes(staffList));
        if (multiOwnersStaff != null && multiOwnersStaff.size() > 0) {
            dataInfo.put("staffList", multiOwnersStaff);
        }
        //查询主从业务部门
        List<String> orgList = new ArrayList<>();
        orgList.add(Constant.OwnerType.Z_ORG.getName());
        orgList.add(Constant.OwnerType.C_ORG.getName());
        List<MultiOwnerResponse> multiOwnersOrg = multiOwnerMapper.selectByType(new MultiOwnerQuery().setOrderId(id).setOwnerTypes(orgList));
        if (multiOwnersOrg != null && multiOwnersOrg.size() > 0) {
            dataInfo.put("orgList", multiOwnersOrg);
        }

        // 获取实收金额
        Map<String, Object> mapFactReceipt = orderMapper.getFactReceipt(id);
        orderResponse.setAmtFactReceipt(new BigDecimal(mapFactReceipt.get("sumFactReceipt").toString()));

        // 收款明细
        List<RecPayResponse> recPayList = recPayMapper.selectByCond(new RecPayQuery().setBiznisId(id).setFlgOrderHandle(false));
        if (recPayList != null && recPayList.size() > 0) {
            // 如果有定金，实收金额加上定金
            if (recPayList.get(0).getFlgLock()) {
                orderResponse.setAmtFactReceipt(orderResponse.getAmtFactReceipt().add(recPayList.get(0).getSumAmtRec()));
            }
            List<RecPayItemResponse> receiptItem = recPayItemMapper.selectByCond(new RecPayItemQuery().setRpId(recPayList.get(0).getRpId()));
            dataInfo.put("receiptItem", receiptItem);
        } else {
            dataInfo.put("receiptItem", new ArrayList<RecPayResponse>());
        }
        return ResponseResultUtil.success(dataInfo);
    }

    /**
     * @desc : 获取订单信息（出库用）
     * @author : 付斌
     * @date : 2024-03-02 17:27
     */
    public ResponseResultVO<?> getOrderForOut(String id) {
        Map<String, Object> dataInfo = new HashMap<>();
        OrderResponse orderResponse = orderMapper.selectById(id);
        dataInfo.put("data", orderResponse);

        // 商品明细
        List<OrderItemResponse> orderItem = orderItemMapper.selectByCondForOut(new OrderItemQuery().setOrderId(id));
        dataInfo.put("dataItem", orderItem);
        return ResponseResultUtil.success(dataInfo);
    }

    /**
     * @desc : 获取订单信息（退货用）
     * @author : 付斌
     * @date : 2024-03-02 17:27
     */
    public ResponseResultVO<?> getOrderForReturn(String id) {
        Map<String, Object> dataInfo = new HashMap<>();
        OrderResponse orderResponse = orderMapper.selectById(id);
        // 数量金额取反
        orderResponse.setSumQuantity(orderResponse.getSumQuantity().negate()).setSumAmount(orderResponse.getSumAmount().negate());
        dataInfo.put("data", orderResponse);

        // 商品明细
        List<OrderItemResponse> orderItem = orderItemMapper.selectByCondForReturn(new OrderItemQuery().setOrderId(id));
        dataInfo.put("dataItem", orderItem);
        return ResponseResultUtil.success(dataInfo);
    }


    /**
     * @desc : 条件查询(总单带明细)
     * @author : 于继渤
     * @date : 2023/1/9 10:36
     */
    @Pagination
    public ResponseResultVO<PageList<OrderResponse>> selectTotalSingleTapeDetailPage(OrderQuery orderQuery) {
        return super.mergeListWithCount(orderQuery, orderMapper.selectByCondDetail(orderQuery),
                orderMapper.countByCondDetail(orderQuery));
    }

    /**
     * @desc : 销售跟踪报表
     * @author : 宋扬
     * @date : 2024/4/24 17:17
     */
    public ResponseResultVO<PageList> getOrderTrackReport(Map<String, Object> param) {
        // 获取组合商品
        Map<String, Object> map = orderMapper.getOrderTrackReport(param);
        JSONObject sku = JSONObject.parseObject(map.get("f_query_ord_for_track").toString());
        // 定义返回值
        PageList data = new PageList<>();
        List dataList = sku.get("data") != null ? JSONObject.parseArray(sku.get("data").toString()).toJavaList(Map.class) : new ArrayList();
        // 组装返回值
        data.setList(dataList);
        return ResponseResultUtil.success(data);
    }


    /**
     * @desc : 一键作废
     * @date : 2024/7/1 13:26
     * @author : 寇珊珊
     */

    public ResponseResultVO<?> oneKeyInvalid(String id) {
        //region  查询当前订单下是否存在有效的退货单
        Long count = outboundItemMapper.selectHasReturn(new OutboundItemQuery()
                .setSOrderId(id)
                .setFlgValid(true)
                .setOutType(Constant.OutType.SALE_RETURN.getName()));
        if (count != null && count > 0) {
            throw new BaseBusinessException(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.ORDER_IS_EXISTS_RETURN_ORDERS.getMessage());
        }
        //endregion

        Order orderForUpdate = orderMapper.selectByIdForUpdate(id);
        //region并发校验
        if (!orderForUpdate.getFlgValid()) {
            throw new BaseBusinessException(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.ISFLGVALID_FALSE.getMessage());
        }
        //endregion
        //region 作废
        Order orderUpdate = new Order();
        orderUpdate.setFlgValid(false).setOrderId(id);
        super.update(orderUpdate, new UpdateWrapper<Order>().lambda().eq(Order::getOrderId,
                UUID.fromString(orderUpdate.getOrderId())));
        //endregion

        //region  需要重新计算的资金账户
        List<String> macList = new ArrayList<>();
        // 收款明细
        RecPay recPayForUpdate = recPayMapper.selectByBiznisIdForUpdate(id, false);
        if (recPayForUpdate != null) {
            // 将之前的明细全部删除
            List<RecPayItem> recPayItemOriginalList = recPayItemMapper.selectByZIdForUpdate(recPayForUpdate.getRpId());
            for (RecPayItem recPayItem : recPayItemOriginalList) {
                //改为更新false
                RecPayItem recPayItemNew = new RecPayItem();
                recPayItemNew.setItemId(recPayItem.getItemId()).setFlgValid(false);
                recPayItemService.updateByUuid(recPayItemNew);
                // 删除账款明细
                accountItemMapper.deleteById(recPayItem.getAccItemId());
                // 删除账户流水
                moneyAccountItemMapper.deleteByInvoiceId(recPayItem.getItemId());

                if (!macList.contains(recPayItem.getMacId())) {
                    macList.add(recPayItem.getMacId());
                }
            }

            String gradeCode = authUtils.getStaff().getGradeCode();
            // 更新总账表的总收款额和可用额
            if (Constant.GradeCode.STD.getName().equals(gradeCode)) {
                accountService.updateReceipt(recPayForUpdate.getObjectId());
            } else {
                accountService.updateReceiptLock(recPayForUpdate.getObjectId());
            }

            // 更新账户余额
            for (String macId : macList) {
                accountService.updateMac(macId);
            }

            // 作废
            RecPay recPayUpdate = new RecPay();
            recPayUpdate.setFlgValid(false).setRpId(recPayForUpdate.getRpId());
            receiptService.updateByUuid(recPayUpdate);
        }
        //endregion

        //region 作废出库单
        outboundSaleOrderService.oneKeySaleOutboundRepeal(id);
        //endregion

        return ResponseResultUtil.success();
    }

    /**
     * @desc   : 以销定采web
     * @author : 姜宁
     * @date   : 2024/7/25 11:07
     */
    @Pagination
    public ResponseResultVO<PageList<Map<String, Object>>> purchaseBasedOnSales(Map<String, Object> param) {
        return super.mergeListWithCount(param, orderMapper.purchaseBasedOnSales(param),
                orderMapper.purchaseBasedOnSalesCountByCond(param));
    }
}
