package com.yiqi.order.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import cn.binarywang.wx.miniapp.bean.express.result.WxMaExpressOrderInfoResult;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yiqi.common.exception.ServiceException;
import com.yiqi.common.core.domain.entity.SysUser;
import com.yiqi.common.enums.*;
import com.yiqi.common.exception.GlobalException;
import com.yiqi.common.utils.DateUtils;
import com.yiqi.common.utils.OrderNoUtils;
import com.yiqi.common.utils.SecurityUtils;
import com.yiqi.core.domain.GoodsInfo;
import com.yiqi.core.domain.GoodsSkuStore;
import com.yiqi.core.domain.dto.GoodsSkuStockRecordDTO;
import com.yiqi.core.service.*;
import com.yiqi.order.domain.*;
import com.yiqi.order.domain.dto.*;
import com.yiqi.order.domain.vo.OrderDeliveryPathVO;
import com.yiqi.order.domain.vo.OrderPurchaseGoodsInfoVO;
import com.yiqi.order.domain.vo.OrderPurchaseGoodsVO;
import com.yiqi.order.domain.vo.OrderSellGoodsListVO;
import com.yiqi.order.service.IOrderPurchaseGoodsSkuService;
import com.yiqi.order.service.IThirdDeliveryService;
import com.yiqi.system.domain.ManageFactory;
import com.yiqi.system.domain.SysStore;
import com.yiqi.system.service.IManageFactoryService;
import com.yiqi.system.service.ISysStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yiqi.order.mapper.OrderPurchaseGoodsMapper;
import com.yiqi.order.service.IOrderPurchaseGoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品订单Service业务层处理
 *
 * @author ruoyi
 * @date 2023-10-17
 */
@Service
public class OrderPurchaseGoodsServiceImpl extends ServiceImpl<OrderPurchaseGoodsMapper, OrderPurchaseGoods> implements IOrderPurchaseGoodsService {
    @Autowired
    IOrderPurchaseGoodsSkuService orderPurchaseGoodsSkuService;
    @Autowired
    private IGoodsInfoService goodsInfoService;
    @Autowired
    ISysStoreService sysStoreService;
    @Autowired
    private ISettlementBalanceRecordService settlementBalanceRecordService;
    @Autowired
    IManageFactoryService manageFactoryService;
    @Autowired
    private OrderNoUtils orderNoUtils;
    @Autowired
    private IGoodsSkuStoreService goodsSkuStoreService;
    @Autowired
    private IGoodsSkuService goodsSkuService;
    @Autowired
    private IGoodsSkuStockRecordService goodsSkuStockRecordService;
    @Autowired
    private IThirdDeliveryService thirdDeliveryService;

    /**
     * 查询商品订单
     *
     * @param id 商品订单主键
     * @return 商品订单
     */
    @Override
    public List<OrderPurchaseGoodsVO> selectOrderPurchaseGoodsById(Long id) {
        return baseMapper.selectOrderPurchaseGoodsById(id);
    }

    /**
     * 修改商品订单
     *
     * @param orderPurchaseGoods 商品订单
     * @return 结果
     */
    @Override
    public int updateOrderPurchaseGoods(OrderPurchaseGoods orderPurchaseGoods) {
        orderPurchaseGoods.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateOrderPurchaseGoods(orderPurchaseGoods);
    }

    /**
     * 批量删除商品订单
     *
     * @param ids 需要删除的商品订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderPurchaseGoodsByIds(Long[] ids) {
        return baseMapper.deleteOrderPurchaseGoodsByIds(ids);
    }

    /**
     * 删除商品订单信息
     *
     * @param id 商品订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderPurchaseGoodsById(Long id) {
        return baseMapper.deleteOrderPurchaseGoodsById(id);
    }


    /**
     * 查询商品订单列表
     *
     * @param orderPurchaseGoods 商品订单
     * @return 商品订单
     */
    @Override
    public List<OrderPurchaseGoods> selectOrderPurchaseGoodsList(OrderPurchaseGoods orderPurchaseGoods) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        orderPurchaseGoods.setSourceType(user.getUserType());
        orderPurchaseGoods.setOrgId(SourceType.STORE.getCode().equals(user.getUserType()) ? user.getStoreId() : user.getFactoryId());
        return baseMapper.selectOrderPurchaseGoodsList(orderPurchaseGoods);
    }

    //<editor-folder desc="进/出货接口">


    /**
     * 查询订单物流轨迹
     */
    @Override
    public OrderDeliveryPathVO getDeliveryPath(Long orderId) throws Exception {
        OrderPurchaseGoods orderPurchaseGoods = baseMapper.selectById(orderId);
        if (orderPurchaseGoods == null) {
            throw new GlobalException("订单不存在");
        }
        return thirdDeliveryService.getDeliveryPath(OrderThirdDeliveryPathDTO.buildDeliveryPathByPurchaseGoodsOrder(orderPurchaseGoods));
    }

    /**
     * 商品出货订单列表
     *
     * @param orderPurchaseGoodsQueryDTO 商品订单
     * @return 商品订单
     */
    @Override
    public List<OrderSellGoodsListVO> sellGoodsList(OrderPurchaseGoodsQueryDTO orderPurchaseGoodsQueryDTO) {
        orderPurchaseGoodsQueryDTO.setParentSourceType(SecurityUtils.getLoginUser().getSourceType());
        List<OrderSellGoodsListVO> VOList = null;
        // 工厂查询门店的订单
        if (SourceType.FACTORY.getCode().equals(SecurityUtils.getLoginUser().getSourceType())) {
            // 传参中，带了orgId， 说明工厂想查某一家店的订单，所以把SourceType加上门店的，配合传的orgId,就能查出来了
            if (StrUtil.isNotEmpty(String.valueOf(orderPurchaseGoodsQueryDTO.getOrgId()))) {
                orderPurchaseGoodsQueryDTO.setSourceType(SourceType.STORE.getCode());
            }
            // 不传orgId， 就是查父级是该工厂的全部门店订单
            orderPurchaseGoodsQueryDTO.setParentOrgId(SecurityUtils.getLoginUser().getOrgId());
            VOList = baseMapper.sellGoodsListByFactory(orderPurchaseGoodsQueryDTO);
        }
        // 总部查询工厂的订单
        if (SourceType.MANAGER.getCode().equals(SecurityUtils.getLoginUser().getSourceType())) {
            // 传参中，带了orgId， 说明总部想查某一家工厂的订单，所以把SourceType加上工厂的，配合传的orgId,就能查出来了
            if (StrUtil.isNotEmpty(String.valueOf(orderPurchaseGoodsQueryDTO.getOrgId()))) {
                orderPurchaseGoodsQueryDTO.setSourceType(SourceType.FACTORY.getCode());
            }
            VOList = baseMapper.sellGoodsListByHq(orderPurchaseGoodsQueryDTO);
        }
        return VOList;
    }

    @Override
    public List<OrderSellGoodsListVO> sellGoodsListByHqFactory(OrderPurchaseGoodsQueryDTO orderPurchaseGoodsQueryDTO) {
        // 总部还需要单独显示  总部工厂的门店订单
        OrderPurchaseGoods purchaseGoods2HQFactory = new OrderPurchaseGoods();
        purchaseGoods2HQFactory.setParentOrgId(Long.valueOf(SourceType.HQ_FACTORY.getCode()));
        purchaseGoods2HQFactory.setParentSourceType(SourceType.FACTORY.getCode());
        if (StrUtil.isNotEmpty(String.valueOf(orderPurchaseGoodsQueryDTO.getOrgId()))) {
            orderPurchaseGoodsQueryDTO.setSourceType(SourceType.STORE.getCode());
        }
        return baseMapper.sellGoodsListByFactory(orderPurchaseGoodsQueryDTO);
    }

    /**
     * 商品出货-接单
     *
     * @param orderId 商品订单id
     * @return 结果
     */
    @Override
    public int confirmOrder(Long orderId) {
        OrderPurchaseGoods orderPurchaseGoods = baseMapper.selectById(orderId);
        if (orderPurchaseGoods == null) {
            throw new GlobalException("订单不存在");
        }
        if (!purchaseGoodsStatusType.CONFIRM_PAY.getCode().equals(orderPurchaseGoods.getOrderStatus())) {
            throw new GlobalException("订单状态非待确认，无法接单");
        }
        orderPurchaseGoods.setPayTime(DateUtils.getNowDate());
        orderPurchaseGoods.setOrderStatus(purchaseGoodsStatusType.NO_SEND.getCode());
        orderPurchaseGoods.buildUpdateData();
        return baseMapper.updateById(orderPurchaseGoods);
    }

    /**
     * 商品出货-拒单
     *
     * @param orderId 商品订单id
     * @return 结果
     */
    @Override
    public int refuseOrder(Long orderId) {
        OrderPurchaseGoods orderPurchaseGoods = baseMapper.selectById(orderId);
        if (orderPurchaseGoods == null) {
            throw new GlobalException("订单不存在");
        }
        if (!purchaseGoodsStatusType.CONFIRM_PAY.getCode().equals(orderPurchaseGoods.getOrderStatus())) {
            throw new GlobalException("订单状态非待确认，无法拒单");
        }
        if (purchaseGoodsStatusType.REFUSE.getCode().equals(orderPurchaseGoods.getOrderStatus())) {
            throw new GlobalException("订单状态已拒单");
        }
        // 更新订单状态
        orderPurchaseGoods.setOrderStatus(purchaseGoodsStatusType.REFUSE.getCode());
        orderPurchaseGoods.buildUpdateData();
//        // 如果勾选了使用抵扣金额，则退回余额
//        if (GoodsType.MATERIAL.getCode().equals(orderPurchaseGoods.getGoodsType()) && SysBoolType.YES.getCode().equals(orderPurchaseGoods.getIsUseBalance())) {
//            this.handleRefundBalanceDeductAmount(orderPurchaseGoods);
//            // 保存记录
//            SettlementBalanceRecord settlementBalanceRecord = SettlementBalanceRecord.buildRefundBalanceRecordByPurchaseOrder(orderPurchaseGoods);
//            settlementBalanceRecordService.save(settlementBalanceRecord);
//        }
        return baseMapper.updateById(orderPurchaseGoods);
    }


    /**
     * 商品出货-取消订单
     *
     * @param orderId 商品订单id
     * @return 结果
     */
    @Override
    public int cancelOrderGoods(Long orderId) {
        OrderPurchaseGoods orderPurchaseGoods = baseMapper.selectById(orderId);
        if (orderPurchaseGoods == null) {
            throw new GlobalException("订单不存在");
        }
        if (!purchaseGoodsStatusType.NO_PAY.getCode().equals(orderPurchaseGoods.getOrderStatus())
                || !purchaseGoodsStatusType.CONFIRM_PAY.getCode().equals(orderPurchaseGoods.getOrderStatus())) {
            throw new GlobalException("订单状态已接单，无法操作取消订单");
        }
        if (purchaseGoodsStatusType.CANCEL_ORDER.getCode().equals(orderPurchaseGoods.getOrderStatus())) {
            throw new GlobalException("订单状态已取消");
        }
        // 更新订单状态
        orderPurchaseGoods.setOrderStatus(purchaseGoodsStatusType.CANCEL_ORDER.getCode());
        orderPurchaseGoods.buildUpdateData();

        // 如果勾选了使用抵扣金额，则退回余额
//        if (GoodsType.MATERIAL.getCode().equals(orderPurchaseGoods.getGoodsType()) && SysBoolType.YES.getCode().equals(orderPurchaseGoods.getIsUseBalance())) {
//            this.handleRefundBalanceDeductAmount(orderPurchaseGoods);
//            // 保存记录
//            SettlementBalanceRecord settlementBalanceRecord = SettlementBalanceRecord.buildRefundBalanceRecordByPurchaseOrder(orderPurchaseGoods);
//            settlementBalanceRecordService.save(settlementBalanceRecord);
//        }
        return baseMapper.updateById(orderPurchaseGoods);
    }

    /**
     * 商品出货-出货
     *
     * @param orderGoodsOutGoodsDTO 商品订单id
     * @param deliveryWay
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int outOrderGoods(OrderGoodsOutGoodsDTO orderGoodsOutGoodsDTO, String deliveryWay) throws Exception {
        OrderPurchaseGoods orderPurchaseGoods = baseMapper.selectById(orderGoodsOutGoodsDTO.getOrderId());
        if (orderPurchaseGoods == null) {
            throw new GlobalException("订单不存在");
        }
        if (!purchaseGoodsStatusType.NO_SEND.getCode().equals(orderPurchaseGoods.getOrderStatus())) {
            throw new GlobalException("订单状态不符合，无法出货");
        }
        // 校验操作权限
        if (!this.checkActionByOutOrder(orderPurchaseGoods)) {
            throw new GlobalException("操作人没有出货权限，无法出货");
        }
        // 查询本次订单内容
        List<OrderPurchaseGoodsSku> orderPurchaseGoodsSkus = orderPurchaseGoodsSkuService.list(new QueryWrapper<OrderPurchaseGoodsSku>().lambda()
                .eq(OrderPurchaseGoodsSku::getOrderId, orderPurchaseGoods.getId()));
        if (CollUtil.isEmpty(orderPurchaseGoodsSkus)) {
            throw new GlobalException("未查询到订单进货商品信息，无法出货");
        }
        //扣减总部库存
        goodsSkuService.addOrMinusGoodsSkuStockByPurchase(0, orderPurchaseGoodsSkus);
        // 库存记录
        this.buildStockRecord(orderPurchaseGoods, orderPurchaseGoodsSkus, Boolean.FALSE, Boolean.FALSE);
        //  自己配送
        if (DeliveryWayType.SELF_SEND.getCode().equals(deliveryWay)) {
            orderPurchaseGoods.setDeliveryWay(DeliveryWayType.SELF_SEND.getCode());
            orderPurchaseGoods.setOrderStatus(purchaseGoodsStatusType.SENDING.getCode());
            orderPurchaseGoods.setSendTime(DateUtils.getNowDate());
            orderPurchaseGoods.buildUpdateData();
            return baseMapper.updateById(orderPurchaseGoods);
        }

        // 获取快递信息-商品信息
        List<GoodsInfo> goodsInfoList = this.getGoodsInfoListByOrderPurchase(orderPurchaseGoods);
        // 获取快递信息-发送人信息
        DeliveryOrgInfoDTO deliveryOrgInfoDTOBySender = this.getOrgInfoByOrderPurchase(orderPurchaseGoods.getParentOrgId(), orderPurchaseGoods.getParentSourceType());
        // 获取快递信息-收件人信息
        DeliveryOrgInfoDTO deliveryOrgInfoDTOByReceiver = this.getOrgInfoByOrderPurchase(orderPurchaseGoods.getOrgId(), orderPurchaseGoods.getSourceType());
        // 生成快递订单
        WxMaExpressOrderInfoResult result = thirdDeliveryService.addDeliveryOrder(OrderThirdDeliveryAddDTO.buildDeliveryOrderByPurchaseGoodsOrder(orderPurchaseGoods, orderGoodsOutGoodsDTO, goodsInfoList, deliveryOrgInfoDTOBySender, deliveryOrgInfoDTOByReceiver));
        if (result != null) {
            orderPurchaseGoods.setDeliveryNo(result.getWaybillId());
        }
        orderPurchaseGoods.setDeliveryWay(DeliveryWayType.DELIVERY.getCode());
        orderPurchaseGoods.setOrderStatus(purchaseGoodsStatusType.SENDING.getCode());
        orderPurchaseGoods.setDeliveryCompany(orderGoodsOutGoodsDTO.getDeliveryCompany());
        orderPurchaseGoods.setDeliveryId(orderGoodsOutGoodsDTO.getDeliveryId());
        orderPurchaseGoods.setSendTime(DateUtils.getNowDate());
        orderPurchaseGoods.buildUpdateData();
        return baseMapper.updateById(orderPurchaseGoods);
    }

    private DeliveryOrgInfoDTO getOrgInfoByOrderPurchase(Long orgId, String sourceType) {
        DeliveryOrgInfoDTO deliveryOrgInfoDTO = new DeliveryOrgInfoDTO();
        if (SourceType.STORE.getCode().equals(sourceType)) {
            SysStore store = sysStoreService.getOne(new QueryWrapper<SysStore>().lambda().eq(SysStore::getId, orgId));
            deliveryOrgInfoDTO = DeliveryOrgInfoDTO.buildDeliveryOrgInfoDTOByStore(store);
        }
        if (SourceType.FACTORY.getCode().equals(sourceType)) {
            ManageFactory factory = manageFactoryService.getOne(new QueryWrapper<ManageFactory>().lambda().eq(ManageFactory::getId, orgId));
            deliveryOrgInfoDTO = DeliveryOrgInfoDTO.buildDeliveryOrgInfoDTOByFactory(factory);
        }
        if (SourceType.MANAGER.getCode().equals(sourceType)) {
            deliveryOrgInfoDTO = DeliveryOrgInfoDTO.buildDeliveryOrgInfoDTOByHq();
        }
        return deliveryOrgInfoDTO;
    }

    private List<GoodsInfo> getGoodsInfoListByOrderPurchase(OrderPurchaseGoods orderPurchaseGoods) {
        List<OrderPurchaseGoodsSku> purchaseGoodsItems = orderPurchaseGoodsSkuService.list(new QueryWrapper<OrderPurchaseGoodsSku>().lambda()
                .eq(OrderPurchaseGoodsSku::getOrderId, orderPurchaseGoods.getId()));
        List<Long> goodIdList = new ArrayList<>(purchaseGoodsItems.stream().collect(Collectors.groupingBy(OrderPurchaseGoodsSku::getGoodsId)).keySet());
        return goodsInfoService.list(new QueryWrapper<GoodsInfo>().lambda().in(GoodsInfo::getId, goodIdList));
    }

    /**
     * 检查操作权限- 出货校验
     */
    private Boolean checkActionByOutOrder(OrderPurchaseGoods orderPurchaseGoods) {
        // 总部操作
        if (SourceType.MANAGER.getCode().equals(SecurityUtils.getLoginUser().getSourceType())) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    /**
     * 快递签收成功后，处理订单
     *
     * @param orderNo
     */
    @Override
    public void handleDeliverySuccessUpdateOrderStatus(String orderNo) {
        OrderPurchaseGoods orderPurchaseGoods = this.getOne(new QueryWrapper<OrderPurchaseGoods>().lambda().eq(OrderPurchaseGoods::getOrderNo, orderNo));
        if (orderPurchaseGoods == null) {
            throw new ServiceException("进货商品订单不存在," + orderNo);
        }
        if (purchaseGoodsStatusType.CONFIRM_RECEIVE.getCode().equals(orderPurchaseGoods.getOrderStatus())) {
            log.debug("该订单已完成，无需处理， 订单编号：" + orderNo);
            return;
        }
        if (!purchaseGoodsStatusType.SENDING.getCode().equals(orderPurchaseGoods.getOrderStatus())) {
            log.debug("该订单不是配送中，无法操作签收， 订单编号：" + orderNo);
            return;
        }
        // 查询订单内容
        List<OrderPurchaseGoodsSku> orderPurchaseGoodsSkus = orderPurchaseGoodsSkuService.list(new QueryWrapper<OrderPurchaseGoodsSku>().lambda()
                .eq(OrderPurchaseGoodsSku::getOrderId, orderPurchaseGoods.getId()));
        // 加上下级库存
        List<GoodsSkuStore> goodsSkuStoreList = goodsSkuStoreService.buildGoodsSkuStockVOByPurchase2AddStock(orderPurchaseGoodsSkus, orderPurchaseGoods);
        goodsSkuStoreService.addGoodsSkuStockByOrderItems(goodsSkuStoreList);
        // 库存记录
        this.buildStockRecord(orderPurchaseGoods, orderPurchaseGoodsSkus, Boolean.TRUE, Boolean.FALSE);
        orderPurchaseGoods.setOrderStatus(purchaseGoodsStatusType.CONFIRM_RECEIVE.getCode());
        orderPurchaseGoods.setFinishTime(DateUtils.getNowDate());
        orderPurchaseGoods.buildUpdateData();
        this.updateById(orderPurchaseGoods);
    }

    /**
     * 商品确认收货
     *
     * @param orderId 商品订单id
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int confirmReceiveGoodsByOrderGoods(Long orderId) {
        OrderPurchaseGoods orderPurchaseGoods = baseMapper.selectById(orderId);
        if (orderPurchaseGoods == null) {
            throw new GlobalException("订单不存在");
        }
        if (purchaseGoodsStatusType.NO_PAY.getCode().equals(orderPurchaseGoods.getOrderStatus())) {
            throw new GlobalException("该订单未支付，无法确认收货");
        }
        if (purchaseGoodsStatusType.CONFIRM_PAY.getCode().equals(orderPurchaseGoods.getOrderStatus())) {
            throw new GlobalException("该订单未接单，无法确认收货");
        }
        if (purchaseGoodsStatusType.NO_SEND.getCode().equals(orderPurchaseGoods.getOrderStatus())) {
            throw new GlobalException("该订单未配送，无法确认收货");
        }
        if (purchaseGoodsStatusType.REFUSE.getCode().equals(orderPurchaseGoods.getOrderStatus())) {
            throw new GlobalException("该订单已拒单，无法确认收货");
        }
        if (purchaseGoodsStatusType.CANCEL_ORDER.getCode().equals(orderPurchaseGoods.getOrderStatus())) {
            throw new GlobalException("该订单已取消，无法确认收货");
        }
        if (purchaseGoodsStatusType.CONFIRM_RECEIVE.getCode().equals(orderPurchaseGoods.getOrderStatus())) {
            throw new GlobalException("该订单已完成");
        }
        // 查询订单内容
        List<OrderPurchaseGoodsSku> orderPurchaseGoodsSkus = orderPurchaseGoodsSkuService.list(new QueryWrapper<OrderPurchaseGoodsSku>().lambda()
                .eq(OrderPurchaseGoodsSku::getOrderId, orderPurchaseGoods.getId()));
        // 加上下级库存
        List<GoodsSkuStore> goodsSkuStoreList = goodsSkuStoreService.buildGoodsSkuStockVOByPurchase2AddStock(orderPurchaseGoodsSkus, orderPurchaseGoods);
        goodsSkuStoreService.addGoodsSkuStockByOrderItems(goodsSkuStoreList);
        // 库存记录
        this.buildStockRecord(orderPurchaseGoods, orderPurchaseGoodsSkus, Boolean.TRUE, Boolean.FALSE);

        // 更新订单状态
        orderPurchaseGoods.setOrderStatus(purchaseGoodsStatusType.CONFIRM_RECEIVE.getCode());
        orderPurchaseGoods.setFinishTime(DateUtils.getNowDate());
        orderPurchaseGoods.buildUpdateData();
        return baseMapper.updateById(orderPurchaseGoods);
    }

    /**
     * 新增商品进货订单
     *
     * @param orderPurchaseGoodsAddDTO 商品订单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertOrderPurchaseGoods(OrderPurchaseGoodsAddDTO orderPurchaseGoodsAddDTO) {
        // 保存进货订单
        OrderPurchaseGoods orderPurchaseGoods = this.buildOrderPurchaseGoodsInfo(orderPurchaseGoodsAddDTO);

        // 总部进货-直接加库存
        if (SourceType.MANAGER.getCode().equals(orderPurchaseGoods.getSourceType())) {
            // 查询本次订单内容
            List<OrderPurchaseGoodsSku> orderPurchaseGoodsSkus = orderPurchaseGoodsSkuService.list(new QueryWrapper<OrderPurchaseGoodsSku>().lambda()
                    .eq(OrderPurchaseGoodsSku::getOrderId, orderPurchaseGoods.getId()));
            goodsSkuService.addOrMinusGoodsSkuStockByPurchase(1, orderPurchaseGoodsSkus);
            // 库存记录
            this.buildStockRecord(orderPurchaseGoods, orderPurchaseGoodsSkus, Boolean.TRUE, Boolean.FALSE);
        }

        return 1;
    }

    /**
     * 进出货 - 组装库存记录list
     *
     * @param orderPurchaseGoods
     * @param orderPurchaseGoodsSkus
     * @param isAdd
     * @param isRefund
     */
    private void buildStockRecord(OrderPurchaseGoods orderPurchaseGoods, List<OrderPurchaseGoodsSku> orderPurchaseGoodsSkus, Boolean isAdd, Boolean isRefund) {
        goodsSkuStockRecordService.saveBatch(GoodsSkuStockRecordDTO.buildStockByOrderPurchaseGoods(orderPurchaseGoods, orderPurchaseGoodsSkus, isAdd, isRefund));
    }


    /**
     * 保存进货订单
     *
     * @param orderPurchaseGoodsAddDTO
     * @return
     */
    private OrderPurchaseGoods buildOrderPurchaseGoodsInfo(OrderPurchaseGoodsAddDTO orderPurchaseGoodsAddDTO) {
        List<OrderPurchaseGoodsVO> purchaseGoodsVOList = orderPurchaseGoodsAddDTO.getPurchaseGoodsVOList();
        if (CollUtil.isEmpty(purchaseGoodsVOList)) {
            throw new GlobalException("操作失败,商品信息为空");
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 保存订单
        OrderPurchaseGoods orderPurchaseGoods = new OrderPurchaseGoods();
        orderPurchaseGoods.setSourceType(user.getUserType());
        // 设置组织id
        if (!SourceType.MANAGER.getCode().equals(user.getUserType())) {
            orderPurchaseGoods.setOrderStatus(purchaseGoodsStatusType.CONFIRM_PAY.getCode());
            orderPurchaseGoods.setOrgId(SourceType.STORE.getCode().equals(user.getUserType()) ? user.getStoreId() : user.getFactoryId());
        } else {
            orderPurchaseGoods.setOrderStatus(purchaseGoodsStatusType.CONFIRM_RECEIVE.getCode());
            orderPurchaseGoods.setSendTime(DateUtils.getNowDate());
            orderPurchaseGoods.setFinishTime(DateUtils.getNowDate());
        }

        orderPurchaseGoods.setGoodsType(orderPurchaseGoodsAddDTO.getGoodsType());
        orderPurchaseGoods.setCostTotalPrice(orderPurchaseGoodsAddDTO.getCostTotalPrice());
//        orderPurchaseGoods.setDeliveryWay(DeliveryWayType.DELIVERY.getCode());
        orderPurchaseGoods.setPayType(PayType.CASH.getCode());
        orderPurchaseGoods.setPayTime(DateUtils.getNowDate());
        orderPurchaseGoods.setDelFlag(UserStatus.OK.getCode());
        orderPurchaseGoods.setCreateBy(user.getCreateBy());
        orderPurchaseGoods.setCreateTime(DateUtils.getNowDate());
        orderPurchaseGoods.setCreateById(user.getUserId());
        // 生成订单编号
        orderPurchaseGoods.setOrderNo(orderNoUtils.getPurchaseOrderNo());
        orderPurchaseGoods.setIsUseBalance(SysBoolType.NO.getCode());
        this.save(orderPurchaseGoods);

        // 无法批量插入
        for (OrderPurchaseGoodsVO orderPurchaseGoodsVO : purchaseGoodsVOList) {
            OrderPurchaseGoodsSku orderPurchaseGoodsSku = new OrderPurchaseGoodsSku();
            orderPurchaseGoodsSku.setOrderId(orderPurchaseGoods.getId());
            orderPurchaseGoodsSku.setBuyNum(orderPurchaseGoodsVO.getBuyNum());
            orderPurchaseGoodsSku.setCostPrice(orderPurchaseGoodsVO.getCostPrice());
            orderPurchaseGoodsSku.setSkuName(orderPurchaseGoodsVO.getSkuName());
            orderPurchaseGoodsSku.setSkuId(orderPurchaseGoodsVO.getSkuId());
            orderPurchaseGoodsSku.setGoodsName(orderPurchaseGoodsVO.getGoodsName());
            orderPurchaseGoodsSku.setGoodsId(orderPurchaseGoodsVO.getGoodsId());
            orderPurchaseGoodsSku.setCreateBy(user.getCreateBy());
            orderPurchaseGoodsSku.setCreateTime(DateUtils.getNowDate());
            orderPurchaseGoodsSku.setCreateById(user.getUserId());
            orderPurchaseGoodsSkuService.save(orderPurchaseGoodsSku);
        }
        return orderPurchaseGoods;
    }

    private void handleSetBalanceDeductAmount(OrderPurchaseGoods orderPurchaseGoods) {
        BigDecimal balance = BigDecimal.ZERO;
        if (SourceType.FACTORY.getCode().equals(SecurityUtils.getLoginUser().getSourceType())) {
            ManageFactory manageFactory = manageFactoryService.getById(SecurityUtils.getLoginUser().getUser().getFactoryId());
            if (manageFactory == null) {
                throw new ServiceException("该工厂不存在，无法进货");
            }
            balance = manageFactory.getBalance() == null ? BigDecimal.ZERO : manageFactory.getBalance();
        }
        if (SourceType.STORE.getCode().equals(SecurityUtils.getLoginUser().getSourceType())) {
            SysStore store = sysStoreService.getById(SecurityUtils.getLoginUser().getUser().getStoreId());
            if (store == null) {
                throw new ServiceException("该门店不存在，无法进货");
            }
            balance = store.getMaterialBalance() == null ? BigDecimal.ZERO : store.getMaterialBalance();
        }
//        BigDecimal lastBalance = BigDecimal.ZERO;
//        if (BigDecimal.ZERO.equals(balance)) {
//            // 余额为0 ，所以抵扣金额=0
//            orderPurchaseGoods.setBalanceDeductAmount(BigDecimal.ZERO);
//            return;
//        } else if (balance.compareTo(orderPurchaseGoods.getCostTotalPrice()) < 0) {
//            // 余额 小于 订单金额， 余额全部抵扣
//            orderPurchaseGoods.setBalanceDeductAmount(balance);
//        } else {
//            // 余额 大于等于 订单金额， 订单金额全部抵扣
//            orderPurchaseGoods.setBalanceDeductAmount(orderPurchaseGoods.getCostTotalPrice());
//            lastBalance = balance.subtract(orderPurchaseGoods.getCostTotalPrice());
//        }
//        // 更新工厂余额
//        if (SourceType.FACTORY.getCode().equals(SecurityUtils.getLoginUser().getSourceType())) {
//            manageFactoryService.update(new UpdateWrapper<ManageFactory>().lambda()
//                    .eq(ManageFactory::getId, SecurityUtils.getLoginUser().getUser().getFactoryId())
//                    .set(ManageFactory::getBalance, lastBalance));
//        }
//        // 更新门店余额
//        if (SourceType.STORE.getCode().equals(SecurityUtils.getLoginUser().getSourceType())) {
//            sysStoreService.update(new UpdateWrapper<SysStore>().lambda()
//                    .eq(SysStore::getId, SecurityUtils.getLoginUser().getUser().getStoreId())
//                    .set(SysStore::getMaterialBalance, lastBalance));
//        }

    }

    private void handleRefundBalanceDeductAmount(OrderPurchaseGoods orderPurchaseGoods) {
        if (SourceType.FACTORY.getCode().equals(orderPurchaseGoods.getSourceType())) {
            manageFactoryService.update(new UpdateWrapper<ManageFactory>().lambda()
                    .eq(ManageFactory::getId, orderPurchaseGoods.getOrgId())
                    .setSql("balance = balance + " + orderPurchaseGoods.getBalanceDeductAmount()));
        }
        if (SourceType.STORE.getCode().equals(orderPurchaseGoods.getSourceType())) {
            sysStoreService.update(new UpdateWrapper<SysStore>().lambda()
                    .eq(SysStore::getId, SecurityUtils.getLoginUser().getUser().getStoreId())
                    .setSql("balance = balance + " + orderPurchaseGoods.getBalanceDeductAmount()));
        }

    }

    @Override
    public void handleAddressInfo(OrderPurchaseGoodsInfoVO orderPurchaseGoodsInfoVO, OrderPurchaseGoods purchaseGoods) {
        if (SourceType.FACTORY.getCode().equals(purchaseGoods.getSourceType())) {
            ManageFactory manageFactory = manageFactoryService.getById(purchaseGoods.getOrgId());
            if (manageFactory == null) {
                throw new ServiceException("该工厂不存在");
            }
            orderPurchaseGoodsInfoVO.setName(manageFactory.getFactoryName());
            orderPurchaseGoodsInfoVO.setProvince(manageFactory.getProvince());
            orderPurchaseGoodsInfoVO.setCity(manageFactory.getCity());
            orderPurchaseGoodsInfoVO.setArea(manageFactory.getArea());
            orderPurchaseGoodsInfoVO.setAddress(manageFactory.getAddress());
            orderPurchaseGoodsInfoVO.setAddressDetail(manageFactory.getDetailAddress());
            orderPurchaseGoodsInfoVO.setContactName(manageFactory.getApplyName());
            orderPurchaseGoodsInfoVO.setContactPhone(manageFactory.getApplyPhone());
        }
        if (SourceType.STORE.getCode().equals(purchaseGoods.getSourceType())) {
            SysStore store = sysStoreService.getById(purchaseGoods.getOrgId());
            if (store == null) {
                throw new ServiceException("该门店不存在，无法进货");
            }
            orderPurchaseGoodsInfoVO.setName(store.getName());
            orderPurchaseGoodsInfoVO.setProvince(store.getProvinceName());
            orderPurchaseGoodsInfoVO.setCity(store.getCityName());
            orderPurchaseGoodsInfoVO.setArea(store.getAreaName());
            orderPurchaseGoodsInfoVO.setAddress(store.getAddress());
            orderPurchaseGoodsInfoVO.setAddressDetail(store.getAddressDetail());
            orderPurchaseGoodsInfoVO.setContactName(store.getContactName());
            orderPurchaseGoodsInfoVO.setContactPhone(store.getContactPhone());
        }
    }
    //</editor-folder>
}
