package nccloud.api.so.so.UpCloses;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import nc.bs.framework.common.NCLocator;
import nc.itf.so.m30.closemanage.ISaleOrderCloseManageMaintain;
import nc.pubitf.so.m30.api.ISaleOrderQueryAPI;
import nc.pubitf.uapbd.IRateTypePubService;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.scmpub.util.CombineViewToAggUtil;
import nc.vo.so.m30.entity.SaleOrderBVO;
import nc.vo.so.m30.entity.SaleOrderHVO;
import nc.vo.so.m30.entity.SaleOrderVO;
import nc.vo.so.m30.entity.SaleOrderViewVO;
import nccloud.api.rest.utils.IJsonForAPI;
import nccloud.api.rest.utils.JsonFactoryForAPI;
import nccloud.api.rest.utils.ResultMessageUtil;
import nccloud.framework.core.json.IJson;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.web.json.JsonFactory;
import nccloud.pubitf.arap.arappub.IArapBillPubUtilService;
import nccloud.pubitf.scmpub.pub.batchopr.dto.ISCMBatchOprContext;
import nccloud.pubitf.scmpub.pub.batchopr.dto.SCMBatchOprContext;
import nccloud.pubitf.scmpub.pub.batchopr.dto.SCMBatchResultDTO;
import nccloud.pubitf.so.saleorderclose.service.IQuerySaleOrderCloseService;
import nccloud.pubitf.so.saleorderclose.service.ISaleOrderCloseMaintainService;
import nccloud.pubitf.so.saleorderclose.utils.SaleOrderCloseUtils;
import nccloud.util.so.TransBillUtil;
import nccloud.web.scmpub.pub.resexp.PfResumeExceptionNccUtils;
import nccloud.web.scmpub.pub.utils.SCMBatchOperatorResult;
import nccloud.web.scmpub.pub.utils.batchopr.SCMBatchOperator;
import nccloud.web.scmpub.vocheck.VOSagaFrozenCheck;
import nccloud.web.so.saleorderclose.entity.SaleOrderCloseInfo;
import nccloud.api.so.so.UpCloses.SaleOrderCloseUtil;
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.Arrays;
import java.util.HashMap;
import java.util.Map;

@Path("so/so/Close")
public class CloseSoResource extends AbstractNCCRestResource {
    @Override
    public String getModule() {
        return "so";
    }
    @POST
    @Path("/ClosesoWith")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString CloseSoResource(JSONString json) {
        JSONObject errojson = new JSONObject();
        try {
            JSONObject jObject = JSON.parseObject(json.toJSONString());
            if (jObject == null) {
                return ResultMessageUtil.exceptionToJSON(new NullPointerException("JSONString:null"));
            }
            JSONArray array = jObject.getJSONArray("bills");
            if (array.isEmpty()) {
                return ResultMessageUtil.exceptionToJSON(new NullPointerException("请选择销售订单"));
            }
            String[] ids = new String[array.size()];
            for (int i = 0; i < array.size(); i++) {
                SaleOrderVO saleOrderVO = new SaleOrderVO();
                String pk = (String) array.getJSONObject(i).getOrDefault("pk", "");
                ids[i] = pk;

            }
            ISaleOrderQueryAPI iSaleOrderQueryAPI= NCLocator.getInstance()
                    .lookup(ISaleOrderQueryAPI.class);
            SaleOrderVO[] billvos = iSaleOrderQueryAPI.queryVOByIDs(ids);
            billvos = Arrays.stream(billvos)
                    .filter(vo -> vo.getParentVO().getFstatusflag() != 4)
                    .toArray(SaleOrderVO[]::new);
            if(billvos.length == 0){
                errojson.put("status", "1");
                errojson.put("message", "单据已经被关闭");
                errojson.put("codeList", "");
                return ResultMessageUtil.toJSON(errojson);

            }
//            ISCMBatchOprContext context = new SCMBatchOprContext();
//            context.setInterfaceName("nc.itf.so.m30.closemanage.ISaleOrderCloseManageMaintain");
//            context.setMethodName("closeSaleOrder");
//            context.setParamTypes(new Class[]{SaleOrderVO[].class});
//            context.setParams(new Object[]{billvos});
//            context.setBillPos(0);

//            SCMBatchResultDTO resulet = SCMBatchOperator.doRemoteCall(context);
            ISaleOrderCloseManageMaintain iSaleOrderCloseManageMaintain = NCLocator.getInstance()
                    .lookup(ISaleOrderCloseManageMaintain.class);
            SaleOrderVO[] saleOrderVOS= iSaleOrderCloseManageMaintain.closeSaleOrder(billvos);
            if(saleOrderVOS.length == 0){
                errojson.put("status", "0");
                errojson.put("message", "关闭失败");
                errojson.put("codeList", "");
                return ResultMessageUtil.toJSON(errojson);

            }
            errojson.put("status", "1");
            errojson.put("message", "成功关闭");
            errojson.put("codeList", "");
            // 返回表示操作成功的JSON字符串
            return ResultMessageUtil.toJSON(errojson);



        } catch (Exception e) {
            errojson.put("status", "0");
            errojson.put("message", e.getMessage());
            errojson.put("codeList", "");
            // 返回表示操作失败的JSON字符串
            return ResultMessageUtil.toJSON(errojson);
        }
    }
    @POST
    @Path("/OpenClose")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString OpenClose(JSONString json) {
        JSONObject errojson = new JSONObject();
        try {
            JSONObject jObject = JSON.parseObject(json.toJSONString());
            if (jObject == null) {
                return ResultMessageUtil.exceptionToJSON(new NullPointerException("JSONString:null"));
            }
            JSONArray array = jObject.getJSONArray("bids");
            if (array.isEmpty()) {
                return ResultMessageUtil.exceptionToJSON(new NullPointerException("请选择销售订单"));
            }
            String[] stringArray = new String[array.size()];

            for (int i = 0; i < array.size(); i++) {
                // 直接获取每个元素的字符串形式
                stringArray[i] = array.getString(i);
            }

            SaleOrderViewVO[] vos = queryViewByBIDs(stringArray, "");
            CombineViewToAggUtil<SaleOrderVO> combineViewToAggUtil = new CombineViewToAggUtil(SaleOrderVO.class, SaleOrderHVO.class, SaleOrderBVO.class);
            SaleOrderVO[] bills = (SaleOrderVO[])combineViewToAggUtil.combineViewToAgg(vos, "csaleorderid");

            bills = Arrays.stream(bills)
                    .filter(vo -> vo.getParentVO().getFstatusflag() == 4)
                    .toArray(SaleOrderVO[]::new);
            if(bills.length == 0){
                errojson.put("status", "1");
                errojson.put("message", "打开成功");
                errojson.put("codeList", "");
                // 返回表示操作成功的JSON字符串
                return ResultMessageUtil.toJSON(errojson);
            }
            SaleOrderViewVO[] result = this.buttonClick(bills, "billOpen");
            if (result.length  == 0 ){
                errojson.put("status", "0");
                errojson.put("message", "打开失败");
                errojson.put("codeList", "");
                return ResultMessageUtil.toJSON(errojson);

            }
            errojson.put("status", "1");
            errojson.put("message", "打开成功");
            errojson.put("codeList", "");
            // 返回表示操作成功的JSON字符串
            return ResultMessageUtil.toJSON(errojson);



        } catch (Exception e) {
            errojson.put("status", "0");
            errojson.put("message", e.getMessage());
            errojson.put("codeList", "");
            // 返回表示操作失败的JSON字符串
            return ResultMessageUtil.toJSON(errojson);
        }
    }
    private void setCloseOpenReason(SaleOrderVO[] bills,String reason) {
        for(SaleOrderVO bill : bills) {
            SaleOrderBVO[] bodys = bill.getChildrenVO();

            for(SaleOrderBVO body : bodys) {
                body.setVclosereason(reason);
            }
        }

    }








    public static SaleOrderViewVO[] buttonClick(SaleOrderVO[] bills, String buttonType) throws BusinessException {
        ISaleOrderCloseMaintainService service=NCLocator.getInstance()
                .lookup(ISaleOrderCloseMaintainService.class);
        SaleOrderViewVO[] saleOrderViewVOS= service.billOpen(bills,false);
        return saleOrderViewVOS;
    }

    public static SaleOrderViewVO[] queryViewByBIDs(String[] bidts, String vclosereason) throws BusinessException {
        Map<String, UFDateTime> bid_ts = new HashMap();
        String[] bids = TransBillUtil.splitBidts(bidts, bid_ts);
        IQuerySaleOrderCloseService service = NCLocator.getInstance()
                .lookup(IQuerySaleOrderCloseService.class);
        SaleOrderViewVO[] vos = service.queryByIds(bids);
        TransBillUtil.fillBodyTs(vos, "csaleorderbid", bid_ts);
        SaleOrderCloseUtils.setCloseOpenReason(vos, vclosereason);
        return vos;
    }





}
