//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package nccloud.web.sscivm.ivsale.application.invoice.action;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import nc.bs.sscivm.ivsale.util.IVApplicationSlsmUtil;
import nc.bs.sscivm.logger.SSCIVMLogger;
import nc.vo.ml.NCLangRes4VoTransl;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.pub.lang.UFDouble;
import nc.vo.sscivm.ivmpub.IVAplocationKPFS;
import nc.vo.sscivm.ivsale.IVApplicationAggVO;
import nc.vo.sscivm.ivsale.IVApplicationBodyVO;
import nc.vo.sscivm.ivsale.IVApplicationHeadVO;
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 nccloud.framework.web.processor.template.BillCardConvertProcessor;
import nccloud.framework.web.ui.pattern.billcard.BillCard;
import nccloud.itf.sscivm.ivsale.service.IVApplicationInvoiceService;
import nccloud.itf.sscivm.ivsale.service.IVApplicationQueryService;
import nccloud.web.sscivm.ivsale.application.util.ApplicationMainUtil;

public class ApplicationSplitMergeMakeInvoiceAction implements ICommonAction {
    public ApplicationSplitMergeMakeInvoiceAction() {
    }

    public Object doAction(IRequest request) {
        IJson json = JsonFactory.create();
        String read = request.read();
        JSONObject param = JSONObject.parseObject(read);
        String slsm = param.getString("slsm");
        IVApplicationInvoiceService ivService = (IVApplicationInvoiceService)ServiceLocator.find(IVApplicationInvoiceService.class);
        JSONObject clazz = new JSONObject();
        Map<String, UFDateTime> pkTsMap = new HashMap();

        try {
            List<IVApplicationAggVO> appVos = new ArrayList();
            Map<String, String> appIdMap = new HashMap();
            JSONArray paramDatas = param.getJSONArray("datas");

            for(int i = 0; i < paramDatas.size(); ++i) {
                String Id = paramDatas.getJSONObject(i).getString("id");
                BillCard billcard = (BillCard)json.fromJson(paramDatas.getJSONObject(i).getString("rightdata"), BillCard.class);
                billcard.setPageid("105802SQ_KPConfirm");
                BillCardConvertProcessor processor = new BillCardConvertProcessor();
                IVApplicationAggVO vo = (IVApplicationAggVO)processor.fromBillCard(billcard);
                vo = ApplicationMainUtil.transToExtAggVO(billcard, vo);
                appVos.add(vo);
                appIdMap.put(vo.getParentVO().getPk_ivapplication(), Id);
            }

            IVApplicationAggVO[] vos = this.checkAppVOs(appVos, clazz);

            for(IVApplicationAggVO vo : vos) {
                vo = IVApplicationSlsmUtil.updateSlsm(vo, slsm);
                JSONObject single = new JSONObject();
                pkTsMap.put(vo.getParentVO().getPk_ivapplication(), vo.getParentVO().getTs());
                ivService.makeInvoice(new IVApplicationAggVO[]{vo}, single, pkTsMap, false);
                if (!clazz.containsKey("successNum")) {
                    clazz.put("successNum", single.getIntValue("successNum"));
                    clazz.put("failNum", single.getIntValue("failNum"));
                    clazz.put("failData", single.get("failData"));
                } else {
                    int successNum = clazz.getIntValue("successNum");
                    int failNum = clazz.getIntValue("failNum");
                    List<Map<String, String>> failMapList = (List)clazz.get("failData");
                    int ssuccessNum = single.getIntValue("successNum");
                    int sfailNum = single.getIntValue("failNum");
                    List<Map<String, String>> sfailMapList = (List)single.get("failData");
                    failMapList.addAll(sfailMapList);
                    clazz.put("successNum", successNum + ssuccessNum);
                    clazz.put("failNum", failNum + sfailNum);
                    clazz.put("failData", failMapList);
                    if (ssuccessNum > 0) {
                        String id = clazz.getString("id");
                        if (id == null) {
                            id = (String)appIdMap.get(vo.getParentVO().getPk_ivapplication());
                        } else {
                            id = id + "," + (String)appIdMap.get(vo.getParentVO().getPk_ivapplication());
                        }

                        clazz.put("id", id);
                    }
                }
            }
        } catch (Exception e) {
            SSCIVMLogger.error(e.getMessage(), e);
            ExceptionUtils.wrapException(e);
        }

        return clazz;
    }

    private IVApplicationAggVO[] checkAppVOs(List<IVApplicationAggVO> appVos, JSONObject clazz) throws BusinessException {
        int failNum = 0;
        List<Map<String, String>> failMapList = new ArrayList();
        List<IVApplicationAggVO> newAppVos = new ArrayList();
        List<IVApplicationAggVO> lastAppVos = new ArrayList();
        Map<String, UFDateTime> pkTsMap = new HashMap();
        Set<String> appIds = new HashSet();
        Set<String> noCheck = new HashSet();

        for(IVApplicationAggVO appVo : appVos) {
            IVApplicationBodyVO[] bodyVos = appVo.getBodyVOs();
//            if (appVo.getParentVO().getKpfs() != null && appVo.getParentVO().getKpfs() != IVAplocationKPFS.ZLKP.toIntValue() && bodyVos[0].getPk_ivappdetail().length() > 20) {
//                Map<String, String> failMap = new HashMap();
//                failMap.put("billNo", appVo.getParentVO().getBillno());
//                failMap.put("msg", NCLangRes4VoTransl.getNCLangRes().getStrByID("1058sal_0", "01058sal-0106"));
//                failMapList.add(failMap);
//                ++failNum;
//            } else {
                if (bodyVos[0].getPk_ivappdetail().length() > 20) {
                    for(IVApplicationBodyVO bodyVo : bodyVos) {
                        String detailpk = bodyVo.getPk_ivappdetail();
                        JSONArray arr = JSONArray.parseArray(bodyVo.getPk_ivappdetail());

                        for(int i = 0; i < arr.size(); ++i) {
                            String pk_ivapplication = arr.getJSONObject(i).getString("pk_ivapplication");
                            appIds.add(pk_ivapplication);
                        }
                    }
                } else {
                    appIds.add(appVo.getParentVO().getPk_ivapplication());
                }

                newAppVos.add(appVo);
            }
//        }

        if (appIds.size() == 0) {
            return (IVApplicationAggVO[])newAppVos.toArray(new IVApplicationAggVO[0]);
        } else {
            IVApplicationQueryService queryser = (IVApplicationQueryService)ServiceLocator.find(IVApplicationQueryService.class);

            for(IVApplicationHeadVO oldHeadVo : queryser.queryHeadVOsByPks((String[])appIds.toArray(new String[0]))) {
                if (oldHeadVo.getInvoiced_jshj().compareTo(UFDouble.ZERO_DBL) != 0 || oldHeadVo.getInvoiceing_jshj().compareTo(UFDouble.ZERO_DBL) != 0) {
                    noCheck.add(oldHeadVo.getPk_ivapplication());
                }

                pkTsMap.put(oldHeadVo.getPk_ivapplication(), oldHeadVo.getTs());
            }

            for(IVApplicationAggVO appVo : appVos) {
                IVApplicationBodyVO[] bodyVos = appVo.getBodyVOs();
                boolean pass = true;
                if (bodyVos[0].getPk_ivappdetail().length() > 20) {
                    Set<String> ids = new HashSet();

                    for(IVApplicationBodyVO bodyVo : bodyVos) {
                        JSONArray arr = JSONArray.parseArray(bodyVo.getPk_ivappdetail());

                        for(int i = 0; i < arr.size(); ++i) {
                            String pk_ivapplication = arr.getJSONObject(i).getString("pk_ivapplication");
                            if (!ids.contains(pk_ivapplication) && !noCheck.contains(pk_ivapplication)) {
                                ids.add(pk_ivapplication);
                                String ts = arr.getJSONObject(i).getString("ts");
                                if ((new UFDateTime(ts)).compareTo((UFDateTime)pkTsMap.get(pk_ivapplication)) != 0) {
                                    Map<String, String> failMap = new HashMap();
                                    failMap.put("billNo", appVo.getParentVO().getBillno());
                                    failMap.put("msg", NCLangRes4VoTransl.getNCLangRes().getStrByID("1058sal_0", "01058sal-0057"));
                                    failMapList.add(failMap);
                                    ++failNum;
                                    pass = false;
                                }
                            }
                        }
                    }
                } else if (!noCheck.contains(appVo.getParentVO().getPk_ivapplication()) && appVo.getParentVO().getTs().compareTo((UFDateTime)pkTsMap.get(appVo.getParentVO().getPk_ivapplication())) != 0) {
                    Map<String, String> failMap = new HashMap();
                    failMap.put("billNo", appVo.getParentVO().getBillno());
                    failMap.put("msg", NCLangRes4VoTransl.getNCLangRes().getStrByID("1058sal_0", "01058sal-0057"));
                    failMapList.add(failMap);
                    ++failNum;
                    pass = false;
                    continue;
                }

                if (pass) {
                    lastAppVos.add(appVo);
                }
            }

            clazz.put("successNum", 0);
            clazz.put("failNum", failMapList.size());
            clazz.put("failData", failMapList);
            return (IVApplicationAggVO[])lastAppVos.toArray(new IVApplicationAggVO[0]);
        }
    }

    private JSONArray converDetailPkToJSONArray(String detailPk) {
        JSONArray jsonArr = new JSONArray();
        List<String> datas = new ArrayList();
        detailPk = detailPk.substring(1, detailPk.length() - 1);
        int start = 0;
        int end = 0;

        for(int i = 0; i < detailPk.length(); ++i) {
            if (detailPk.charAt(i) == '{') {
                start = i;
            }

            if (detailPk.charAt(i) == '}') {
                datas.add(detailPk.substring(start, i + 1));
            }
        }

        for(String data : datas) {
            data = data.substring(1, data.length() - 1);
            JSONObject json = new JSONObject();
            String[] values = data.split(",");

            for(String value : values) {
                value = value.trim();
                String[] vas = value.split("=");
                json.put(vas[0], vas[1]);
            }

            jsonArr.add(json);
        }

        return jsonArr;
    }
}
