package nc.api.mmpac.resource;

import com.alibaba.fastjson.JSONObject;
import nc.bs.framework.common.NCLocator;
import nc.bs.logging.Log;
import nc.bs.trade.business.HYPubBO;
import nc.bs.trade.business.HYSuperDMO;
import nc.impl.mmpac.apply.task.TaskAMaintainServiceImpl;
import nc.itf.mmpac.apply.task.ITaskABusinessService;
import nc.itf.mmpac.apply.task.ITaskAMaintainService;
import nc.itf.mmpac.apply.task.ITaskAQueryService;
import nc.itf.mmpac.pmo.pac0002.IPMOQueryService;
import nc.itf.uap.IUAPQueryBS;
import nc.itf.uap.pf.IPfExchangeService;
import nc.util.mmf.framework.base.MMArrayUtil;
import nc.util.mmf.framework.base.MMCollectionUtil;
import nc.util.mmf.framework.base.MMValueCheck;
import nc.vo.mmpac.apply.task.entity.AggTaskAVO;
import nc.vo.mmpac.apply.task.entity.TaskABVO;
import nc.vo.mmpac.pmo.pac0002.entity.PMOAggVO;
import nc.vo.mmpac.pmo.pac0002.entity.PMOItemVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.CircularlyAccessibleValueObject;
import nc.vo.pub.compiler.PfParameterVO;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDouble;
import nccloud.api.rest.utils.ResultMessageUtil;
import nccloud.framework.service.ServiceLocator;
import nccloud.pubitf.mmpac.pmo.service.IPublicPMOService4Activity;
import nccloud.ws.rest.resource.AbstractNCCRestResource;
import org.json.JSONString;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import java.util.*;

@Path("mmpac/applytask")
public class ApplytaskRestResource  extends AbstractNCCRestResource {
    HYSuperDMO dmo = null;
    private static final Log logger = Log.getInstance("pmoresoucelogger");
    public HYSuperDMO getSuperDMO() {
        if (dmo == null) {
            dmo = new HYSuperDMO();
        }
        return dmo;
    }
    public ApplytaskRestResource() {
    }
    @Override
    public String getModule() {
        return "mmpac";
    }

    @POST
    @Path("/save")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString save(Map<String, Object> paramMap) throws BusinessException {
        logger.debug("=================开始进行================");
        List<Map<String, Object>> paramList = (List) paramMap.get("data");
        if (paramList == null || paramList.size() == 0) {
            throw new BusinessException("数据不能为空");
        }
        HYPubBO hybo = new HYPubBO();
        List<String> ids = new ArrayList<String>();
        List<String> bids= new ArrayList<>();
        List<AggTaskAVO> aggTaskAVOS = new ArrayList<>();
        for (Map<String, Object> param : paramList) {
           Object orderId= hybo.findColValue("mm_pmo","cpmohid"," vbillcode  ='" + param.get("billcode") + "' ");
           String mrlCode= (String) param.get("mrlcode");
           String mrlid=(String) hybo.findColValue("bd_material","pk_material"," code  = '" + mrlCode + "' ");
           if(mrlid == null){
               throw new BusinessException("产品编码不能为空");
           }
            if (orderId != null && !orderId.equals("")) {
               PMOAggVO[] pmoaggvos = ((IPMOQueryService)NCLocator.getInstance().lookup(IPMOQueryService.class)).queryByPks(new String[]{(String) orderId});
               if (pmoaggvos == null || pmoaggvos.length == 0) {

               }else{
                   for (PMOAggVO pmoaggvo : pmoaggvos) {
                       for (PMOItemVO pmoItemVO:   pmoaggvo.getChildrenVO()){
                              if(pmoItemVO.getCmaterialvid().equals(mrlid)){
                                  ids.add(pmoaggvo.getParentVO().getCpmohid()) ;
                                  bids.add(pmoItemVO.getCmoid());
                                  AggTaskAVO[] aggvos = pushActivity((String[]) ids.toArray(new String[ids.size()]), (String[]) bids.toArray(new String[ids.size()]));
                                  if (aggvos == null || aggvos.length == 0) {

                                  }else {
                                      Object cactivityid= hybo.findColValue("bd_activity","cactivityid"," vactivitycode  ='G001' ");

                                      for (AggTaskAVO aggTaskAVO : aggvos) {
                                          aggTaskAVO.getParentVO();
                                          TaskABVO[] taskABVOS= (TaskABVO[])aggTaskAVO.getChildrenVO();
                                          for (TaskABVO taskABVO : taskABVOS) {
                                              taskABVO.setCactivityid((String) cactivityid);
                                              taskABVO.setNactnum(new UFDouble((double) param.get("workTime")) );
                                              String month = (String) param.get("month");

                                              taskABVO.setDtaskdate(UFDate.getDate(month) );
//                                              taskABVO.setNactnum(new UFDouble((double) param.get("workTime")) );

                                          }
                                          aggTaskAVOS.add(aggTaskAVO);
                                      }
                                  }
                              }
                       }
                   }
               }

           }
        }



        ITaskAMaintainService iTaskAQueryService = NCLocator.getInstance().lookup(ITaskAMaintainService.class);
        AggTaskAVO[] sourceVOs = iTaskAQueryService.insert(aggTaskAVOS.toArray(new AggTaskAVO[aggTaskAVOS.size()]));
        JSONObject errojson = new JSONObject();
        errojson.put("data", sourceVOs);
        errojson.put("status", "1");
        errojson.put("message", "保存成功");
        errojson.put("codeList", "");
        // 返回表示操作成功的JSON字符串
        return ResultMessageUtil.toJSON(errojson);
    }
    public AggTaskAVO[] pushActivity(String[] ids, String[] bids) throws BusinessException {
        PMOAggVO[] pmoaggvos = ((IPMOQueryService)NCLocator.getInstance().lookup(IPMOQueryService.class)).queryByPks(ids);
        if (MMArrayUtil.isEmpty(pmoaggvos)) {
            return null;
        } else {
            if (MMArrayUtil.isNotEmpty(bids)) {
                Set<String> bidSet = new HashSet();

                for(String bid : bids) {
                    bidSet.add(bid);
                }

                PMOAggVO cardAggvo = pmoaggvos[0];
                List<PMOItemVO> filterList = new ArrayList();
                PMOItemVO[] items = cardAggvo.getChildrenVO();
                if (MMArrayUtil.isNotEmpty(items)) {
                    for(PMOItemVO item : items) {
                        if (!MMValueCheck.isEmpty(item) && bidSet.contains(item.getCmoid())) {
                            filterList.add(item);
                        }
                    }
                }

                if (MMCollectionUtil.isNotEmpty(filterList)) {
                    cardAggvo.setChildrenVO((CircularlyAccessibleValueObject[])filterList.toArray(new PMOItemVO[filterList.size()]));
                }
            }

            AggTaskAVO[] taskvos = ((ITaskABusinessService)NCLocator.getInstance().lookup(ITaskABusinessService.class)).fillTaskPmoInfo(pmoaggvos);
            return taskvos;
        }
    }
}
