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.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.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.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.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.mac.RecPayItemVO;
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.mac.AccountService;
import com.dk.mdm.service.mac.RecPayItemService;
import com.dk.mdm.service.mac.ReceiptService;
import com.dk.mdm.service.mst.MoneyAccountService;
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;

@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 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;

    /**
     * @desc : 条件查询
     * @author : 付斌
     * @date : 2023/1/9 10:40
     */
    @Pagination
    public ResponseResultVO<PageList<OrderResponse>> selectByCond(OrderQuery orderQuery) {
        return super.mergeListWithCount(orderQuery, orderMapper.selectByCond(orderQuery),
                orderMapper.countByCond(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();
            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())
                    .setReportStaff(orderVO.getMakeStaff()).setSaleStatus(Constant.SaleStatus.CHENGJIAO.getName()).setCpId(orderVO.getCpId());
            customerMapper.insert(customer);
            orderVO.setCusId(customer.getCusId());
        }

        // 获取单号
        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) {
            for (OrderItemVO orderItemVO : orderVO.getItemList()) {
                OrderItem orderItem = orderItemConvert.convertToPo(orderItemVO);
                orderItem.setOrderId(order.getOrderId()).setCpId(order.getCpId()).setOutStatus(Constant.OutStatus.DAICHUKU.getName());
                orderItemMapper.insert(orderItem);
            }
        }

        /**************************************** 客户收款begin ********************************/
        if (orderVO.getReceiptList() != null && orderVO.getReceiptList().size() > 0) {
            RecPay recPay = new RecPay();
            // 获取单号
            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);
            // 计算订单明细的出库中数量，金额合计
            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);
        }
        /**************************************** 客户收款end ********************************/
        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());
        }
        // 如果全部出库了
        if (orderForUpdate.getSumQuantity().compareTo(orderForUpdate.getOutQty()) == 0) {
            throw new BaseBusinessException(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.ORDER_IS_OUT.getMessage());
        }

        // 明细实体（避免并发，需要再查一遍）
        OrderItem orderItemForUpdate;
        // 转化实体
        Order order = orderConvert.convertToPo(orderVO);
        //删除的
        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());
                // 非待出库单据不能删除
                if (!Constant.OutStatus.DAICHUKU.getName().equals(orderItemForUpdate.getOutStatus())) {
                    throw new BaseBusinessException(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.NO_WAIT_INTO.getMessage());
                } else {
                    orderItemMapper.deleteById(orderItemVO.getItemId());
                }
            }
        }
        // 新增的
        List<OrderItemVO> insertOrderItemVOList = orderVO.getItemList().stream().filter(it -> it.getItemId() == null).collect(Collectors.toList());
        for (OrderItemVO orderItemVO : insertOrderItemVOList) {
            OrderItem orderItem = orderItemConvert.convertToPo(orderItemVO);
            orderItem.setOrderId(order.getOrderId()).setCpId(order.getCpId()).setOutStatus(Constant.OutStatus.DAICHUKU.getName());
            orderItemMapper.insert(orderItem);
        }
        // 编辑的
        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 (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.getWhId().equals(orderItemVO.getWhId())) {
                    throw new BaseBusinessException(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.ORDER_ISOUT.getMessage());
                }
            }
            OrderItem orderItem = orderItemConvert.convertToPo(orderItemVO);
            orderItemService.updateByUuid(orderItem);
        }

        // 删除业绩信息
        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 (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);
            } 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());
        }

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

        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) {
                // 删除收付款明细
                recPayItemMapper.deleteById(recPayItem.getItemId());
                // 删除账款明细
                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(id);
            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);
        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);
    }

}
