package nc.bs.so.m30.maintain.rule.insert;

import nc.bs.framework.common.NCLocator;
import nc.impl.pubapp.pattern.rule.IRule;
import nc.itf.bd.material.sale.IMaterialSaleService;
import nc.md.persist.framework.IMDPersistenceQueryService;
import nc.vo.bd.material.sale.MaterialSaleVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDouble;
import nc.vo.so.m30.entity.SaleOrderBVO;
import nc.vo.so.m30.entity.SaleOrderVO;

import java.util.ArrayList;

public class WritebackMaterialPriceRule implements IRule<SaleOrderVO>{


    @Override
    public void process(SaleOrderVO[] vos) {
        // TODO Auto-generated method stub
        for (SaleOrderVO vo : vos) {
            //根据销售订单子表的物料编码和销售组织查询物料主表
            SaleOrderBVO[] saleOrderitems =  vo.getChildrenVO();
            //循环销售订单子表
            for(int i = 0; i < saleOrderitems.length; i++) {
                SaleOrderBVO item = saleOrderitems[i];
                //取销售订单子表的物料编码和销售组织
                String cmaterialvid = item.getCmaterialvid(); //物料主键
                String pk_org = item.getPk_org(); //销售组织
                UFDouble nqtorigprice = item.getNqtorigprice(); //无税单价
                IMDPersistenceQueryService aggvoQueryService = NCLocator.getInstance().lookup(IMDPersistenceQueryService.class);
                // 条件查询得到物料MaterialSaleVO
                try {
                    String whereSql = "nvl(bd_materialsale.dr,0) = 0 and bd_materialsale.pk_material = '" + cmaterialvid + "' and bd_materialsale.pk_org = '" + pk_org + "'";
                    @SuppressWarnings("unchecked")
                    ArrayList<MaterialSaleVO> materialSaleVOs = (ArrayList<MaterialSaleVO>)aggvoQueryService.queryBillOfVOByCond(MaterialSaleVO.class, whereSql, true, false);
                    if(materialSaleVOs.size() <= 0) {
                        continue;
                    }
                    for(MaterialSaleVO materialSaleVO : materialSaleVOs) {
                        materialSaleVO.setResaleprice(nqtorigprice);
                        //实体更新物料销售表
//							IMaterialSaleService iMaterialSaleService = ServiceLocator.find(IMaterialSaleService.class);
                        IMaterialSaleService iMaterialSaleService = NCLocator.getInstance().lookup(IMaterialSaleService.class);
                        iMaterialSaleService.updateMaterialSaleVO(materialSaleVO);
                    }
                }catch(BusinessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

}
