package nccloud.web.mmpac.pickm.action;

import nc.itf.mmpac.pickm.IPickmQueryService;
import nc.itf.mmpac.pmo.pac0002.IPMOMaintainService;
import nc.itf.pu.m20.IPraybillMaintain;
import nc.itf.uap.pf.busiflow.PfButtonClickContext;
import nc.util.mmf.busi.service.PFPubService;
import nc.util.mmf.framework.base.MMValueCheck;
import nc.vo.mmpac.pickm.entity.AggPickmVO;
import nc.vo.mmpac.pickm.entity.PickmItemVO;
import nc.vo.mmpac.pmo.pac0002.entity.PMOAggVO;
import nc.vo.mmpac.pmo.pac0002.entity.PMOHeadVO;
import nc.vo.mmpac.pmo.pac0002.entity.PMOItemVO;
import nc.vo.pu.m20.entity.PraybillHeaderVO;
import nc.vo.pu.m20.entity.PraybillVO;
import nc.vo.pub.AggregatedValueObject;
import nc.vo.pub.BusinessException;
import nc.vo.pub.compiler.PfParameterVO;
import nccloud.dto.mmpac.pickm.pub.entity.PickmQueryInfoDTO;
import nccloud.framework.core.exception.ExceptionUtils;
import nccloud.framework.core.json.IJson;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.web.action.itf.ICommonAction;
import nccloud.framework.web.container.IRequest;
import nccloud.framework.web.json.JsonFactory;

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

public class PickmToPmo implements ICommonAction {
    @Override
    public Object doAction(IRequest iRequest) {
        String read = iRequest.read();
        IJson json = JsonFactory.create();
        try {
            // 获取请求查询信息
            PickmQueryInfoDTO paramDTO = json.fromJson(read, PickmQueryInfoDTO.class);
            // 获取主键
            String[] cpickmids = paramDTO.getCpickmids();
//            String[] cpickmbids = paramDTO.getCpickmbids();
//            if (MMValueCheck.isEmpty(cpickmids) && (null == cpickmbids || cpickmbids.length == 0)) {
//                return null;
//            }
            AggPickmVO[] aggVOs = null;
            IPickmQueryService service = ServiceLocator.find(IPickmQueryService.class);
            if (MMValueCheck.isNotEmpty(cpickmids)) {
                aggVOs = service.queryBillsByPks(cpickmids);
            }
            if (MMValueCheck.isEmpty(aggVOs)) {
                /*@res "单据已被修改或删除，请刷新界面重新操作！"*/
                ExceptionUtils.wrapBusinessException(nc.vo.ml.NCLangRes4VoTransl.getNCLangRes().getStrByID("5008100_0", "05008100-0009"));
            }


            PMOAggVO[] prayVOs = convertToGeneralInVO(processAggVOs(aggVOs), null);
            for (PMOAggVO prayVO : prayVOs) {
                for (int j=0;j<prayVO.getChildrenVO().length;j++) {
                    prayVO.getChildrenVO()[j].setVrowno(String.valueOf(j*10+10));
                }
            }
            IPMOMaintainService maintain= ServiceLocator.find(IPMOMaintainService.class);
            PMOAggVO[] insertVos = maintain.insert(prayVOs);
            Map<String, Object> returnMap = new HashMap<>();
            returnMap.put("data", insertVos);
            returnMap.put("success", true);
            return returnMap;
        } catch (Exception e) {
            ExceptionUtils.wrapException(e);
        }
        return null;
    }
    private PMOAggVO[] convertToGeneralInVO(AggregatedValueObject[] sourceBillVOs, PfParameterVO srcParaVo)
            throws BusinessException {
        // 来源交易类型或单据类型，需要在单据类型中注册
        String srcBillOrTranstype = "55A3";
        // 目标交易类型或单据类型，需要在单据类型中注册
        String destBillOrTranstype = "55A2";
        // classifyMode int型参数，调用模式，参照PfButtonClickContext中定义，代码中调用为接口方式 ClassifyByItfdef
        int classifyMode = PfButtonClickContext.ClassifyByItfdef;
        PMOAggVO[] inVOS = (PMOAggVO[]) PFPubService.runChangeData(srcBillOrTranstype, destBillOrTranstype, sourceBillVOs, srcParaVo, classifyMode);
        if (MMValueCheck.isEmpty(inVOS)) {
            ExceptionUtils.wrapBusinessException("备料计划转换流程生产订单失败");
        }
        for (PMOAggVO inVO : inVOS) {
            // 其它入库单的仓库、交易类型取自【业务参数设置】的默认值
            PMOHeadVO head = inVO.getParentVO();
            head.setCtrantypeid("0001A110000000001S1E");

            for (PMOItemVO itemVO: inVO.getChildrenVO()){

            }
            // head.setCwarehouseid("");
        }
        return inVOS;
    }

    public AggPickmVO[] processAggVOs(AggPickmVO[] aggVOs) {
        Map<Object, List<AggPickmVO>> groupMap = new HashMap<>();

        for (AggPickmVO vo : aggVOs) {
            Object pk_org = vo.getParentVO().getPk_org();
            groupMap.computeIfAbsent(pk_org, k -> new ArrayList<>()).add(vo);
        }

        List<AggPickmVO> resultList = new ArrayList<>();

        for (Map.Entry<Object, List<AggPickmVO>> entry : groupMap.entrySet()) {
            List<AggPickmVO> group = entry.getValue();

            // 修改1：使用ISuperVO列表收集子对象
            List<PickmItemVO> mergedChildren = new ArrayList<PickmItemVO>();
            for (AggPickmVO vo : group) {
                PickmItemVO[] items = (PickmItemVO[]) vo.getChildren(PickmItemVO.class);
                if (items != null) {
                    for (PickmItemVO child : items) {
                        //只合并项目专用料数据
                        if(child.getBprojectmaterial().booleanValue()){
                            mergedChildren.add(child);
                        }
                        // CircularlyAccessibleValueObject 实现了 ISuperVO
                    }
                }
            }
            if(mergedChildren.size() == 0){
                continue;
            }

            AggPickmVO newVO = new AggPickmVO();
            newVO.setParent(group.get(0).getParentVO());
            // 修改2：转换为ISuperVO数组
            newVO.setChildren(PickmItemVO.class, mergedChildren.toArray(new PickmItemVO[0]));

            resultList.add(newVO);
        }

        return resultList.toArray(new AggPickmVO[0]);
    }
}
