package com.hzs.scm.purchase.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.CacheConstants;
import com.hzs.common.core.constant.SaOrderFieldConstants;
import com.hzs.common.core.constant.SystemFieldConstants;
import com.hzs.common.core.constant.msg.DocumentMsgConstants;
import com.hzs.common.core.constant.msg.ScmMsgConstants;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.core.utils.ComputeUtil;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.domain.scm.po.PoOrder;
import com.hzs.common.domain.scm.po.ext.PoOrderExt;
import com.hzs.common.domain.scm.po.ext.PoOrderItemsExt;
import com.hzs.common.domain.scm.pub.ScmItemSpecs;
import com.hzs.common.domain.scm.pub.ScmOrderApproveLog;
import com.hzs.common.domain.scm.purchase.IcPurchaseInB;
import com.hzs.common.domain.scm.purchase.IcPurchaseInH;
import com.hzs.common.domain.scm.purchase.ext.IcPurchaseInBExt;
import com.hzs.common.domain.scm.purchase.ext.IcPurchaseInHExt;
import com.hzs.common.domain.system.sys.SysUser;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.scm.ic.service.IIcOnHandNumService;
import com.hzs.scm.no.service.IScmBillNoService;
import com.hzs.scm.po.service.IPoOrderService;
import com.hzs.scm.pub.param.ScmApproveParam;
import com.hzs.scm.pub.service.IScmItemSpecsService;
import com.hzs.scm.pub.service.IScmOrderApproveLogService;
import com.hzs.scm.purchase.mapper.IcPurchaseInHMapper;
import com.hzs.scm.purchase.param.PurchaseInBParam;
import com.hzs.scm.purchase.param.PurchaseInParam;
import com.hzs.scm.purchase.service.IIcPurchaseInBService;
import com.hzs.scm.purchase.service.IIcPurchaseInHService;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;
import com.hzs.system.sys.IUserServiceApi;
import com.hzs.system.sys.dto.ApprovalBusinessResultDTO;
import com.hzs.system.sys.dto.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * <p>
 * 采购订单表头 服务实现类
 * </p>
 *
 * @author hzs
 * @since 2023-11-17
 */
@Service
@Slf4j
public class IcPurchaseinHServiceImpl extends ServiceImpl<IcPurchaseInHMapper, IcPurchaseInH> implements IIcPurchaseInHService {

    @DubboReference
    private ICurrencyServiceApi currencyServiceApi;

    @DubboReference
    private IUserServiceApi userServiceApi;

    @Autowired
    private RedisService redisService;

    @Autowired
    private IScmBillNoService scmBillNoService;

    @Autowired
    private IScmItemSpecsService scmItemSpecsService;

    @Autowired
    private IIcPurchaseInBService purchaseInbService;

    @Autowired
    private IIcOnHandNumService onHandNumService;

    @Autowired
    private IScmOrderApproveLogService scmOrderApproveLogService;

    @Autowired
    private IPoOrderService poOrderService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertSavePurchaseByPoOrder(List<PoOrderExt> poOrderList, PurchaseInParam purchaseInhParam, Long pkMember) {
        // 根据采购订单封装采购入库单
        // 入库单表头
        Date date = DateUtils.currentDateTime();
        // 入库单表头
        IcPurchaseInH icPurchaseInH = packagePurchaseInH(poOrderList.get(0), purchaseInhParam, date, pkMember);
        // 入库单表体
        List<IcPurchaseInB> icPurchaseInbList = packagePurchaseInB(icPurchaseInH, purchaseInhParam, date, pkMember);
        icPurchaseInH.setPkStorehouse(icPurchaseInbList.get(0).getPkStorehouse());
        // 保存主表
        save(icPurchaseInH);
        // 保存明细表
        for (IcPurchaseInB icPurchaseInB : icPurchaseInbList) {
            icPurchaseInB.setPkPurchase(icPurchaseInH.getPkId());
        }
        purchaseInbService.saveBatch(icPurchaseInbList);
        saveScmItemSpecs(pkMember, icPurchaseInH, icPurchaseInbList, poOrderList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertSavePurchaseBack(IcPurchaseInHExt oldPurchaseInExt, PurchaseInParam purchaseInhParam) {
        // 复制
        IcPurchaseInHExt purchaseInExt = BeanUtil.copyProperties(oldPurchaseInExt, IcPurchaseInHExt.class);
        purchaseInExt.setReturnStatus(EYesNo.YES.getIntValue());
        purchaseInExt.setReturnReason(purchaseInhParam.getReturnReason());
        List<IcPurchaseInBExt> purchaseInBiExtList = BeanUtil.copyToList(oldPurchaseInExt.getIcPurchaseInbList(), IcPurchaseInBExt.class);
        Long pkSource = oldPurchaseInExt.getPkId();
        purchaseInExt.setPkId(null);
        Date currentDate = DateUtils.currentDateTime();
        purchaseInExt.setOrderCode(scmBillNoService.createScmBillNoByOrderType(EScmOrderType.PURCHASE_IN.getValue()));
        purchaseInExt.setOrderDate(purchaseInhParam.getOrderDate());
        purchaseInExt.setRemark(purchaseInhParam.getRemark());
        purchaseInExt.setCreationTime(currentDate);
        purchaseInExt.setOrderStatus(EScmOrderStatus.SAVE.getValue());
        Map<Long, PurchaseInBParam> purchaseBiMap = new HashMap<>();
        for (PurchaseInBParam purchaseInBiParam : purchaseInhParam.getPurchaseInBParamList()) {
            purchaseBiMap.put(purchaseInBiParam.getPkId(), purchaseInBiParam);
        }
        List<IcPurchaseInB> savePurchaseInBiExtList = new ArrayList<>();
        BigDecimal totalNum = BigDecimal.ZERO;
        for (IcPurchaseInBExt purchaseInBiExt : purchaseInBiExtList) {
            Long pkSourceB = purchaseInBiExt.getPkId();
            if(purchaseBiMap.containsKey(pkSourceB)){
                PurchaseInBParam purchaseInBiParam = purchaseBiMap.get(pkSourceB);
                purchaseInBiExt.setPkSource(pkSource);
                purchaseInBiExt.setPkSourceB(pkSourceB);
                purchaseInBiExt.setPkId(null);
                purchaseInBiExt.setBizDate(purchaseInBiParam.getBizDate());
                if(!ComputeUtil.compareValue(purchaseInBiExt.getNassistnum(), purchaseInBiParam.getNnum())){
                    throw new RuntimeException("退货数量不能大于采购入库数量！");
                }
                purchaseInBiExt.setNnum(purchaseInBiParam.getNnum());
                // 无税金额  = 无税单价*数量
                purchaseInBiExt.setNorigmny(ComputeUtil.computeMultiply(purchaseInBiExt.getNorigprice(), purchaseInBiExt.getNnum()));
                // 含税单价  = 无税单价*（1+税率）
                purchaseInBiExt.setNorigtaxprice(ComputeUtil.computeMultiply(purchaseInBiExt.getNorigprice(),
                        ComputeUtil.computeAdd(BigDecimal.ONE, ComputeUtil.computeMultiply(purchaseInBiExt.getNtaxrate(), BigDecimal.valueOf(0.01)))));
                // 税额 =无税单价*税率*数量
                purchaseInBiExt.setNtax(ComputeUtil.computeMultiply(ComputeUtil.computeBonusMultiply(purchaseInBiExt.getNorigprice(), purchaseInBiExt.getNtaxrate()), purchaseInBiExt.getNnum()));
                // 价税合计 含税单价*数量
                purchaseInBiExt.setNorigtaxmny(ComputeUtil.computeMultiply(purchaseInBiExt.getNorigtaxprice(), purchaseInBiExt.getNnum()));
                purchaseInBiExt.setCreationTime(currentDate);
                purchaseInBiExt.setTransType(ETransType.GENERAL_OUT.getValue());

                savePurchaseInBiExtList.add(purchaseInBiExt);
                totalNum = ComputeUtil.computeAdd(totalNum, purchaseInBiExt.getNnum());
            }
        }
        purchaseInExt.setTotalNum(totalNum);
        baseMapper.insert(purchaseInExt);
        if(savePurchaseInBiExtList.size() >0) {
            savePurchaseInBiExtList.forEach(purchaseInBiExt->
                    purchaseInBiExt.setPkPurchase(purchaseInExt.getPkId()));
            purchaseInbService.saveBatch(savePurchaseInBiExtList);
            List<ScmItemSpecs> saveScmItemSpecsList = scmItemSpecsService.packageOrderItemsSpecs(savePurchaseInBiExtList, purchaseInExt.getPkId());
            if (saveScmItemSpecsList.size() > 0) {
                scmItemSpecsService.saveBatch(saveScmItemSpecsList);
            }
        }
    }

    /*
     * @description: 采购订单对应的规格
     * @author: sui q
     * @date: 2023/11/24 11:21
     * @param: null null
     **/
    private Map<Long, List<ScmItemSpecs>> packageItemSpecsMap(List<PoOrderExt> poOrderList) {
        List<ScmItemSpecs> scmItemSpecsList = new ArrayList<>();
        for (PoOrderExt poOrderExt : poOrderList) {
            for (PoOrderItemsExt poOrderItemsExt : poOrderExt.getPoOrderItemsExtList()) {
                ScmItemSpecs scmItemSpecs = ScmItemSpecs.builder()
                        .pkOrder(poOrderExt.getPkId())
                        .pkOrderItems(poOrderItemsExt.getPkId())
                        .build();
                scmItemSpecsList.add(scmItemSpecs);
            }
        }
        return scmItemSpecsService.queryScmItemSpecsByCondition(EScmOrderType.PO_ORDER.getValue(), scmItemSpecsList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSavePurchaseByPoOrder(List<PoOrderExt> poOrderList, IcPurchaseInHExt purchaseInhExt,
                                            PurchaseInParam purchaseInhParam, Long pkMember) {
        // 更新规格明细表，先删除在新增 根据主表主键删除
        scmItemSpecsService.deleteItemSpecsById(EScmOrderType.PURCHASE_IN.getValue(), purchaseInhParam.getPkId(), pkMember);
        Date date = DateUtils.currentDateTime();
        // 入库单表头
//        IcPurchaseInH icPurchaseInH = packagePurchaseInH(poOrderList.get(0), purchaseInhParam, date, pkMember);
        purchaseInhExt.setOrderDate(purchaseInhParam.getOrderDate());
        purchaseInhExt.setRemark(purchaseInhParam.getRemark());
        // 入库单表体
        List<IcPurchaseInB> icPurchaseInbList = packagePurchaseInB(purchaseInhExt, purchaseInhParam, date, pkMember);
        // merge 对入库单表体进行 icPurchaseInbList 修改或新增 查询出删除的、
        List<IcPurchaseInB> insertPurchaseInbList = new ArrayList<>();
        List<IcPurchaseInB> updatePurchaseInbList = new ArrayList<>();
        List<Long> updateIdList = new ArrayList<>();
        icPurchaseInbList.forEach(purchaseInb -> {
            if (purchaseInb.getPkId() != null) {
                updateIdList.add(purchaseInb.getPkId());
                updatePurchaseInbList.add(purchaseInb);
            } else {
                purchaseInb.setPkPurchase(purchaseInhExt.getPkId());
                insertPurchaseInbList.add(purchaseInb);
            }
        });
        List<IcPurchaseInB> delPurchaseInb = new ArrayList<>();
        for (IcPurchaseInB icPurchaseInB : purchaseInhExt.getIcPurchaseInbList()) {
            if (!updateIdList.contains(icPurchaseInB.getPkId())) {
                icPurchaseInB.setPkModified(pkMember);
                delPurchaseInb.add(icPurchaseInB);
            }
        }
        List<String> poOrderKeyList = new ArrayList<>();
        String purchaseLockKey = CacheConstants.IC_PURCHASE_IN_LOCK + purchaseInhExt.getPkId();
        try {
            // 加锁 采购订单加锁，采购入库单加锁，采购订单同时只能被一个人操作
            for (PoOrderExt poOrderExt : poOrderList) {
                poOrderKeyList.add(CacheConstants.PO_ORDER_LOCK + poOrderExt.getPkId());
            }
            if (!redisService.lockKeyByList(poOrderKeyList)) {
                throw new RuntimeException(ScmMsgConstants.BILL_NOT_OPERATION);
            }
            if (!redisService.lockKeyOnce(purchaseLockKey)) {
                throw new RuntimeException(ScmMsgConstants.BILL_NOT_OPERATION);
            }
            // 删除明细
            if (delPurchaseInb.size() > 0) {
                purchaseInbService.deletePurchaseInbByList(delPurchaseInb);
            }
            if (insertPurchaseInbList.size() > 0) {
                purchaseInbService.saveBatch(insertPurchaseInbList);
            }
            if (updatePurchaseInbList.size() > 0) {
                updatePurchaseInbList.forEach(purchaseInb ->
                        purchaseInbService.updateById(purchaseInb));
            }
            saveScmItemSpecs(pkMember, purchaseInhExt, icPurchaseInbList, poOrderList);
            // 更新入库单表
            updateById(purchaseInhExt);
        } finally {
            redisService.unlockByList(poOrderKeyList);
            redisService.unlock(purchaseLockKey);
        }
    }

    private void saveScmItemSpecs(Long pkMember, IcPurchaseInH icPurchaseInH, List<IcPurchaseInB> icPurchaseInbList, List<PoOrderExt> poOrderList) {
        // 封装明细表对应的规格
        Map<Long, List<ScmItemSpecs>> itemSpecsMap = packageItemSpecsMap(poOrderList);
        List<ScmItemSpecs> saveScmItemSpecsList = new ArrayList<>();
        for (IcPurchaseInB icPurchaseInB : icPurchaseInbList) {
            if (itemSpecsMap.containsKey(icPurchaseInB.getPkPoOrderItems())) {
                List<ScmItemSpecs> itemSpecsList = itemSpecsMap.get(icPurchaseInB.getPkPoOrderItems());
                scmItemSpecsService.packageScmItemSpecsList(itemSpecsList, pkMember,
                        icPurchaseInH.getPkId(), icPurchaseInB.getPkId(), EScmOrderType.PURCHASE_IN.getValue());
                saveScmItemSpecsList.addAll(itemSpecsList);
            }
        }
        // 保存订单明细规格
        if (saveScmItemSpecsList.size() > 0) {
            scmItemSpecsService.saveBatch(saveScmItemSpecsList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePurchaseByPk(Long pkPurchase, Long pkMember) {
        String purchaseLockKey = CacheConstants.IC_PURCHASE_IN_LOCK + pkPurchase;
        if (!redisService.lockKeyOnce(purchaseLockKey)) {
            throw new RuntimeException(ScmMsgConstants.BILL_NOT_OPERATION);
        }
        // 删除规格明细表
        scmItemSpecsService.deleteItemSpecsById(EScmOrderType.PURCHASE_IN.getValue(), pkPurchase, pkMember);
        // 删除订单明细表
        purchaseInbService.deletePurchaseInbByPkPurchase(pkPurchase, pkMember);
        // 删除订单主表
        UpdateWrapper<IcPurchaseInH> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set(SystemFieldConstants.DEL_FLAG, EYesNo.NO.getIntValue());
        updateWrapper.set(SystemFieldConstants.PK_MODIFIED, pkMember);
        updateWrapper.set(SystemFieldConstants.MODIFIED_TIME, DateUtils.currentDateTime());
        updateWrapper.eq(SystemFieldConstants.PK_ID, pkPurchase);
        update(updateWrapper);
        redisService.unlock(purchaseLockKey);
    }

    @Override
    public IcPurchaseInHExt queryPurchaseInExtById(Long pkId, Integer orderStatus, Integer pkCountry) {
        IcPurchaseInHExt purchaseInExt = baseMapper.queryPurchaseInhExtById(pkId, orderStatus, pkCountry);
        if(purchaseInExt == null){
            return null;
        }
        // 查询明细表，需要携带规格
        List<IcPurchaseInBExt> purchaseInBiExtList = purchaseInbService.queryPurchaseInbByPk(purchaseInExt.getIcPurchaseInbList());
        purchaseInExt.setIcPurchaseInbList(purchaseInBiExtList);
        return purchaseInExt;
    }

    @Override
    public IcPurchaseInHExt queryPurchaseInhExtById(Long pkId, Integer orderStatus, Integer pkCountry) {
        return baseMapper.queryPurchaseInhExtById(pkId, orderStatus, pkCountry);
    }

    @Override
    public IcPurchaseInHExt queryDisPurchaseInhExtById(Long pkId, Integer orderStatus) {
        PurchaseInParam purchaseInParam = new PurchaseInParam();
        purchaseInParam.setPkId(pkId);
        purchaseInParam.setOrderStatus(orderStatus);
        List<IcPurchaseInHExt> purchaseInExtList = baseMapper.queryDisPurchaseInhExtByCondition(purchaseInParam);
        if(CollectionUtil.isNotEmpty(purchaseInExtList)){
            return purchaseInExtList.get(0);
        }
        return null;
    }


    @Override
    public List<IcPurchaseInHExt> queryDisPurchaseInExtByCondition(PurchaseInParam purchaseInParam) {
        if (purchaseInParam.getEndDate() != null) {
            purchaseInParam.setEndDate(DateUtils.afterDate(1, ChronoUnit.DAYS, purchaseInParam.getEndDate()));
        }
        return baseMapper.queryDisPurchaseInhExtByCondition(purchaseInParam);
    }

    @Override
    public List<IcPurchaseInHExt> queryTotalPurchaseInhExtByCondition(PurchaseInParam purchaseInParam) {
        if (purchaseInParam.getEndDate() != null) {
            purchaseInParam.setEndDate(DateUtils.afterDate(1, ChronoUnit.DAYS, purchaseInParam.getEndDate()));
        }
        return baseMapper.queryTotalPurchaseInhExtByCondition(purchaseInParam);
    }

    /*
     * @description: 审核采购退货单
     * @author: sui q
     * @date: 2024/3/6 11:48
     * @param: null null
     **/
    private String approvePurchaseOutByStatus(ApprovalBusinessResultDTO approvalBusinessResultDTO, Integer scmOrderStatus, Integer approveStatus){
        // 查询订单日志表
        List<ScmOrderApproveLog> scmOrderApproveLogList = scmOrderApproveLogService.queryScmOrderApproveLogByCondition(null, approvalBusinessResultDTO.getEApprovalBusiness().getValue(), approvalBusinessResultDTO.getBusinessCode());
        if (scmOrderApproveLogList == null || scmOrderApproveLogList.size() == 0) {
            return TransactionUtils.getContent(DocumentMsgConstants.DOCUMENT_NOT_EXISTS);
        }
        ScmOrderApproveLog scmOrderApproveLog = scmOrderApproveLogList.get(0);
        // 查询采购退货单
        IcPurchaseInHExt purchaseInExt = queryPurchaseInExtById(scmOrderApproveLog.getPkOrder(), EScmOrderStatus.SUBMIT.getValue(), null);
        if (purchaseInExt == null) {
            return TransactionUtils.getContent(DocumentMsgConstants.DOCUMENT_HAS_HANDLE);
        }
        // 更新采购入库单状态
        updatePurchaseStatus(purchaseInExt.getPkId(), approvalBusinessResultDTO.getLoginUser(), scmOrderStatus);
        // 更新前程日志表状态
        scmOrderApproveLogService.updateScmOrderApproveStatus(scmOrderApproveLog.getPkId(), approvalBusinessResultDTO.getLoginUser().getUserId(), approveStatus);
        // 弃审的时候回退批次数量
        if(EAgentApprovalStatus.REFUSE.getValue() == approveStatus){
            onHandNumService.backIcOnHandNumByGeneralOut(purchaseInExt, purchaseInExt.getIcPurchaseInbList(), EScmOrderType.PURCHASE_IN.getValue(), approvalBusinessResultDTO.getLoginUser().getUserId());
        }else {
            // 审核通过回写采购入库单、明细，先回写明细
            purchaseInbService.mergePurchaseInBiByPurchaseBack(purchaseInExt.getIcPurchaseInbList());
            baseMapper.mergePurchaseInExt(purchaseInExt.getIcPurchaseInbList(), approvalBusinessResultDTO.getLoginUser().getUserId());
//            Set<Long> sourceIdSet = new HashSet<>();
//            for (IcPurchaseInBExt purchaseInBiExt : purchaseInExt.getIcPurchaseInbList()) {
//                sourceIdSet.add(purchaseInBiExt.getPkSource());
//            }
//            // 退货单回写原订单累计出库数量
//            // 原订单累计出库数量为0后需要回写主订单为已退货
//            for (Long aLong : sourceIdSet) {
//                updatePurchaseStatus(aLong, approvalBusinessResultDTO.getLoginUser(), EScmOrderStatus.BACK.getValue());
//            }
        }
        return null;
    }


    private String approvePurchaseByStatus(ApprovalBusinessResultDTO approvalBusinessResultDTO, Integer scmOrderStatus, Integer approveStatus){
        // 查询订单日志表
        List<ScmOrderApproveLog> scmOrderApproveLogList = scmOrderApproveLogService.queryScmOrderApproveLogByCondition(null, approvalBusinessResultDTO.getEApprovalBusiness().getValue(), approvalBusinessResultDTO.getBusinessCode());
        if (scmOrderApproveLogList == null || scmOrderApproveLogList.size() == 0) {
            return TransactionUtils.getContent(DocumentMsgConstants.DOCUMENT_NOT_EXISTS);
        }
        ScmOrderApproveLog scmOrderApproveLog = scmOrderApproveLogList.get(0);
        // 查询采购入库单
        IcPurchaseInHExt icPurchaseInhExt = queryPurchaseInhExtById(scmOrderApproveLog.getPkOrder(), EScmOrderStatus.SUBMIT.getValue(), approvalBusinessResultDTO.getLoginUser().getDataCountry());
        if (icPurchaseInhExt == null) {
            return TransactionUtils.getContent(DocumentMsgConstants.DOCUMENT_HAS_HANDLE);
        }
        // 更新采购入库单状态
        updatePurchaseStatus(icPurchaseInhExt.getPkId(), approvalBusinessResultDTO.getLoginUser(), scmOrderStatus);
        // 更新前程日志表状态
        scmOrderApproveLogService.updateScmOrderApproveStatus(scmOrderApproveLog.getPkId(), approvalBusinessResultDTO.getLoginUser().getUserId(), approveStatus);
        if(EAgentApprovalStatus.APPROVED.getValue() == approveStatus){
            // 查询采购入库单明细表
            List<IcPurchaseInBExt> icPurchaseInbList = purchaseInbService.queryPurchaseInbByPk(icPurchaseInhExt.getIcPurchaseInbList());
            if(icPurchaseInbList != null && icPurchaseInbList.size() >0){
                icPurchaseInhExt.setIcPurchaseInbList(icPurchaseInbList);
            }
            // 更新累计入库数量
            purchaseInbService.updatePurchaseInbByPk(icPurchaseInhExt.getIcPurchaseInbList());
            // 更新现存量
            onHandNumService.mergeIcOnHandNumByGeneralIn(icPurchaseInhExt, icPurchaseInhExt.getIcPurchaseInbList(), EScmOrderType.PURCHASE_IN.getValue(), approvalBusinessResultDTO.getLoginUser().getUserId());
            // 更新采购订单累计入库数量
            poOrderService.updatePoOrderItemsTotalNum(icPurchaseInhExt.getIcPurchaseInbList(), approvalBusinessResultDTO.getLoginUser().getUserId());
        }
        return null;
    }

    private void updatePurchaseStatus(Long pkId, LoginUser loginUser, Integer orderStatus) {
        UpdateWrapper<IcPurchaseInH> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set(SaOrderFieldConstants.ORDER_STATUS, orderStatus);
        updateWrapper.set(SystemFieldConstants.PK_MODIFIED, loginUser.getUserId());
        updateWrapper.set(SystemFieldConstants.MODIFIED_TIME, DateUtils.currentDateTime());
        updateWrapper.eq(SystemFieldConstants.PK_ID, pkId);
        update(updateWrapper);
    }

    private IcPurchaseInH packagePurchaseInH(PoOrder poOrder, PurchaseInParam purchaseInhParam, Date date, Long pkMember) {
        SysUser sysUser = userServiceApi.selectUserById(pkMember).getData();
        // 根据登录账号获得部门
        IcPurchaseInH purchaseInh = IcPurchaseInH.builder()
                .pkDept(sysUser.getPkDept().intValue())
                .pkWhsmanager(pkMember)
                .pkCubasdoc(poOrder.getPkCubasdoc())
                .orderCode(scmBillNoService.createScmBillNoByOrderType(EScmOrderType.PURCHASE_IN.getValue()))
                .pkStorehouse(purchaseInhParam.getPkStorehouse())
                .orderDate(purchaseInhParam.getOrderDate())
                .pkCorp(poOrder.getPkCorp())
                .orderStatus(EScmOrderStatus.SAVE.getValue())
                .remark(purchaseInhParam.getRemark())
                .build();
        if (purchaseInhParam.getPkId() == null) {
            purchaseInh.setPkCreator(pkMember);
        } else {
            purchaseInh.setPkId(purchaseInhParam.getPkId());
            purchaseInh.setModifiedTime(date);
            purchaseInh.setPkModified(pkMember);
        }
        purchaseInh.setPkCountry(purchaseInhParam.getPkCountry());
        return purchaseInh;
    }

    private List<IcPurchaseInB> packagePurchaseInB(IcPurchaseInH icPurchaseInH, PurchaseInParam purchaseInhParam, Date date, Long pkMember) {
        List<IcPurchaseInB> icPurchaseInbList = new ArrayList<>();
        // 根据国家获得汇率
        CurrencyDTO currencyDTO = currencyServiceApi.getCurrency(purchaseInhParam.getPkCountry()).getData();
        BigDecimal totalNum = BigDecimal.ZERO;
        for (PurchaseInBParam purchaseInbParam : purchaseInhParam.getPurchaseInBParamList()) {
            IcPurchaseInB icPurchaseInB = BeanUtil.copyProperties(purchaseInbParam, IcPurchaseInB.class);
            icPurchaseInB.setPkPoOrder(purchaseInbParam.getPkPoOrder());
            icPurchaseInB.setPkPoOrderItems(purchaseInbParam.getPkPoOrderItems());
            icPurchaseInB.setPkPurchase(purchaseInhParam.getPkId());
            if (EYesNo.YES.getIntValue() == purchaseInbParam.getIsGift()) {
                icPurchaseInB.setNtaxrate(BigDecimal.ZERO);
                icPurchaseInB.setNorigprice(BigDecimal.ZERO);
                // 含税单价  = 无税单价*（1+税率）
                icPurchaseInB.setNorigtaxprice(BigDecimal.ZERO);
                // 无税金额  = 无税单价*数量
                icPurchaseInB.setNorigmny(BigDecimal.ZERO);
                // 税额 =无税单价*数量
                icPurchaseInB.setNtax(BigDecimal.ZERO);
                // 价税合计=含税单价*数量
                icPurchaseInB.setNorigtaxmny(BigDecimal.ZERO);
            } else {
                // 无税金额  = 无税单价*数量
                icPurchaseInB.setNorigmny(ComputeUtil.computeMultiply(purchaseInbParam.getNorigprice(), purchaseInbParam.getNnum()));
                // 含税单价  = 无税单价*（1+税率）
                icPurchaseInB.setNorigtaxprice(ComputeUtil.computeMultiply(purchaseInbParam.getNorigprice(),
                        ComputeUtil.computeAdd(BigDecimal.ONE, ComputeUtil.computeMultiply(purchaseInbParam.getNtaxrate(), BigDecimal.valueOf(0.01)))));
                // 税额 =无税单价*税率*数量
                icPurchaseInB.setNtax(ComputeUtil.computeMultiply(ComputeUtil.computeBonusMultiply(purchaseInbParam.getNorigprice(), purchaseInbParam.getNtaxrate()), purchaseInbParam.getNnum()));
                // 价税合计 含税单价*数量
                icPurchaseInB.setNorigtaxmny(ComputeUtil.computeMultiply(icPurchaseInB.getNorigtaxprice(), purchaseInbParam.getNnum()));
            }
            icPurchaseInB.setPkRate(currencyDTO.getPkId());
            totalNum = ComputeUtil.computeAdd(totalNum, icPurchaseInB.getNnum());
//            List<ItemSpecsParam> itemSpecsParamList = purchaseInbParam.getItemSpecsParamList();
//            List<ScmItemSpecs> scmItemSpecsList = scmItemSpecsService.packageScmItemByParam(itemSpecsParamList, purchaseInhParam.getPkCountry(), pkMember,
//                    icPurchaseInB.getPkPurchase(), icPurchaseInB.getPkId(), EScmOrderType.PURCHASE_IN.getValue());
//            if (scmItemSpecsList.size() > 0) {
//                icPurchaseInB.setScmItemSpecsList(scmItemSpecsList);
//            }
            icPurchaseInB.setTransType(ETransType.GENERAL_IN.getValue());
            if (icPurchaseInB.getPkId() == null) {
                icPurchaseInB.setPkCreator(pkMember);
            } else {
                icPurchaseInB.setModifiedTime(date);
                icPurchaseInB.setPkModified(pkMember);
            }
            icPurchaseInB.setPkBatchCode(purchaseInbParam.getPkBatchCode());
            icPurchaseInB.setPkCountry(purchaseInhParam.getPkCountry());
            icPurchaseInbList.add(icPurchaseInB);
        }
        icPurchaseInH.setTotalNum(totalNum);
        return icPurchaseInbList;
    }
}
