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

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

import java.util.*;
import java.util.stream.Collectors;

import nc.bs.sscivm.ivsale.util.IVSaleUtil;
import nc.bs.sscivm.logger.SSCIVMLogger;
import nc.ui.querytemplate.querytree.IQueryScheme;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.pubapp.query2.sql.process.QueryCondition;
import nc.vo.pubapp.query2.sql.process.QuerySchemeProcessor;
import nc.vo.sscivm.ivsale.IVApplicationHeadVO;
import nc.vo.sscivm.ivsale.IVApplogVO;
import nccloud.dto.baseapp.querytree.dataformat.QueryTreeFormatVO;
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.container.RequestSysJsonVO;
import nccloud.framework.web.container.SessionContext;
import nccloud.framework.web.convert.translate.Translator;
import nccloud.framework.web.json.JsonFactory;
import nccloud.framework.web.ui.pattern.grid.Grid;
import nccloud.framework.web.ui.pattern.grid.GridOperator;
import nccloud.itf.sscivm.ivsale.service.IVApplicationQueryService;
import nccloud.pubitf.platform.query.INCCloudQueryService;
import nccloud.web.sscivm.ivsale.application.util.DataChangeLogic;

public class ApplicationQryAction implements ICommonAction {
    private static final String TS = "ts";
    private static final String PKS = "pks";

    public ApplicationQryAction() {
    }

    public Object doAction(IRequest request) {
        IJson json = JsonFactory.create();
        Map<String, Object> result = new HashMap();

        try {
            QueryTreeFormatVO info = (QueryTreeFormatVO) json.fromJson(request.read(), QueryTreeFormatVO.class);
            IVApplicationQueryService queryService = (IVApplicationQueryService) ServiceLocator.find(IVApplicationQueryService.class);
            String infoString = request.read();
            Map<String, Object> map = (Map) json.fromJson(infoString, Map.class);
            String pagecode = (String) map.get("pagecode");
            String areaid = (String) map.get("areaid");
            RequestSysJsonVO sysparam = request.readSysParam();
            String appcode = sysparam.getAppcode();
            Map<String, Object> pageInfo = (Map) map.get("pageInfo");
            GridOperator operator = new GridOperator(pagecode);
            Grid invApplication = null;
            Translator translator = new Translator();
            boolean sgbzflag = false;
            String pk_group = SessionContext.getInstance().getClientInfo().getPk_group();
            if (IVSaleUtil.isSgsq(appcode, pk_group)) {
                sgbzflag = true;
            }
            List<IVApplicationHeadVO> allApplicationAggVOList = null;
            if (info.getQuerycondition() != null) {
                INCCloudQueryService ncCloudQueryService = (INCCloudQueryService) ServiceLocator.find(INCCloudQueryService.class);
                IQueryScheme scheme = ncCloudQueryService.convertCondition(info);
                Map<String, List<String>> pkAndTsList = queryService.queryApplicationPksBySchema(scheme, appcode, sgbzflag);
                String pageSize = (String) pageInfo.get("pageSize");
                String pageNum = (String) pageInfo.get("pageIndex");
                // 拿到allApplicationVOList中的所有PK,以及查询参数中的FPHM 再查询一次数据库
                boolean isSpcialQuery = false;
                QuerySchemeProcessor processor = new QuerySchemeProcessor(scheme);
                QueryCondition kprq = processor.getQueryCondition("KPRQ");
                QueryCondition fphm = processor.getQueryCondition("FPHM");
                if (kprq == null && fphm == null) {
                    allApplicationAggVOList = queryService.queryApplicationsBySchema(scheme, pageSize, appcode, sgbzflag);
                } else {
                    allApplicationAggVOList = queryService.queryApplicationsBySchema(scheme, pageSize, appcode, sgbzflag, false);
                    isSpcialQuery = true;
                }
                // 查询数据库 如果 kprq 和 fphm 其中一个不为空 那么就不分页 手动分页查询
                String[] invoiceDate = {};
                String[] invoiceNums = {};
                String[] filteredPks = {};
                if (isSpcialQuery) {
                    if (kprq != null) {
                        invoiceDate = kprq.getValues();
                    }
                    if (fphm != null) {
                        invoiceNums = fphm.getValues();
                    }
                    if (allApplicationAggVOList.size() != 0) {
                        List<String> ivApplicationHeadVOS = allApplicationAggVOList.stream()
                                .map(IVApplicationHeadVO::getPk_ivapplication)
                                .collect(Collectors.toList());
                        filteredPks = ivApplicationHeadVOS.toArray(new String[0]);
                    }
                    // 如果条件中 填写了发票号码 执行此逻辑
                    if (invoiceDate != null && invoiceDate.length > 0 || invoiceNums != null && invoiceNums.length > 0) {
                        List<IVApplogVO> ivApplogVOS = queryService.queryByInvoiceNumberAndAggPK(filteredPks, invoiceDate, invoiceNums);
                        // 将allApplicationAggVOList的主键中 ivApplogVOS每一项的lyid是否包含在内
                        allApplicationAggVOList = allApplicationAggVOList.stream()
                                .filter(aggVO -> ivApplogVOS.stream()
                                        .anyMatch(logVO -> logVO.getLyid().equals(aggVO.getPk_ivapplication())))
                                .collect(Collectors.toList());
                    }
                    // 分页的PKS
                    filteredPks = allApplicationAggVOList.stream()
                            .map(IVApplicationHeadVO::getPk_ivapplication)
                            .collect(Collectors.toList()).toArray(new String[0]);
                    // 分页筛选
                    int subIndex = Math.min(allApplicationAggVOList.size(), Integer.parseInt(pageNum + 1) * Integer.parseInt(pageSize));
                    allApplicationAggVOList = allApplicationAggVOList
                            .subList(Integer.parseInt(pageNum), subIndex);
                }
                if (allApplicationAggVOList != null && allApplicationAggVOList.size() > 0) {
                    invApplication = operator.toGrid(allApplicationAggVOList.toArray(new IVApplicationHeadVO[allApplicationAggVOList.size()]));
                    invApplication.setPageid(pagecode);
                    DataChangeLogic.setViewScala(invApplication);
                    translator.translate(invApplication);
                    result.put(areaid, invApplication);
                    result.put("pks", filteredPks.length > 0 ? filteredPks : pkAndTsList.get("pks"));
                    result.put("ts", pkAndTsList.get("ts"));
                }
            } else {
                Map<String, Object> reqMap = (Map) json.fromJson(request.read(), Map.class);
                ArrayList<Object> pkList = (ArrayList) reqMap.get("pks");
                allApplicationAggVOList = queryService.queryHeadVOsByPks((String[]) pkList.toArray(new String[pkList.size()]), sgbzflag);
                if (allApplicationAggVOList != null && allApplicationAggVOList.size() > 0) {
                    invApplication = operator.toGrid(allApplicationAggVOList.toArray(new IVApplicationHeadVO[allApplicationAggVOList.size()]));
                    invApplication.setPageid(pagecode);
                    DataChangeLogic.setViewScala(invApplication);
                    translator.translate(invApplication);
                    result.put(areaid, invApplication);
                }
            }
        } catch (Exception e) {
            SSCIVMLogger.error(e.getMessage(), e);
            ExceptionUtils.wrappException(e);
        }

        return result;
    }
}
