package nc.impl.bd.bom.bom0202;

import nc.bs.bd.bom.bom0202.bp.BomDataValidatorBP;
import nc.bs.bd.bom.bom0202.bp.BomDeleteBP;
import nc.bs.bd.bom.bom0202.bp.BomInsertBP;
import nc.bs.bd.bom.bom0202.bp.BomInsertCommitBP;
import nc.bs.bd.bom.bom0202.bp.BomPubBP;
import nc.bs.bd.bom.bom0202.bp.BomUpdateBP;
import nc.bs.bd.bom.bom0202.bp.BomUpdateCommitBP;
import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.bs.framework.common.NCLocator;
import nc.bs.ml.NCLangResOnserver;
import nc.bs.pubapp.AppBsContext;
import nc.bs.uap.lock.PKLock;
import nc.impl.pubapp.pattern.data.bill.BillUpdate;
import nc.impl.pubapp.pattern.data.bill.tool.BillTransferTool;
import nc.impl.pubapp.pattern.data.vo.VOQuery;
import nc.itf.bd.bom.bom0202.IBomBillMaintainService;
import nc.itf.bd.bom.bom0202.IBomBillQueryService;
import nc.mmbd.utils.factoryparam.MMBDFactoryParameter;
import nc.util.mmf.framework.base.MMArrayUtil;
import nc.util.mmf.framework.base.MMValueCheck;
import nc.util.mmf.framework.db.MMSqlBuilder;
import nc.util.mmf.framework.gc.GCBillTransferTool;
import nc.vo.bd.bom.bom0202.entity.AggBomVO;
import nc.vo.bd.bom.bom0202.entity.BomActivityVO;
import nc.vo.bd.bom.bom0202.entity.BomItemVO;
import nc.vo.bd.bom.bom0202.entity.BomOutputsVO;
import nc.vo.bd.bom.bom0202.entity.BomUseOrgVO;
import nc.vo.bd.bom.bom0202.entity.BomVO;
import nc.vo.bd.bom.bom0202.enumeration.BomCategoryEnum;
import nc.vo.bd.bom.bom0202.enumeration.BomTypeEnum;
import nc.vo.bd.bom.bom0202.enumeration.FBomBillstatusEnum;
import nc.vo.bd.bom.bom0202.enumeration.VersionTypeEnum;
import nc.vo.bd.bom.bom0202.message.MMBDLangConstBom0202;
import nc.vo.pub.BusinessException;
import nc.vo.pub.VOStatus;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <b> 生产BOM维护的持久化类 </b>
 * <p>
 * 提供了基本的增删改操作
 * </p>
 * 创建日期:2010-1-15
 *
 * @author:zhoujuna
 */
public class BomBillMaintainServiceImpl implements IBomBillMaintainService {
    /**
     * 构造函数
     */

    @Override
    public void deleteBoms(AggBomVO[] objs) throws BusinessException {

        if (objs == null || objs.length == 0) {
            return;
        }
        try {
            // 加锁 + 检查ts
            GCBillTransferTool<AggBomVO> transTool = new GCBillTransferTool<AggBomVO>(objs);
            // 补全前台VO
            AggBomVO[] fullBills = transTool.getClientFullInfoBill();
            BomDeleteBP bp = new BomDeleteBP();
            bp.delete(fullBills);
        } catch (Exception ex) {
            ExceptionUtils.marsh(ex);
        }
    }

    @Override
    public AggBomVO[] insertBom(AggBomVO[] aggVO) throws BusinessException {
        return this.insertBomForEcn(aggVO, true);
    }

    @Override
    public AggBomVO[] insertBomForEcn(AggBomVO[] aggVO, boolean checkEcn) throws BusinessException {
        return this.insertBomForEcnAndRepls(aggVO, checkEcn, null);
    }

    @Override
    public AggBomVO[] insertBomForEcnAndRepls(AggBomVO[] aggVO, boolean checkEcn, String[] orgins)
            throws BusinessException {
        // TODO Auto-generated method stub
        try {
            // 加锁 + 检查ts
            GCBillTransferTool<AggBomVO> transTool = new GCBillTransferTool<AggBomVO>(aggVO);
            // 补全前台VO
            AggBomVO[] fullBills = transTool.getClientFullInfoBill();
            BomInsertBP bp = new BomInsertBP();
            AggBomVO[] returnVOs = bp.insert(fullBills, checkEcn, orgins, false);
            for (int i = 0; i < returnVOs.length; i++) {
                aggVO[i].setParent(returnVOs[i].getParent());
                aggVO[i].setChildren(BomItemVO.class, returnVOs[i].getChildrenVO());
                aggVO[i].setChildren(BomOutputsVO.class, returnVOs[i].getChildren(BomOutputsVO.class));
                aggVO[i].setChildren(BomUseOrgVO.class, returnVOs[i].getChildren(BomUseOrgVO.class));
            }
            return aggVO;
        } catch (Exception e) {
            ExceptionUtils.marsh(e);

        }
        return null;
    }

    @Override
    public AggBomVO[] updateBom(AggBomVO[] aggVO) throws BusinessException {
        return this.updateBomForEcn(aggVO, true);
    }

    @Override
    public AggBomVO[] updateBomForEcn(AggBomVO[] aggVO, boolean checkEcn) throws BusinessException {
        return this.updateBomForBomTree(aggVO, checkEcn, false, false);
    }

    @Override
    public AggBomVO[] updateBomForEcn(AggBomVO[] aggVO,Map<String,String> rownoMap, boolean checkEcn) throws BusinessException {
        return this.updateBomForBomTree(aggVO,rownoMap,checkEcn, false, false);
    }

    @Override
    public void validateBom(AggBomVO[] aggvos) throws BusinessException {
        BomDataValidatorBP bp = new BomDataValidatorBP();
        bp.validate(aggvos);

    }

    @Override
    public AggBomVO[] updateBomForBomTree(AggBomVO[] aggVO, boolean isCheckEcn, boolean isFromBom, boolean isEcn)
            throws BusinessException {
        if (MMArrayUtil.isEmpty(aggVO)) {
            return null;
        }
        try {
            // 检查该BOM是否被删除，因为如果BOM树状维护将BOM删除了，不允许修改该条记录
            Set<String> bomids = new HashSet<String>();
            for (AggBomVO vo : aggVO) {
                bomids.add(vo.getPrimaryKey());
            }
            Set<String> checkResult = BomPubBP.getBomID(bomids.toArray(new String[] {}));
            this.fillActivityVO(aggVO);
            if (checkResult != null && checkResult.size() < bomids.size()) {
                ExceptionUtils.wrappBusinessException(MMBDLangConstBom0202.getBOM_DELETED());
            }
            // 加锁 + 检查ts
            GCBillTransferTool<AggBomVO> transTool = new GCBillTransferTool<AggBomVO>(aggVO);
            // 补全前台VO
            AggBomVO[] fullBills = transTool.getClientFullInfoBill();
            // 获得修改前vo
            AggBomVO[] originBills = transTool.getOriginBills();
            BomUpdateBP bp = new BomUpdateBP();
            return bp.update(fullBills, originBills, isCheckEcn, isFromBom, isEcn);
        } catch (Exception e) {
            ExceptionUtils.wrappException(e);
        }
        return null;
    }

    @Override
    public AggBomVO[] updateBomForBomTree(AggBomVO[] aggVO,Map<String,String> rownoMap, boolean isCheckEcn, boolean isFromBom, boolean isEcn)
            throws BusinessException {
        if (MMArrayUtil.isEmpty(aggVO)) {
            return null;
        }
        try {
            // 检查该BOM是否被删除，因为如果BOM树状维护将BOM删除了，不允许修改该条记录
            Set<String> bomids = new HashSet<String>();
            for (AggBomVO vo : aggVO) {
                bomids.add(vo.getPrimaryKey());
            }
            Set<String> checkResult = BomPubBP.getBomID(bomids.toArray(new String[] {}));
            this.fillActivityVO(aggVO);
            if (checkResult != null && checkResult.size() < bomids.size()) {
                ExceptionUtils.wrappBusinessException(MMBDLangConstBom0202.getBOM_DELETED());
            }
            // 加锁 + 检查ts
            GCBillTransferTool<AggBomVO> transTool = new GCBillTransferTool<AggBomVO>(aggVO);
            // 补全前台VO
            AggBomVO[] fullBills = transTool.getClientFullInfoBill();
            // 获得修改前vo
            AggBomVO[] originBills = transTool.getOriginBills();
            BomUpdateBP bp = new BomUpdateBP();
            bp.setRownoMap(rownoMap);
            return bp.update(fullBills, originBills, isCheckEcn, isFromBom, isEcn);
        } catch (Exception e) {
            ExceptionUtils.wrappException(e);
        }
        return null;
    }

    private void fillActivityVO(AggBomVO[] aggVO) {
        for (AggBomVO aggBomVO : aggVO) {

            if (MMValueCheck.isNotEmpty(aggBomVO.getChildren(BomActivityVO.class))) {
                continue;
            }

            // 如果没有编辑过物料作业量，那么Model中数据为空，所以要把重查一下数据。
            String pk_group = aggBomVO.getParent().getAttributeValue(BomVO.PK_GROUP).toString();
            String pk_org = aggBomVO.getParent().getAttributeValue(BomVO.PK_ORG).toString();
            BomActivityVO[] actVOs = null;
            try {
                actVOs = this.getBomBillQueryService().getBomActivityVOsByBomId(pk_group, pk_org,
                        aggBomVO.getPrimaryKey());
            } catch (BusinessException e) {
                ExceptionUtils.wrappException(e);
            }
            List<BomActivityVO> actList = new ArrayList<BomActivityVO>();
            if (MMArrayUtil.isNotEmpty(actVOs)) {
                for (BomActivityVO vo : actVOs) {
                    if (MMValueCheck.isNotEmpty(vo.getNstandardwknum())) {
                        vo.setStatus(VOStatus.UNCHANGED);
                        actList.add(vo);
                    }
                }
                aggBomVO.setChildren(BomActivityVO.class, actList.toArray(new BomActivityVO[] {}));
            }
        }

    }

    @Override
    public AggBomVO[] commitBom(AggBomVO[] clientFullVOs, AggBomVO[] originBills) throws BusinessException {
        try {

            return new BillUpdate<AggBomVO>().update(clientFullVOs, originBills);
        } catch (Exception e) {
            ExceptionUtils.marsh(e);
            return null;

        }
    }

    @Override
    public AggBomVO[] uncommitBom(AggBomVO[] clientFullVOs, AggBomVO[] originBills) throws BusinessException {
        try {

            return new BillUpdate<AggBomVO>().update(clientFullVOs, originBills);
        } catch (Exception e) {
            ExceptionUtils.marsh(e);
            return null;

        }
    }

    @Override
    public AggBomVO[] auditBom(AggBomVO[] clientFullVOs, AggBomVO[] originBills) throws BusinessException {
        Map<String, Integer> newBomMap = new HashMap<>();
        for (AggBomVO vo: clientFullVOs){
            BomVO headVO = (BomVO) vo.getParent();
            newBomMap.put(vo.getPrimaryKey(), headVO.getFbillstatus());
        }
        try {
            // 审批默认BOM后需要把已有的有效默认BOM取消默认
            for (AggBomVO aggvo : originBills) {
                if (Integer.valueOf(FBomBillstatusEnum.IAPPROVE).equals(newBomMap.get(aggvo.getPrimaryKey()))){
                    BomVO head = (BomVO) aggvo.getParent();
                    if (!head.getHbdefault().booleanValue()) {
                        continue;
                    }
                    if (BomCategoryEnum.NORMAL_BOM.equalsValue(head.getHfbomcategory())) {
                        // 根据组织+物料+物料版本+BOM类型+有效无效更新原来的默认BOM为非默认；审批更新有效的
                        ArrayList<String> defaultPks = this.isBomOrCfgBomDefaultVersionExist(head.getPk_org(),
                                head.getHcmaterialid(), head.getHcmaterialvid(), head.getFbomtype(),
                                VersionTypeEnum.AVAILABLE.toIntValue());
                        if (MMValueCheck.isNotEmpty(defaultPks)) {
                            defaultPks.remove(head.getCbomid());// pk去掉当前审批的这条数据pk
                            this.CancelBomOrCfgBomDefaultVersion(defaultPks);
                        }
                    } else {
                        List<String> defaultpks = this.isOrderBomDefaultVersionExist(head.getPk_org(),
                                head.getVsobillcode(), head.getVsobillno(), head.getFbomtype());
                        if (MMValueCheck.isNotEmpty(defaultpks)) {
                            defaultpks.remove(head.getCbomid());// pk去掉当前审批的这条数据pk
                            this.CancelBomOrCfgBomDefaultVersion(defaultpks);
                        }
                    }
                }
            }
            return new BillUpdate<AggBomVO>().update(clientFullVOs, originBills);
        } catch (Exception e) {
            ExceptionUtils.marsh(e);
            return null;

        }
    }

    @Override
    public AggBomVO[] unauditBom(AggBomVO[] clientFullVOs, AggBomVO[] originBills) throws BusinessException {
        try {
            // 取消审批默认BOM后需要把已有的无效默认BOM取消默认
            for (AggBomVO aggvo : originBills) {
                BomVO head = (BomVO) aggvo.getParent();
                if (!head.getHbdefault().booleanValue()) {
                    continue;
                }
                /**
                 * delete by qianzhx 取消审批不做任何的取消默认操作
                 */
                // 根据组织+物料+物料版本+BOM类型+有效无效更新原来的默认BOM为非默认；取消审批更新无效的
                // ArrayList<String> defaultPks =
                // this.isBomOrCfgBomDefaultVersionExist(head.getPk_org(),
                // head.getHcmaterialid(),
                // head.getHcmaterialvid(), head.getFbomtype(),
                // VersionTypeEnum.UNAVAILABLE.toIntValue());
                // if (MMValueCheck.isNotEmpty(defaultPks)) {
                // defaultPks.remove(head.getCbomid());
                // this.CancelBomOrCfgBomDefaultVersion(defaultPks);
                // }
            }
            // 取消审批后把bom版本类型变为无效版本
            for (AggBomVO aggvo : clientFullVOs) {
                BomVO head = (BomVO) aggvo.getParent();
                // head.setHbdefault(UFBoolean.FALSE);
                head.setHfversiontype(VersionTypeEnum.UNAVAILABLE.toIntValue());
                head.setStatus(VOStatus.UPDATED);
                // ArrayList<String> cbomids = new ArrayList<String>();
                // cbomids.add(head.getCbomid());3

                // this.updateVersiontype(cbomids);
            }
            return new BillUpdate<AggBomVO>().update(clientFullVOs, originBills);
        } catch (Exception e) {
            ExceptionUtils.marsh(e);
            return null;

        }
    }

    @SuppressWarnings("boxing")
    @Override
    // 停用
    public AggBomVO[] seal(AggBomVO[] object) throws BusinessException {

        BomVO[] headvo = new BomVO[object.length];
        for (int i = 0; i < object.length; i++) {
            headvo[i] = (BomVO) object[i].getParentVO();

            try {
                if (headvo == null || headvo.length == 0) {
                    return null;
                }
                // 校验是否启用工程变更管理，是否默认版本 || UFBoolean.TRUE.equals(headvo[0].getHbdefault())
                // 如果是标准BOM启用工程变更，那么不支持修改
                String pkorg = headvo[i].getAttributeValue(BomVO.PK_ORG).toString();
                boolean isNormalBom = headvo[i].getHfbomcategory() == BomCategoryEnum.NORMAL_BOM.toIntValue();
                //1130需求变更，定制BOM不走工程变更
                boolean isCustBom=MMValueCheck.isTrue(headvo[i].getHbcustomized());
                // 配置BOM不支持ECN，所以先对BOM类型做判断
                if (!isCustBom&&isNormalBom && !headvo[i].getFbomtype().equals(BomTypeEnum.CONFIGBOM.toIntValue())
                        && this.isMMECN001Control(pkorg)) {
                    ExceptionUtils.wrappBusinessException(MMBDLangConstBom0202.getUnsupportUnEditWhenMMDB001Control());
                    return null;
                }
                if (headvo[i].getFbillstatus().intValue() != FBomBillstatusEnum.APPROVE.toIntValue()) {
                    ExceptionUtils.wrappBusinessException(NCLangResOnserver.getInstance().getString("1014362_0", null,
                                    "01014362-0465", null, new String[] { headvo[i].getVbillcode() })
//							.getStrByID("1014362_0","01014362-0465")/* BOM状态不是审批通过，无法启用/停用！ */
                    );
                } else if (headvo[i].getHfversiontype().intValue() == VersionTypeEnum.UNAVAILABLE.toIntValue()) {
                    ExceptionUtils.wrappBusinessException(NCLangResOnserver.getInstance().getString("1014362_0", null,
                                    "01014362-0466", null, new String[] { headvo[i].getVbillcode() })
//							getStrByID("1014362_0","01014362-0466")/* BOM已经是无效版本，无需停用！ */
                    );
                }
                // else if (UFBoolean.TRUE.equals(headvo[0].getHbdefault())) {
                // ExceptionUtils.wrappBusinessException(MMBDLangConstBom0202.getUnsupportEditWhenbdefault());
                // return null;
                // }
                headvo[i].setHbdefault(UFBoolean.FALSE);
                headvo[i].setHfversiontype(VersionTypeEnum.UNAVAILABLE.toIntValue());
                headvo[i].setStatus(VOStatus.UPDATED);

            } catch (Exception e) {
                ExceptionUtils.marsh(e);
            }
        }
        // 持久化
        BillTransferTool<AggBomVO> transferTool = new BillTransferTool<AggBomVO>(object);
        AggBomVO[] originBills = transferTool.getOriginBills();
        BillUpdate<AggBomVO> bo = new BillUpdate<AggBomVO>();
        bo.update(object, originBills);
        PKLock.getInstance().releaseDynamicLocks();

        return object;
        // return null;

    }

    @SuppressWarnings("boxing")
    @Override
    public AggBomVO[] unSeal(AggBomVO[] object) throws BusinessException {

        BomVO[] headvo = new BomVO[object.length];
        for (int i = 0; i < object.length; i++) {
            headvo[i] = (BomVO) object[i].getParentVO();
            try {
                if (headvo == null || headvo.length == 0) {
                    return null;
                }
                // 校验是否启用工程变更管理
                // 如果是正常非订单BOM,启用工程变更后，不支持修改
                String pkorg = headvo[i].getAttributeValue(BomVO.PK_ORG).toString();
                boolean isNormalBom = headvo[i].getHfbomcategory() == BomCategoryEnum.NORMAL_BOM.toIntValue();
                //1130需求变更，定制BOM不走工程变更
                boolean isCustBom=MMValueCheck.isTrue(headvo[i].getHbcustomized());
                if (!isCustBom&&isNormalBom && !headvo[i].getFbomtype().equals(BomTypeEnum.CONFIGBOM.toIntValue())
                        && this.isMMECN001Control(pkorg)) {
                    ExceptionUtils.wrappBusinessException(MMBDLangConstBom0202.getUnsupportUnEditWhenMMDB001Control());
                    return null;
                }
                if (headvo[i].getFbillstatus().intValue() != FBomBillstatusEnum.APPROVE.toIntValue()) {
                    ExceptionUtils.wrappBusinessException(NCLangResOnserver.getInstance().getString("1014362_0", null,
                                    "01014362-0465", null, new String[] { headvo[i].getVbillcode() })

//                    		getStrByID("1014362_0","01014362-0465")/* BOM状态不是审批通过，无法启用/停用！ */
                    );
                } else if (headvo[i].getHfversiontype().intValue() == VersionTypeEnum.AVAILABLE.toIntValue()) {
                    ExceptionUtils.wrappBusinessException(NCLangResOnserver.getInstance().getString("1014362_0", null,
                                    "01014362-0467", null, new String[] { headvo[i].getVbillcode() })

//							getStrByID("1014362_0","01014362-0467")/* BOM已经是有效版本，无需启用！ */
                    );
                }
                headvo[i].setHfversiontype(VersionTypeEnum.AVAILABLE.toIntValue());
                headvo[i].setStatus(VOStatus.UPDATED);

            } catch (Exception e) {
                ExceptionUtils.marsh(e);
            }
        }
        // 持久化
        BillTransferTool<AggBomVO> transferTool = new BillTransferTool<AggBomVO>(object);
        AggBomVO[] originBills = transferTool.getOriginBills();
        BillUpdate<AggBomVO> bo = new BillUpdate<AggBomVO>();
        bo.update(object, originBills);
        PKLock.getInstance().releaseDynamicLocks();
        return object;

    }

    private boolean isMMECN001Control(String pk_org) {
        boolean isMMECN001_Contrl = false;
        isMMECN001_Contrl = MMBDFactoryParameter.isAlterCtrl(pk_org);
        return isMMECN001_Contrl;
    }

    @Override
    public AggBomVO[] insertBomWithParam(AggBomVO[] aggvos, boolean isCheckEcn, boolean isOnApprove)
            throws BusinessException {
        try {
            // 加锁 + 检查ts
            GCBillTransferTool<AggBomVO> transTool = new GCBillTransferTool<AggBomVO>(aggvos);
            // 补全前台VO
            AggBomVO[] fullBills = transTool.getClientFullInfoBill();
            BomInsertBP bp = new BomInsertBP();
            AggBomVO[] returnVOs = bp.insert(fullBills, isCheckEcn, isOnApprove);
            for (int i = 0; i < returnVOs.length; i++) {
                aggvos[i].setParent(returnVOs[i].getParent());
                aggvos[i].setChildren(BomItemVO.class, returnVOs[i].getChildrenVO());
                aggvos[i].setChildren(BomOutputsVO.class, returnVOs[i].getChildren(BomOutputsVO.class));
                aggvos[i].setChildren(BomUseOrgVO.class, returnVOs[i].getChildren(BomUseOrgVO.class));
            }
            return aggvos;
        } catch (Exception e) {
            ExceptionUtils.marsh(e);

        }
        return null;
    }

    @Override
    public AggBomVO[] insertCommitBomWithParam(AggBomVO[] aggvos, boolean isCheckEcn, boolean isOnApprove) throws BusinessException {
        BomInsertCommitBP bp = new BomInsertCommitBP();
        AggBomVO[] result = bp.insertCommit(aggvos,isCheckEcn,isOnApprove);
        return result;
    }

    @Override
    public AggBomVO[] insertCommitBomWithParam_RequiresNew(AggBomVO[] aggvos, boolean isCheckEcn, boolean isOnApprove) throws BusinessException {
        BomInsertCommitBP bp = new BomInsertCommitBP();
        AggBomVO[] result = bp.insertCommit(aggvos,isCheckEcn,isOnApprove);
        return result;
    }
    @Override
    public AggBomVO[] updateBomWithParam(AggBomVO[] aggvos, boolean isFromBom, boolean isecn, boolean isCheckEcn,
                                         boolean isOnApprove) throws BusinessException {
        if (MMArrayUtil.isEmpty(aggvos)) {
            return null;
        }
        try {
            // 检查该BOM是否被删除，因为如果BOM树状维护将BOM删除了，不允许修改该条记录
            Set<String> bomids = new HashSet<String>();
            for (AggBomVO vo : aggvos) {
                bomids.add(vo.getPrimaryKey());
            }
            Set<String> checkResult = BomPubBP.getBomID(bomids.toArray(new String[] {}));
            if (checkResult != null && checkResult.size() < bomids.size()) {
                ExceptionUtils.wrappBusinessException(MMBDLangConstBom0202.getBOM_DELETED());
            }
            // 加锁 + 检查ts
            GCBillTransferTool<AggBomVO> transTool = new GCBillTransferTool<AggBomVO>(aggvos);
            // 补全前台VO
            AggBomVO[] fullBills = transTool.getClientFullInfoBill();
            // 获得修改前vo
            AggBomVO[] originBills = transTool.getOriginBills();
            BomUpdateBP bp = new BomUpdateBP();
            return bp.update(fullBills, originBills, isCheckEcn, isOnApprove, isFromBom, isecn);
        } catch (Exception e) {
            ExceptionUtils.marsh(e);
        }
        return null;
    }

    @Override
    public AggBomVO[] updateCommitBomWithParam(AggBomVO[] aggvos, boolean isFromBom, boolean isecn, boolean isCheckEcn, boolean isOnApprove) throws BusinessException {
        BomUpdateCommitBP bp = new BomUpdateCommitBP();
        AggBomVO[] result = bp.updateCommit(aggvos,isFromBom,isecn,isCheckEcn,isOnApprove);
        return result;
    }

    @Override
    public void deleteBomsWithParam(AggBomVO[] aggvos, boolean isCheckEcn, boolean isOnApprove)
            throws BusinessException {

        if (aggvos == null || aggvos.length == 0) {
            return;
        }
        try {
            // 加锁 + 检查ts
            GCBillTransferTool<AggBomVO> transTool = new GCBillTransferTool<AggBomVO>(aggvos);
            // 补全前台VO
            AggBomVO[] fullBills = transTool.getClientFullInfoBill();
            BomDeleteBP bp = new BomDeleteBP();
            bp.delete(fullBills, isCheckEcn, isOnApprove);
        } catch (Exception ex) {
            ExceptionUtils.marsh(ex);
        }
    }

    /**
     * 根据bom主键，更新默认字段为否
     *
     * @param cbomid
     */
    private void CancelBomOrCfgBomDefaultVersion(List<String> cbomids) {
        if (MMValueCheck.isEmpty(cbomids)) {
            return;
        }
        BaseDAO dao = new BaseDAO();
        MMSqlBuilder sql = new MMSqlBuilder();
        sql.append(" update ");
        sql.append(BomVO.TABLE_NAME);
        sql.set();
        sql.append(BomVO.HBDEFAULT, UFBoolean.FALSE);
        sql.where();
        sql.append(BomVO.CBOMID, cbomids);
        try {
            dao.executeUpdate(sql.toString());
        } catch (DAOException e) {
            ExceptionUtils.wrappException(e);
        }
    }

    /**
     * 根据bom主键，更新版本类型为无效版本
     *
     * @param cbomid
     */
    private void updateVersiontype(ArrayList<String> cbomids) {
        if (MMValueCheck.isEmpty(cbomids)) {
            return;
        }
        BaseDAO dao = new BaseDAO();
        MMSqlBuilder sql = new MMSqlBuilder();
        sql.append(" update ");
        sql.append(BomVO.TABLE_NAME);
        sql.set();
        sql.append(BomVO.HFVERSIONTYPE, VersionTypeEnum.UNAVAILABLE.toIntValue());
        sql.where();
        sql.append(BomVO.CBOMID, cbomids);
        try {
            dao.executeUpdate(sql.toString());
        } catch (DAOException e) {
            ExceptionUtils.wrappException(e);
        }
    }

    private List<String> isOrderBomDefaultVersionExist(String pk_org, String vsobillcode, String vsobillno,
                                                       Integer fbomtype) {
        if (fbomtype == 3) {
            return null;
        }
        if (MMValueCheck.isEmpty(vsobillcode) || MMValueCheck.isEmpty(vsobillno)) {
            return null;
        }
        VOQuery<BomVO> queryService = new VOQuery<BomVO>(BomVO.class, new String[] { BomVO.CBOMID });
        MMSqlBuilder sql = new MMSqlBuilder();
        sql.and();
        sql.append(BomVO.PK_GROUP, AppBsContext.getInstance().getPkGroup());
        sql.and();
        sql.append(BomVO.PK_ORG, pk_org);
        sql.and();
        sql.append(BomVO.VSOBILLCODE, vsobillcode);
        sql.and();
        sql.append(BomVO.VSOBILLNO, vsobillno);
        sql.and();
        sql.append(BomVO.FBOMTYPE, fbomtype.intValue());
        sql.and();
        sql.append(BomVO.HFBOMCATEGORY, 2);
        sql.and();
        sql.append(BomVO.HBDEFAULT, "Y");
        sql.and();
        sql.append(BomVO.HFVERSIONTYPE, VersionTypeEnum.AVAILABLE.toIntValue());// 查询有效的bom
        sql.appendDr();

        BomVO[] bomVOs = queryService.query(sql.toString(), null);
        List<String> result = new ArrayList<String>();
        for (BomVO bomVO : bomVOs) {
            result.add(bomVO.getCbomid());
        }
        if (MMValueCheck.isNotEmpty(result)) {
            return result;
        }
        return null;

    }

    /**
     * 判断指定条件的BOM/配置BOM的无效/有效的默认版本是否存在
     *
     * @param pkGroup     集团主键
     * @param pkOrg       组织主键
     * @param materialVid 物料版本主键
     * @param version     Bom版本号
     * @return 已存在BOM无效默认版本pk
     */
    public ArrayList<String> isBomOrCfgBomDefaultVersionExist(String pkOrg, String cmaterialoid, String materialVid,
                                                              Integer bomtype, Integer hfversiontype) {
        VOQuery<BomVO> queryService = new VOQuery<BomVO>(BomVO.class, new String[] { BomVO.CBOMID });
        MMSqlBuilder sql = new MMSqlBuilder();
        sql.and();
        sql.append(BomVO.PK_GROUP, AppBsContext.getInstance().getPkGroup());
        sql.and();
        sql.append(BomVO.PK_ORG, pkOrg);
        sql.and();
        sql.append(BomVO.HCMATERIALID, cmaterialoid);
        if (materialVid == null) {
            sql.and();
            sql.append(BomVO.HCMATERIALVID, "~");
        } else {
            sql.and();
            sql.append(BomVO.HCMATERIALVID, materialVid);
        }
        sql.and();
        sql.append(BomVO.FBOMTYPE, bomtype);
        sql.and();
        sql.append(BomVO.HFBOMCATEGORY, 1);
        sql.and();
        sql.append(BomVO.HBDEFAULT, "Y");
        sql.and();
        sql.append(BomVO.HBCUSTOMIZED, "N");// 是否定制值为否
        sql.and();
        sql.append(BomVO.HFVERSIONTYPE, hfversiontype);
        sql.appendDr();

        BomVO[] bomVOs = queryService.query(sql.toString(), null);
        ArrayList<String> cbomids = new ArrayList<String>();
        if (MMValueCheck.isNotEmpty(bomVOs)) {
            for (BomVO bomvo : bomVOs) {
                if (MMValueCheck.isNotEmpty(bomvo)) {
                    cbomids.add(bomvo.getCbomid());
                }
            }
            return cbomids;
        }
        return null;

    }

    @Override
    public void updateBomForBomCopy0214(AggBomVO[] aggvos, AggBomVO[] origins, boolean isCheckEcn) {
        // 加锁 + 检查ts
        GCBillTransferTool<AggBomVO> transTool = new GCBillTransferTool<AggBomVO>(aggvos);
        // 补全前台VO
        AggBomVO[] fullBills = transTool.getClientFullInfoBill();
        // 获得修改前vo
        AggBomVO[] originBills = transTool.getOriginBills();
        Set<String> ids = new HashSet<String>();
        for (AggBomVO aggBomVO : originBills) {
            ids.add(aggBomVO.getPrimaryKey());
        }

        BomUpdateBP updatebp = new BomUpdateBP();
        updatebp.update(fullBills, origins, false, false, false, ids.toArray(new String[0]), false);

    }

    private IBomBillQueryService getBomBillQueryService() {
        return NCLocator.getInstance().lookup(IBomBillQueryService.class);
    }

    @Override
    public void deleteCustomizedBom(AggBomVO[] aggvos) throws BusinessException {
        if (aggvos == null || aggvos.length == 0) {
            return;
        }
        try {
            // 加锁 + 检查ts
            GCBillTransferTool<AggBomVO> transTool = new GCBillTransferTool<AggBomVO>(aggvos);
            // 补全前台VO
            AggBomVO[] fullBills = transTool.getClientFullInfoBill();
            BomDeleteBP bp = new BomDeleteBP();
            bp.deleteCustomizedBom(fullBills);
        } catch (Exception ex) {
            ExceptionUtils.marsh(ex);
        }
    }

}
