package nccloud.pubimpl.gl.lightgl.assdetail;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;

import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.glcom.ass.assitem.cache.AccAssItemCache;
import nc.bs.logging.Logger;
import nc.gl.account.glconst.CurrTypeConst;
import nc.gl.utils.DataFormatUtilGL;
import nc.gl.utils.GLMultiLangUtil;
import nc.itf.bd.pub.IBDMetaDataIDConst;
import nc.itf.fi.pub.Currency;
import nc.itf.fi.pub.MeasdocUtils;
import nc.itf.gl.pub.ILinkQueryParamTransfer;
import nc.pub.gl.query.CBalanceAssTool;
import nc.pub.gl.query.GlQueryVOAssTool;
import nc.pubitf.accperiod.AccountCalendar;
import nc.pubitf.bd.accessor.GeneralAccessorFactory;
import nc.pubitf.bd.accessor.IGeneralAccessor;
import nc.ui.fi.uforeport.BSDataSourceControl;
import nc.vo.bd.accassitem.AccAssItemVO;
import nc.vo.bd.accessor.IBDData;
import nc.vo.bd.accessor.bankaccsub.BankaccsubBDDataVO;
import nc.vo.bd.account.AccountVO;
import nc.vo.bd.account.pub.AccountGLSimpleVO;
import nc.vo.bd.material.MaterialVO;
import nc.vo.bd.pub.BDCacheQueryUtil;
import nc.vo.fipub.freevalue.account.proxy.AccAssGL;
import nc.vo.fipub.freevalue.util.FreeValueDefUtil;
import nc.vo.fipub.utils.StrTools;
import nc.vo.gateway60.accountbook.AccountBookUtil;
import nc.vo.gateway60.itfs.AccountByPkThreadCache;
import nc.vo.gateway60.itfs.AccountUtilGL;
import nc.vo.gateway60.itfs.CalendarUtilGL;
import nc.vo.gl.detailbooks.DetailBSKey;
import nc.vo.gl.detailbooks.DetailBSVO;
import nc.vo.glcom.account.Balanorient;
import nc.vo.glcom.ass.AssAccessorManager;
import nc.vo.glcom.ass.AssVO;
import nc.vo.glcom.balance.GLQueryObj;
import nc.vo.glcom.balance.GlQryFormatVO;
import nc.vo.glcom.balance.GlQueryVO;
import nc.vo.glcom.tools.BaseCorpChooser;
import nc.vo.jcom.util.Convertor;
import nc.vo.ml.NCLangRes4VoTransl;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.pub.lang.UFDouble;
import nccloud.dto.gl.lightgl.displayformattool.ShowContentCenter;
import nccloud.pub.gl.lightgl.ColumnInfo;
import nccloud.pub.gl.lightgl.IColumnInfo;
import nccloud.pub.gl.tool.ReportExportUtil;
import nccloud.pubimpl.gl.account.AccountRepUtil;
import nccloud.pubimpl.gl.account.GLReportFormat;
import nccloud.pubimpl.gl.util.JsonUtils;

public class AssDetailBO {
    public Map<String, Object> queryAssBalance(Map<String, Object> params) throws BusinessException {
        BSDataSourceControl envInit = initEnvirment(params);
        try {
            GlQueryVO qryvo = null;
            // 判断是否为联查
            if (params.get("link") != null) {
                Class<?> clazz = Class.forName(params.get("class").toString());
                ILinkQueryParamTransfer transfor = (ILinkQueryParamTransfer) clazz.newInstance();
                qryvo = (GlQueryVO) transfor.transLinkQueryParam(params);
                params.put("pageindex", "1");
            } else {
                qryvo = getQueryVO(params);
                AccountRepUtil.checkQueryVO(qryvo);
                AccountRepUtil.checkPeriodSpan(qryvo);
                checkQryObjs(qryvo);
            }
            DetailList dataList = new DetailList();
            Integer pageindex = JsonUtils.getInteger(params.get("pageindex"));
            Integer pagedirection = JsonUtils.getInteger(params.get("pagedirection"));
            HashMap<String, Object> dataMap = dealQuery(qryvo, pageindex - 1, dataList, pagedirection);
            return getRes(dataList.getQueryVO(), dataMap);
        } catch (Exception e) {
            Logger.error(e.getMessage(), e);
            throw new BusinessException(e.getMessage(), e);
        } finally {
            if (envInit != null) {
                envInit.afterPress("", null, null);
            }
        }
    }

    /**
     * 初始化数据源环境变量（报表联查跨数据源）
     *
     * @param params
     * @throws BusinessException
     */
    public BSDataSourceControl initEnvirment(Map<String, Object> params) throws BusinessException {
        if (params.containsKey("env")) {
            try {
                String env = (String) params.get("env");
                String[] envs = env.replace("[", "").replace("]", "").replaceAll("\"", "").split(",");
                BSDataSourceControl envInit = new BSDataSourceControl();
                envInit.beforePress(null, envs, null);
                return envInit;
            } catch (Exception e) {
                Logger.error(e.getMessage());
                throw new BusinessException(e.getMessage(), e);
            }
        }
        return null;
    }

    /**
     * 根据参数获取当页数据
     *
     * @param qryvo
     * @param params
     * @param dataList
     * @return
     * @throws Exception
     */
    public HashMap<String, Object> dealQuery(GlQueryVO qryvo, int pageindex, DetailList dataList, Integer pagedirection)
            throws Exception {
        HashMap<String, Object> dataMap = new HashMap<String, Object>();
        dataList.setBillModel(new AssDetailWebModel());
        dataList.setQueryVO(qryvo);
        int totalPage = dataList.getPageNums();
        dataList.getBillModel().preFilterDataFromBalance(qryvo);
//		Integer pageindex = JsonUtils.getInteger(params.get("pageindex"));// 第几页，从1开始
        DetailBSVO[] vos = (DetailBSVO[]) dataList.goPage(pageindex);
        int pageIndexCopy = pageindex;
        while ((pagedirection == null || pagedirection == 0) && vos.length == 0 && pageindex + 1 < totalPage) {//辅助和科目放表头，点下一页前端过滤空数据改为后端过滤。把数据和页面数返回给前端
//			pageindex++; //如果没有余额totalPage为0，不会进入循环。
            pageindex = pageindex + 1;
            vos = (DetailBSVO[]) dataList.goPage(pageindex);
        }
        while ((pagedirection != null && pagedirection == 1) && vos.length == 0 && pageindex + 1 > 0) {//辅助和科目放表头，点前一页前端过滤空数据改为后端过滤。把数据和页面数返回给前端
//			pageindex++; //如果没有余额totalPage为0，不会进入循环。
            pageindex = pageindex - 1;
            vos = (DetailBSVO[]) dataList.goPage(pageindex);
        }
        if (pagedirection != null && pagedirection == 1 && (vos == null || vos.length == 0)) {//场景：点了返回第一页，第一页没数去了下一页。然后点上一页，前面页都没数所以要往后找有数的
            pageindex = pageIndexCopy;
            while (vos.length == 0 && pageindex + 1 < totalPage) {
                pageindex = pageindex + 1;
                vos = (DetailBSVO[]) dataList.goPage(pageindex);
            }
        }
        dataList.getQueryVO().setIVoucherState(totalPage);
        dataMap.put("datavos", vos);
        dataMap.put("pageindex", pageindex + 1);//比实际页面少一，这里补上
        return dataMap;
    }

    public GlQueryVO constructQueryVO(Map<String, Object> params) throws Exception {
        GlQueryVO qryvo = null;
        if (params.get("link") != null) {
            Class<?> clazz = Class.forName(params.get("class").toString());
            ILinkQueryParamTransfer transfor = (ILinkQueryParamTransfer) clazz.newInstance();
            qryvo = (GlQueryVO) transfor.transLinkQueryParam(params);
            params.put("pageindex", "1");
        } else {
            qryvo = getQueryVO(params);
            AccountRepUtil.checkQueryVO(qryvo);
            AccountRepUtil.checkPeriodSpan(qryvo);
            checkQryObjs(qryvo);
        }
        return qryvo;
    }

    /**
     * 小友机器人智能查账，补充必要参数
     *
     * @param params
     * @throws BusinessException
     */
    private void fillParamMap(Map<String, Object> params) throws BusinessException {
        // 小友参数，期间yyyyMM-yyyyMM
        String companyPK = (String) ((Map<?, ?>) params.get("companychoose")).get("pk_org");
        String accountingPeriod = JsonUtils.getStrEmpty(params.get("accountingPeriod"));
        String auxiliaryFiles = JsonUtils.getStrEmpty(params.get("auxiliaryFiles"));
        String accountSubject = JsonUtils.getStrNULL(params.get("accountSubject"));
        // 处理账簿、期间、辅助项、科目等参数
        List<String> accountingbook_pks = new ArrayList<String>();
        String pk_accountingbook = AccountRepUtil.getAccountingbookPKByOrgPK(companyPK);
        accountingbook_pks.add(pk_accountingbook);
        UFDate bizDate = new UFDate(InvocationInfoProxy.getInstance().getBizDateTime());
        AccountCalendar calendar = CalendarUtilGL.getAccountCalendarByAccountBook(pk_accountingbook);
        calendar.setDate(bizDate);
        String periodyear = calendar.getYearVO().getPeriodyear();
        if (StrTools.isEmptyStr(accountingPeriod) || accountingPeriod.length() > 40 || !accountingPeriod.matches("\\d{6}-\\d{6}[^\\s]*")) {
            throw new BusinessException(
                    "会计期间格式不正确！请按照如下示例：" + periodyear + "01" + StrTools.PERIODSPLIT + periodyear + "03");
        }
        String[] splitPeriod = accountingPeriod.split(StrTools.PERIODSPLIT);
        String year_begin = splitPeriod[0].substring(0, 4);
        String year_end = splitPeriod[1].substring(0, 4);
        String period_begin = splitPeriod[0].substring(4);
        String period_end = splitPeriod[1].substring(4);
        if (StrTools.isEmptyStr(year_begin)) {
            year_begin = periodyear;
        }
        if (StrTools.isEmptyStr(year_end)) {
            year_end = year_begin;
        }
        if (StrTools.isEmptyStr(period_begin)) {
            period_begin = calendar.getMonthVO().getAccperiodmth();
        }
        if (StrTools.isEmptyStr(period_end)) {
            period_end = period_begin;
        }
        String commaEn = ",";
        String commaCh = "，";
        String[] itemname = auxiliaryFiles.contains(commaEn) ? auxiliaryFiles.split(commaEn)
                : auxiliaryFiles.split(commaCh);
        // 设置默认参数
        params.put("pk_glorgbooks", accountingbook_pks);
        params.put("selectionState", true);
        params.put("beginyear", year_begin);
        params.put("endyear", year_end);
        params.put("beginperiod", period_begin);
        params.put("endperiod", period_end);
        params.put("begindate", year_begin + StrTools.PERIODSPLIT + period_begin + StrTools.PERIODSPLIT + "01");
        params.put("enddate", year_begin + StrTools.PERIODSPLIT + period_begin + StrTools.PERIODSPLIT + "01");
        params.put("includeUnTallyed", true);
        params.put("includeError", true);
        params.put("includeTransfer", true);
        params.put("includeReClassify", false);
        params.put("currTypeName", CurrTypeConst.QUERY_LOC_CURRTYPE());
        params.put("return_currtype", CurrTypeConst.LOC_RETURN);
        params.put("sortType", "0");
        params.put("balanceDirection", Balanorient.TWOWAY);
        params.put("pageindex", "1");
        // 查询对象：会计科目
        List<Map<String, Object>> qryObjs = new ArrayList<Map<String, Object>>();
        Map<String, Object> accountQryObj = new HashMap<String, Object>(6);
        String MultiLang_Account = NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000031");/** @res * "会计科目" */
        accountQryObj.put("name", MultiLang_Account);
        accountQryObj.put("pk_checktype", MultiLang_Account);
        if (!StrTools.isEmptyStr(accountSubject)) {
            StringBuilder pk_accasoa = new StringBuilder();
            // 1、科目范围 1001-1002
            if (accountSubject.contains(StrTools.PERIODSPLIT)) {
                String[] accountScope = accountSubject.split(StrTools.PERIODSPLIT);
                AccountGLSimpleVO[] accvos = AccountUtilGL.querySimpleAccountVOs(new String[]{pk_accountingbook},
                        accountScope[0], accountScope[1], "1", "1", true, false,
                        AccountRepUtil.getPowerCond(), bizDate.toString());
                if (accvos != null && accvos.length > 0) {
                    for (AccountGLSimpleVO accvo : accvos) {
                        pk_accasoa.append(accvo.getPk_accasoa()).append(commaEn);
                    }
                } else {
                    throw new BusinessException(
                            NCLangRes4VoTransl.getNCLangRes().getStrByID("20021101", "UPP20021101-000264")/* @res "科目编码" */
                                    + NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000230")/* @res "查询范围"*/
                                    + accountSubject
                                    + NCLangRes4VoTransl.getNCLangRes().getStrByID("20021201", "UPP20021201-000322")/*@res "没有符合条件的数据！"*/);
                }
                // 2、指定一个或多个科目编码，分隔符是中英文的逗号：1001 1001,1002,1003
            } else {
                accountSubject = accountSubject.replaceAll(" ", "");
                String[] accountCodes = accountSubject.contains(commaCh) ? accountSubject.split(commaCh)
                        : accountSubject.split(commaEn);
                Map<String, String> accountCodesMap = new Hashtable<String, String>(accountCodes.length);// 错误的科目编码
                for (String code : accountCodes) {
                    accountCodesMap.put(code, "");
                }
                AccountVO[] accvos = AccountByPkThreadCache.getInstance().getAccountVOByCodes(pk_accountingbook,
                        accountCodes, bizDate.toString());
                if (accvos != null && accvos.length > 0) {
                    for (AccountVO accvo : accvos) {
                        if (accvo != null) {
                            pk_accasoa.append(accvo.getPk_accasoa()).append(commaEn);
                            accountCodesMap.remove(accvo.getCode());
                        }
                    }
                }
                if (!accountCodesMap.isEmpty()) {
                    StringBuilder errAccCode = new StringBuilder();
                    for (String code : accountCodesMap.keySet()) {
                        errAccCode.append(code).append(commaEn);
                    }
                    errAccCode.deleteCharAt(errAccCode.length() - 1);
                    throw new BusinessException(
                            NCLangRes4VoTransl.getNCLangRes().getStrByID("20021101", "UPP20021101-000264")/* @res "科目编码" */
                                    + errAccCode.toString()
                                    + NCLangRes4VoTransl.getNCLangRes().getStrByID("20021505", "UPP20021505-000146")/* @res "不存在" */);
                }
            }
            if (pk_accasoa.length() > 0) {
                pk_accasoa.deleteCharAt(pk_accasoa.length() - 1);
            }
            accountQryObj.put("pk_checkvalue", pk_accasoa.toString());
        }
        accountQryObj.put("headEle", false);
        accountQryObj.put("accEle", false);
        accountQryObj.put("includeSub", false);
        qryObjs.add(accountQryObj);
        // 查询对象：辅助项
        if (itemname != null && itemname.length > 0) {
            IGeneralAccessor accessor = GeneralAccessorFactory.getAccessor(IBDMetaDataIDConst.ACCASSITEM);
            String groupId = InvocationInfoProxy.getInstance().getGroupId();
            StringBuilder errChecktype = new StringBuilder();// 错误的辅助项名称
            for (String checktypename : itemname) {
                checktypename = checktypename.trim();
                if (StrTools.isEmptyStr(checktypename)) {
                    continue;
                }
                IBDData bdData = accessor.getDocByNameWithMainLang(groupId, checktypename);
                if (bdData == null) {
                    errChecktype.append(checktypename).append(commaEn);
                }
                // 如果存在错误数据，最终会抛错，就不必构造对象了
                if (errChecktype.length() == 0) {
                    Map<String, Object> qryObj = new HashMap<String, Object>(6);
                    qryObj.put("name", bdData.getName().toString());
                    qryObj.put("pk_checktype", bdData.getPk());
                    qryObj.put("pk_checkvalue", "");
                    qryObj.put("headEle", false);
                    qryObj.put("accEle", false);
                    qryObj.put("includeSub", false);
                    qryObjs.add(qryObj);
                }
            }
            if (errChecktype.length() > 0) {
                errChecktype.deleteCharAt(errChecktype.length() - 1);
                throw new BusinessException(
                        NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000058")/* @res*"辅助核算"*/
                                + errChecktype.toString()
                                + NCLangRes4VoTransl.getNCLangRes().getStrByID("20021505", "UPP20021505-000146")/* @res "不存在" */);
            }
        }
        params.put("qryObjs", qryObjs);
    }

    /**
     * nc.ui.gl.assbalance.QueryDialogPanel.getqryVO()
     *
     * @param params
     * @return
     * @throws BusinessException
     */
    public GlQueryVO getQueryVO(Map<String, Object> params) throws BusinessException {
        // 小友机器人智能查账
        if (params.containsKey("companyName")) {
            fillParamMap(params);
        }
        GlQueryVO qryVO = new GlQueryVO();
        String[] pk_glorgbooks = JsonUtils.getStrArray(params.get("pk_glorgbooks"));
        if (pk_glorgbooks == null || pk_glorgbooks.length == 0) {
            throw new BusinessException(
                    NCLangRes4VoTransl.getNCLangRes().getStrByID("gl20111017public_v1_0", "02002001-0019")/* @res "请先选择核算账簿!!" */);
        }
        String pk_accountingbook = pk_glorgbooks[0];
        String newBase = BaseCorpChooser.getPk_BasCorp(pk_glorgbooks, pk_accountingbook);
        qryVO.setBaseAccountingbook(newBase);
        if (pk_glorgbooks == null || pk_glorgbooks.length == 0) {
            pk_glorgbooks = new String[]{pk_accountingbook};
        }
        qryVO.setpk_accountingbook(pk_glorgbooks);
        GlQryFormatVO qryFormatVo = qryVO.getFormatVO();

        qryVO.setQueryByPeriod(JsonUtils.getBoolean(params.get("selectionState")));
//		qryVO.setYear(JsonUtils.getStrNULL(params.get("beginyear")));
//		qryVO.setPeriod(JsonUtils.getStrNULL(params.get("beginperiod")));
//		String begindate = JsonUtils.getStrNULL(params.get("begindate"));
//		qryVO.setDate(StrTools.isEmptyStr(begindate) ? null : AccountRepUtil.getStdStartDate(begindate));
//		qryVO.setEndYear(JsonUtils.getStrNULL(params.get("endyear")));
//		qryVO.setEndPeriod(JsonUtils.getStrNULL(params.get("endperiod")));
//		String enddate = JsonUtils.getStrNULL(params.get("enddate"));
//		qryVO.setEndDate(StrTools.isEmptyStr(enddate) ? null : AccountRepUtil.getStdEndDate(enddate));
        if (qryVO.isQueryByPeriod()) {
            qryVO.setYear(JsonUtils.getStrNULL(params.get("beginyear")));
            qryVO.setPeriod(JsonUtils.getStrNULL(params.get("beginperiod")));
            qryVO.setEndYear(JsonUtils.getStrNULL(params.get("endyear")));
            qryVO.setEndPeriod(JsonUtils.getStrNULL(params.get("endperiod")));
            if (!StrTools.isEmptyStr(qryVO.getYear()) && !StrTools.isEmptyStr(qryVO.getEndYear())
                    && !StrTools.isEmptyStr(qryVO.getPeriod()) && !StrTools.isEmptyStr(qryVO.getEndPeriod())) {
                AccountCalendar calendar = CalendarUtilGL.getAccountCalendarByAccountBook(qryVO.getBaseAccountingbook());
                calendar.set(qryVO.getYear(), qryVO.getPeriod());
                qryVO.setDate(calendar.getMonthVO().getBegindate());
                calendar.set(qryVO.getEndYear(), qryVO.getEndPeriod().substring(0, 2));
                qryVO.setEndDate(calendar.getMonthVO().getEnddate().asEnd());
            }
        } else {
            String date = JsonUtils.getStrNULL(params.get("begindate"));
            qryVO.setDate(StrTools.isEmptyStr(date) ? null : AccountRepUtil.getStdStartDate(date));
            String endDate = JsonUtils.getStrNULL(params.get("enddate"));
            qryVO.setEndDate(StrTools.isEmptyStr(endDate) ? null : AccountRepUtil.getStdEndDate(endDate));
            if (qryVO.getDate() != null && qryVO.getEndDate() != null) {
                AccountCalendar calendar = CalendarUtilGL.getAccountCalendarByAccountBook(qryVO.getBaseAccountingbook());
                calendar.setDate(qryVO.getDate());
                qryVO.setYear(calendar.getYearVO().getPeriodyear());
                qryVO.setPeriod(calendar.getMonthVO().getAccperiodmth());

                calendar.setDate(qryVO.getEndDate());
                qryVO.setEndYear(calendar.getYearVO().getPeriodyear());
                qryVO.setEndPeriod(calendar.getMonthVO().getAccperiodmth());
            }
        }

        qryVO.setIncludeUnTallyed(JsonUtils.getBoolean(params.get("includeUnTallyed")));
        qryVO.setIncludeError(JsonUtils.getBoolean(params.get("includeError")));
        qryVO.setIncludeTransfer(JsonUtils.getBoolean(params.get("includeTransfer")));
        qryVO.setIncludeReClassify(JsonUtils.getBoolean(params.get("includeReClassify")));

        qryVO.setCurrTypeName(JsonUtils.getStrNULL(params.get("currTypeName")));
        qryVO.setM_Return_CurrType(JsonUtils.getInteger(params.get("return_currtype")));
        qryVO.setLocalFrac(false);
        // ----------------------------------
        if (qryVO.getCurrTypeName().equals(CurrTypeConst.AUX_CURRTYPE())
                || qryVO.getCurrTypeName().equals(CurrTypeConst.QUERY_LOC_CURRTYPE())
                || qryVO.getCurrTypeName().equals(CurrTypeConst.ALL_CURRTYPE())) {
            qryVO.setPk_currtype(null);
            if (qryVO.getCurrTypeName().equals(CurrTypeConst.AUX_CURRTYPE())) {
                qryVO.setLocalFrac(true);
            }
        } else {
            qryVO.setPk_currtype(JsonUtils.getStrNULL(params.get("pk_currtype")));
        }
        if (qryVO.getCurrTypeName().equals(CurrTypeConst.ALL_CURRTYPE())) {
            qryVO.setLocalFrac(ReportExportUtil.isLocalFrac(pk_accountingbook));
        }
        qryFormatVo.setMultiCorpCombine(false);

        qryFormatVo.setBalanceOrient(JsonUtils.getInteger(params.get("balanceDirection")));
        // 0表示显示在查询对象之后,1为前
        qryFormatVo.setCorpDispLocation(1);
        qryFormatVo.setIsSubjSelectAll(true);
        qryFormatVo.setSortType(JsonUtils.getInteger(params.get("sortType")));//排序方式。制单日期0，凭证号1
        qryFormatVo.setShowDayAcc(JsonUtils.getBoolean(params.get("addupByDay")));//是否按日合计
        qryVO.setDisLocalCurySum(JsonUtils.getBoolean(params.get("disLocalCurySum")));//显示本币合计
        qryFormatVo.setShowHasBalanceButZeroOccur(!JsonUtils.getBoolean(params.get("ckNoAccurNoDsp")));//无发生不显示
        qryFormatVo.setShowYearAcc(JsonUtils.getBoolean(params.get("dspAccumu")));//期间无发生显示累计数
        qryFormatVo.setCombineVoucher(JsonUtils.getBoolean(params.get("combineVoucher")));//合并同凭证分录

        // end v31添加
        qryVO.setFormatVO(qryFormatVo);
        // add by zhaoshya,参照得到的pk是vid,需要转换下
        Object[] pk_orgs = JsonUtils.getStrArray(params.get("pk_orgs"));
        String[] pk_units = null;
        if (pk_glorgbooks.length == 1) {
            if (pk_orgs != null && pk_orgs.length > 0) {
                pk_units = new String[pk_orgs.length];
                for (int i = 0; i < pk_orgs.length; i++) {
                    pk_units[i] = pk_orgs[i].toString();
                }
            } else {
                pk_units = AccountRepUtil.getPowerUnits(pk_glorgbooks[0]);
            }
        }

        // 处理利润中心zlp
        Object[] pk_liabilitycenteros = JsonUtils.getStrArray(params.get("pk_liabilitycenter")); //params.get("pk_liabilitycenter")==null||params.get("pk_liabilitycenter").equals("")?null:((List<String>)params.get("pk_liabilitycenter")).toArray(new String[0]);
        String[] pk_liabilitycenters = null;
        if (pk_glorgbooks.length == 1) {
            if (pk_liabilitycenteros != null && pk_liabilitycenteros.length > 0) {
                pk_liabilitycenters = new String[pk_liabilitycenteros.length];
                for (int i = 0; i < pk_liabilitycenteros.length; i++) {
                    pk_liabilitycenters[i] = pk_liabilitycenteros[i].toString();
                }
            } else {
                //查询有权限的利润中心
//				pk_liabilitycenters=AccountRepUtil.getPowerProfitCenters(new String[] {pk_accountingbook});
            }
        }
        qryVO.setPk_liabilitycenters(pk_liabilitycenters);

        qryVO.setPk_unis(pk_units);
        qryVO.setMultiBusi(JsonUtils.getBoolean(params.get("multiBusi")));
        //是否合并利润中心
        qryVO.setMultiLiabcenter(JsonUtils.getBoolean(params.get("multliabcenter")));
        UFDate busiDate = new UFDate(InvocationInfoProxy.getInstance().getBizDateTime());
        qryVO.setPk_user(InvocationInfoProxy.getInstance().getUserId());
        qryVO.setDefaultAdjust(false);
        qryVO.setUseSubjVersion(JsonUtils.getBoolean(params.get("useSubjVersion")));
        if (qryVO.isUseSubjVersion()) {
            qryVO.setSubjVersion(JsonUtils.getStrNULL(params.get("subjVersion")));
        } else {
            qryVO.setSubjVersionYear("" + busiDate.getYear());
            qryVO.setSubjVerisonPeriod(busiDate.getStrMonth());
            qryVO.setSubjVersion(busiDate.toStdString());
        }
        setQryObjs(qryVO, params.get("qryObjs"));
        qryVO.setShowBusinessDate(JsonUtils.getBoolean(params.get("showBusDate")));// 显示业务日期
        qryVO.setNeedCheckData(true);
        return qryVO;
    }

    private Map<String, Object> getRes(GlQueryVO qryvo, HashMap<String, Object> dataMap) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();

        DetailBSVO[] data = (DetailBSVO[]) dataMap.get("datavos");
        int pageindex = (int) dataMap.get("pageindex");
        result.put("column", getColumn(qryvo));
        result.put("data", getData(qryvo, data));
        result.put("totalpage", qryvo.getIVoucherState());
        result.put("pageindex", pageindex);//把当前有数据的页面返回给前端

        Map<String, String> headTitle = new HashMap<String, String>();
        headTitle.put("accbook", AccountRepUtil.getOrgNames(qryvo));/* @res "核算账簿：" */
        headTitle.put("period",
                qryvo.isQueryByPeriod() ?
                        qryvo.getYear() + StrTools.PERIODSPLIT + qryvo.getPeriod() + StrTools.PERIODSCOPESPLIT + qryvo.getEndYear() + StrTools.PERIODSPLIT + qryvo.getEndPeriod()
                        : DataFormatUtilGL.formatDate(qryvo.getDate()).getValue() + StrTools.PERIODSCOPESPLIT + DataFormatUtilGL.formatDate(qryvo.getEndDate()).getValue());/* @res "期  间：" */
        headTitle.put("currtype", qryvo.getCurrTypeName());/* @res "币  种：" */
        // 查询对象
        StringBuilder queryObjName = new StringBuilder();
        // 取出作为表头的查询对象，然后将其辅助项值做为表头
        if (qryvo.getFormatVO() != null && qryvo.getFormatVO().getQryObjs() != null && qryvo.getAssVos() != null) {
            for (GLQueryObj qryObj : qryvo.getFormatVO().getQryObjs()) {
                if (qryObj.getHeadEle()) {
                    if (qryObj.getType().equals(NCLangRes4VoTransl.getNCLangRes().getStrByID("2002gl55", "UPP2002gl55-000061")/*@res "会计科目"*/)) {
                        String subjName = ShowContentCenter.getShowAccsubj(
                                qryvo.getBaseAccountingbook(), qryvo.getPk_account() == null ? null : qryvo.getPk_account()[0], qryvo.getSubjVersion());
                        queryObjName.append(NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000135")/*@res "【科  目："*/
                                + subjName + NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000136")/*@res "】"*/);
                    } else {
                        for (AssVO assvo : qryvo.getAssVos()) {
                            if (qryObj.getType().equals(assvo.getChecktypename())) {
                                String assname = ShowContentCenter.getShowAss(qryvo.getBaseAccountingbook(), new AssVO[]{assvo});
                                queryObjName.append(assname);
                                break;
                            }
                        }
                    }
                }
            }
        }
        headTitle.put("queryobjname", queryObjName.toString());/* @res "对象" */
        headTitle.put("unit", getUnitName(qryvo));// 计量单位
        result.put("headtitle", headTitle);
        return result;
    }

    /**
     * 计量单位
     * <br>nc.ui.gl.assdetail.AssDetailUI.setTableData
     *
     * @param qryvo
     * @return
     * @throws BusinessException
     */
    private String getUnitName(GlQueryVO qryvo) throws BusinessException {
        String unit = "";
        GLQueryObj[] allQryObjs = qryvo.getFormatVO().getQryObjs();
        Vector vTempHead = new Vector();
        Vector vHeadAssLoc = new Vector();
        int adjustValue = 0;
        for (int i = 0; i < allQryObjs.length; i++) {
            if (allQryObjs[i].getType().equals(nc.vo.ml.NCLangRes4VoTransl.getNCLangRes().getStrByID("2002gl55", "UPP2002gl55-000061")/*@res "会计科目"*/)) {
                adjustValue--;
            }
            if (allQryObjs[i].getHeadEle()) {
                vTempHead.add(allQryObjs[i]);
                if (!allQryObjs[i].getType().equals(nc.vo.ml.NCLangRes4VoTransl.getNCLangRes().getStrByID("2002gl55", "UPP2002gl55-000061")/*@res "会计科目"*/)) {
                    vHeadAssLoc.add(Integer.valueOf(i + adjustValue));
                }

            }
        }
        /*
         * 添加对方科目查询对象是否是表头查询对象
         * added by Liyongru for V55 at 20080828
         */
        if (qryvo.getOppSubjQryObj() != null && qryvo.getOppSubjQryObj().getHeadEle()) {
            vTempHead.add(qryvo.getOppSubjQryObj());
        }


        //GLQueryObj[] body = (GLQueryObj[]) Convertor.convertVectorToArray(vTempBody);
        GLQueryObj[] head = (GLQueryObj[]) Convertor.convertVectorToArray(vTempHead);
        //Integer[] bodyAssLocation = (Integer[]) Convertor.convertVectorToArray(vBodyAssLoc);
        Integer[] headAssLocation = (Integer[]) Convertor.convertVectorToArray(vHeadAssLoc);
        if (qryvo.getPk_account() != null) {
            String sUnit = "";
			/*	modify by pangjsh
				只支持数量核算科目和物料放在表头进行查询时，按照物料的主计量单位显示计量单位信息
				1.如果表头有物料辅助核算，则表头按照物料的主计量单位显示计量单位信息
				2.如果表头无物料辅助核算，则表头按照数量核算科目的默认计量单位显示计量单位信息。
			*/
            String classid = IBDMetaDataIDConst.MATERIAL_V;
            AccAssItemVO[] assItems = AccAssItemCache.getAccAssItemsByClassIDs(new String[]{classid});
            AssVO headAssVO = null;
            boolean accountIsHead = false;    //科目在表头
            boolean assUnitIsExist = false;    //存在辅助核算计量单位
            /*
             *	1.数量核算科目和物料放在表头进行查询时，按照物料的主计量单位显示计量单位信息
             *	2.如果表头有物料辅助核算，则表头按照物料的主计量单位显示计量单位信息
             *	3.如果表头无物料辅助核算，则表头按照数量核算科目的默认计量单位显示计量单位信息。
             */
            if (head != null && head.length > 0) {
                int assIndex = -1;
                for (int i = 0; i < head.length; i++) {
                    if (head[i].getType().equals(nc.vo.ml.NCLangRes4VoTransl.getNCLangRes().getStrByID("2002gl55", "UPP2002gl55-000061")/*@res "会计科目"*/)) {
                        accountIsHead = true;
                    } else if (!head[i].getType().equals(nc.vo.ml.NCLangRes4VoTransl.getNCLangRes().getStrByID("20021010", "UPP20021005-000274")/*@res "对方科目"*/)) {
                        ++assIndex;
                    }
                    //辅助核算在表头
                    if (headAssLocation != null && assIndex >= 0) {
                        headAssVO = qryvo.getAssVos()[headAssLocation[assIndex].intValue()];
                        for (AccAssItemVO accAssItemVO : assItems) {
                            //物料基本信息的辅助核算类型在表头
                            if (accAssItemVO.getPk_accassitem().equals(headAssVO.getPk_Checktype())) {
                                Object[] measdoc = BDCacheQueryUtil.queryVOsByIDs(MaterialVO.class, MaterialVO.PK_MATERIAL,
                                        new String[]{headAssVO.getPk_Checkvalue()}, new String[]{MaterialVO.PK_MEASDOC});
                                //物料基本信息辅助核算的计量单位
                                if (measdoc != null && measdoc[0] != null) {
                                    sUnit = ((MaterialVO) measdoc[0]).getPk_measdoc();
                                    assUnitIsExist = true;
                                    break;
                                }
                            }
                        }
                    }
                    if (assUnitIsExist && accountIsHead) {
                        break;
                    }
                }

                if (accountIsHead) {
                    AccountVO accountVO = AccountByPkThreadCache.getInstance().getAccountVO(qryvo.getPk_account()[0], qryvo.getSubjVersion());
                    String accountUnit = accountVO == null ? null : accountVO.getUnit();
                    if (!assUnitIsExist) {
                        //物料基本信息计量单位不存在，置为科目计量单位
                        sUnit = accountUnit;
                    } else {
                        if (accountUnit == null) {
                            sUnit = accountUnit;
                        }
                    }
                    //这里处理是否有问题，老代码
//					if(sUnit==null && vos.length > 0){//针对多维分析表会计科目放表头，总计行联查明细 added by Liyongru for V55 at 20081201
//						if(vos[0].getValue(DetailBSKey.K_PK_ACCASOA) != null){
//							AccountVO acc= AccountCache.getInstance().getAccountVOByPK(qryVO.getBaseAccountingbook(),vos[0].getValue(DetailBSKey.K_PK_ACCASOA).toString());
//							sUnit=acc==null?null:acc.getUnit();
//						}
//					}
                }
                unit = sUnit == null ? "" : MeasdocUtils.getNameBypk(sUnit);
            } else {
                //无表头查询，计量单位置空
                unit = "";
            }
        }
        return unit;
    }

    private List<IColumnInfo> getColumn(GlQueryVO qryvo) {
        List<IColumnInfo> colList = new ArrayList<IColumnInfo>();
        // 跨年则显示年列
        if (qryvo.getDate().getYear() != qryvo.getEndDate().getYear()) {
            colList.add(new ColumnInfo(NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000485")/*@res "年"*/, "year", ColumnInfo.LEFT));
            colList.add(new ColumnInfo(NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000079")/*@res "月"*/, "month", ColumnInfo.LEFT));
            colList.add(new ColumnInfo(NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000087")/*@res "日"*/, "day", ColumnInfo.LEFT));
        } else {
            colList.add(AccountRepUtil.getMultHeadColum(String.valueOf(qryvo.getDate().getYear())
                    , new String[]{NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000079")/*@res "月"*/,
                            NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000087")/*@res "日"*/},
                    new String[]{"month", "day"}, new String[]{ColumnInfo.LEFT, ColumnInfo.LEFT}));
        }
        if (qryvo.isShowBusinessDate()) {
            colList.add(new ColumnInfo(NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-001008")/*@res "业务日期"*/, "businessdate", ColumnInfo.LEFT));
        }
//		if(qryvo.getpk_accountingbook().length>1&&!qryvo.isMultiCorpCombine()){
        if (qryvo.getpk_accountingbook().length > 1) {
            colList.add(new ColumnInfo(NCLangRes4VoTransl.getNCLangRes().getStrByID("gl20111017public_v1_0", "1200230400004")/*@res "核算账簿名称"*/, "bookname", ColumnInfo.LEFT));
        }
        if (AccountRepUtil.isAssdetailBuSupport(qryvo)) {
            colList.add(new ColumnInfo(NCLangRes4VoTransl.getNCLangRes().getStrByID("common", "UCMD1-000396")/*@res "业务单元"*/, "unitname", ColumnInfo.LEFT));
        }
        //利润中心
        if (AccountRepUtil.isAssliabilitycenterSupport(qryvo)) {
            colList.add(new ColumnInfo(NCLangRes4VoTransl.getNCLangRes().getStrByID("common", "UCMD1-000445")/*@res "利润中心"*/, "liabilitycentername", ColumnInfo.LEFT));
        }

        if (!GlQueryVOAssTool.isMultiPages(qryvo)) {
            GLQueryObj[] queryObjs = qryvo.getFormatVO().getQryObjs();
            for (int i = 0; i < queryObjs.length; i++) {
                GLQueryObj queryObj = queryObjs[i];
                if (queryObj.getTypeName().equals(NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000031")/* @res "会计科目" */)) {
                    colList.add(new ColumnInfo(NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000010")/*@res "科目编码"*/, "accsubjcode", ColumnInfo.LEFT));
                    colList.add(new ColumnInfo(NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000011")/*@res "科目名称"*/, "accsubjname", ColumnInfo.LEFT));
                } else {
                    AssVO[] assvos = queryObj.getValueRange();
                    if (assvos != null && assvos[0] != null) {
                        AssVO assvo = assvos[0];
                        colList.add(new ColumnInfo(assvo.getChecktypename() + NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000033")/*@res "编码"*/,
                                "checkvaluecode" + i, ColumnInfo.LEFT));
                        colList.add(new ColumnInfo(assvo.getChecktypename() + NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000034")/*@res "名称"*/,
                                "showname" + i, ColumnInfo.LEFT));
                    }
                }
            }
        } else {
            GLQueryObj[] queryObjs = qryvo.getFormatVO().getQryObjs();
            for (int i = 0; i < queryObjs.length; i++) {
                GLQueryObj queryObj = queryObjs[i];
                if (!queryObj.getHeadEle()) {
                    if (queryObj.getTypeName().equals(NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000031")/* @res "会计科目" */)) {
                        colList.add(new ColumnInfo(NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000010")/*@res "科目编码"*/, "accsubjcode", ColumnInfo.LEFT));
                        colList.add(new ColumnInfo(NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000011")/*@res "科目名称"*/, "accsubjname", ColumnInfo.LEFT));
                    } else {
                        AssVO[] assvos = queryObj.getValueRange();
                        if (assvos != null && assvos[0] != null) {
                            AssVO assvo = assvos[0];
                            colList.add(new ColumnInfo(assvo.getChecktypename() + NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000033")/*@res "编码"*/, "checkvaluecode" + i, ColumnInfo.LEFT));
                            colList.add(new ColumnInfo(assvo.getChecktypename() + NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000034")/*@res "名称"*/, "showname" + i, ColumnInfo.LEFT));
                        }
                    }
                }
            }
        }

        colList.add(new ColumnInfo(NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000008")/*@res "凭证号"*/, "voucherno", ColumnInfo.LEFT));
        colList.add(new ColumnInfo(NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000009")/*@res "摘要"*/, "explanation", ColumnInfo.LEFT));
        // 查询所有币种则显示币种列
        if (qryvo.getCurrTypeName().equals(CurrTypeConst.ALL_CURRTYPE())) {
            colList.add(new ColumnInfo(NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000012")/*@res "币种"*/, "currtypename", ColumnInfo.LEFT));
        }
        colList.add(new ColumnInfo(NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000287")/*@res "对方科目"*/, "oppsubjname", ColumnInfo.LEFT));
        colList.add(new ColumnInfo(NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000288")/*@res "单价"*/, "price", ColumnInfo.RIGTH));
        // 查询不是本币则显示折本汇率列
        if (!qryvo.getCurrTypeName().equals(CurrTypeConst.QUERY_LOC_CURRTYPE())) {
            colList.add(new ColumnInfo(NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000290")/*@res "折本汇率"*/, "ratio2", ColumnInfo.RIGTH));
        }

        String[] childStr = null;
        String[] childAlign = null;
        String[] childKey = null;
        if (qryvo.getCurrTypeName().equals(CurrTypeConst.QUERY_LOC_CURRTYPE())) {
            childStr = new String[]{
                    NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000050")/* @res "数量" */,
                    NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000053") /* @res "本币" */};
            childAlign = new String[]{ColumnInfo.RIGTH, ColumnInfo.RIGTH};
            childKey = new String[]{"debitquantity", "debitlocamount"};
        } else {
            childStr = new String[]{
                    NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000050")/* @res "数量" */,
                    NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000051")/* @res "原币" */,
                    NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000053") /* @res "本币" */};
            childAlign = new String[]{ColumnInfo.RIGTH, ColumnInfo.RIGTH, ColumnInfo.RIGTH};
            childKey = new String[]{"debitquantity", "debitamount", "debitlocamount"};
        }
        colList.add(AccountRepUtil.getMultHeadColum(NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000074")/* @res "借方" */
                , childStr, childKey, childAlign));
        if (qryvo.getCurrTypeName().equals(CurrTypeConst.QUERY_LOC_CURRTYPE())) {
            childKey = new String[]{"creditquantity", "creditlocamount"};
        } else {
            childKey = new String[]{"creditquantity", "creditamount", "creditlocamount"};
        }
        colList.add(AccountRepUtil.getMultHeadColum(NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000076")/*@res "贷方"*/
                , childStr, childKey, childAlign));
        colList.add(new ColumnInfo(NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000134")/* @res "方向" */,
                "balanceorient", ColumnInfo.CENTER));
        if (qryvo.getCurrTypeName().equals(CurrTypeConst.QUERY_LOC_CURRTYPE())) {
            childStr = new String[]{NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000050")/*@res "数量"*/
                    , NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000291")/*@res "平均单价"*/
                    , NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000053")/*@res "本币"*/};
            childAlign = new String[]{ColumnInfo.RIGTH, ColumnInfo.RIGTH, ColumnInfo.RIGTH};
            childKey = new String[]{"balancequant", "averageprice", "balancelocamount"};
        } else {
            childStr = new String[]{NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000050")/*@res "数量"*/
                    , NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000291")/*@res "平均单价"*/
                    , NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000051")/*@res "原币"*/
                    , NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000053")/*@res "本币"*/};
            childAlign = new String[]{ColumnInfo.RIGTH, ColumnInfo.RIGTH, ColumnInfo.RIGTH, ColumnInfo.RIGTH};
            childKey = new String[]{"balancequant", "averageprice", "balanceamount", "balancelocamount"};
        }
        colList.add(AccountRepUtil.getMultHeadColum(NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000077")/*@res "余额"*/
                , childStr, childKey, childAlign));
        return colList;

    }


    /**
     * 表体数据json
     *
     * @param qryvo
     * @param detailBSVOs
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> getData(GlQueryVO qryvo, DetailBSVO[] detailBSVOs) throws Exception {
        Map<String, String> assIndexMap = new HashMap<String, String>();
        GLQueryObj[] queryObjs = qryvo.getFormatVO().getQryObjs();
        for (int i = 0; i < queryObjs.length; i++) {
            GLQueryObj queryObj = queryObjs[i];
            AssVO[] assvos = queryObj.getValueRange();
            if (assvos != null && assvos.length > 0 && assvos[0] != null) {
                assIndexMap.put(assvos[0].getPk_Checktype(), i + "");
            }
        }

        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
        String pk_localcurr = AccountRepUtil.getLocalCurr(qryvo);
        String pk_org = AccountBookUtil.getPk_org(qryvo.getBaseAccountingbook());
        GLReportFormat format = new GLReportFormat(DetailBSKey.K_PK_ACCOUNTINGBOOK, DetailBSKey.K_ACCSUBJCODE, DetailBSKey.K_PK_CURRTYPE);
        boolean isExistsMaterial = isExistsMaterial(qryvo);
        Map<String, String> materialMeasdocMap = null;
        if (isExistsMaterial) {
            materialMeasdocMap = getMaterialMeasdoc(detailBSVOs);
        }
        for (DetailBSVO vo : detailBSVOs) {
            Map<String, Object> row = new HashMap<String, Object>();
            // openapi新增字段 begin
            row.put("prepareddate", vo.getValue(DetailBSKey.K_DAY));
            row.put("year", vo.getValue(DetailBSKey.K_YEAR));
            row.put("period", vo.getValue(DetailBSKey.K_MONTH));
            row.put("detailindex", vo.getValue(DetailBSKey.K_DETAILINDEX));
            row.put("explanation", vo.getValue(DetailBSKey.K_EXPLANATION));
            row.put("vouchertype", vo.getValue(DetailBSKey.K_VOUCHERTYPE));
            row.put("vouchernum", vo.getValue(DetailBSKey.K_VOUCHERNO));
            // openapi新增字段 end
            if (vo.getDaybakAsDate() != null) {
                UFDateTime date = vo.getDaybakAsDate();//去除格式化
                date = DataFormatUtilGL.getLocalDateTime(date);
                row.put("year", date.getYear());
                row.put("month", date.getStrMonth());
                row.put("day", date.getStrDay());
            }
            row.put("businessdate", DataFormatUtilGL.formatStringDateTime((String) vo.getValue(DetailBSKey.K_BUSINESSDATE)));
            row.put("bookname", vo.getValue(DetailBSKey.K_GLORGBOOKNAME));
            row.put("unitname", vo.getValue(DetailBSKey.K_PK_UNIT_V));
            row.put("liabilitycentername", vo.getValue(DetailBSKey.K_LIABILITYCENTERNAME));
            row.put("accsubjcode", vo.getValue(DetailBSKey.K_ACCSUBJCODE));
            row.put("accsubjname", vo.getValue(DetailBSKey.K_ACCSUBJNAME));
            if (vo.getValue(DetailBSKey.K_VOUCHERTYPE) != null && vo.getValue(DetailBSKey.K_VOUCHERNO) != null) {
                row.put("voucherno", vo.getValue(DetailBSKey.K_VOUCHERTYPE) + StrTools.PERIODSPLIT + vo.getValue(DetailBSKey.K_VOUCHERNO));
            }
            row.put("explanation", vo.getValue(DetailBSKey.K_EXPLANATION));
            row.put("currtypename", vo.getValue(DetailBSKey.K_CURRTYPENAME));
            row.put("oppsubjname", vo.getValue(DetailBSKey.K_OPPOSSUBJ));
            row.put("price", format.getFormatPrice(vo.getValue(DetailBSKey.K_PRICE), vo, qryvo.getSubjVersion()));
            if (!qryvo.getCurrTypeName().equals(CurrTypeConst.QUERY_LOC_CURRTYPE())
                    && !StrTools.isEmptyStr((String) vo.getValue(DetailBSKey.K_PK_VOUCHER))) {
                row.put("ratio2", format.getFormatRate(getRadio(qryvo, vo), getCurrtypePK(qryvo, vo), pk_localcurr, pk_org));
            }
            row.put("debitamount", format.getFormatAmountVlaue(vo.getValue(DetailBSKey.K_DEBITAMOUNT), vo, pk_localcurr));
            row.put("debitlocamount", format.getFormatLocalVlaue(vo.getValue(DetailBSKey.K_DEBITLOCAMOUNT), pk_localcurr));
            row.put("creditamount", format.getFormatAmountVlaue(vo.getValue(DetailBSKey.K_CREDITAMOUNT), vo, pk_localcurr));
            row.put("creditlocamount", format.getFormatLocalVlaue(vo.getValue(DetailBSKey.K_CREDITLOCAMOUNT), pk_localcurr));
            String balanceorient = "";
            // 辅助明细账多账簿查询总计行去掉方向
            if (vo.getValue(DetailBSKey.K_EXPLANATION) != null &&
                    nc.vo.ml.NCLangRes4VoTransl.getNCLangRes().getStrByID("2002033381", "UPP2002033381-000138")/*@res "总计"*/
                            .equals(vo.getValue(DetailBSKey.K_EXPLANATION).toString()) && qryvo.getpk_accountingbook().length > 1) {
                balanceorient = null;
            } else {
                balanceorient = Balanorient.getOrientStr(Integer.valueOf(vo.getValue(DetailBSKey.K_BALANCEORI).toString()));
            }
            row.put("balanceorient", balanceorient);
            row.put("averageprice", format.getFormatPrice(vo.getValue(DetailBSKey.K_AVERAGEPRICE), vo, qryvo.getSubjVersion()));
            row.put("balanceamount", format.getFormatAmountVlaue(vo.getValue(DetailBSKey.K_BALANCEAMOUNT), vo, pk_localcurr));
            row.put("balancelocamount", format.getFormatLocalVlaue(vo.getValue(DetailBSKey.K_BALANCELOCAMOUNT), pk_localcurr));
            // 数量格式化
            if (NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000000")/*@res "期初"*/.equals(vo.getValue(DetailBSKey.K_EXPLANATION))) {
                //处理辅助明细表期初数量精度
                row.put("debitquantity", format.getBeginBalanceQuan(vo.getValue(DetailBSKey.K_DEBITQUANT), qryvo.getPk_account(), qryvo.getBaseAccountingbook()));
                row.put("creditquantity", format.getBeginBalanceQuan(vo.getValue(DetailBSKey.K_CREDITQUANT), qryvo.getPk_account(), qryvo.getBaseAccountingbook()));
                row.put("balancequant", format.getBeginBalanceQuan(vo.getValue(DetailBSKey.K_BALANCEQUANT), qryvo.getPk_account(), qryvo.getBaseAccountingbook()));
            } else if (isExistsMaterial) {
                String materialPK = getMaterialPK(vo);
                String pk_measdoc = materialMeasdocMap.get(materialPK);
                row.put("debitquantity", format.getFormatQuanMaterial(vo.getValue(DetailBSKey.K_DEBITQUANT), pk_measdoc));
                row.put("creditquantity", format.getFormatQuanMaterial(vo.getValue(DetailBSKey.K_CREDITQUANT), pk_measdoc));
                row.put("balancequant", format.getFormatQuanMaterial(vo.getValue(DetailBSKey.K_BALANCEQUANT), pk_measdoc));
            } else {
                row.put("debitquantity", format.getFormatQuan(vo.getValue(DetailBSKey.K_DEBITQUANT), vo, qryvo.getSubjVersion()));
                row.put("creditquantity", format.getFormatQuan(vo.getValue(DetailBSKey.K_CREDITQUANT), vo, qryvo.getSubjVersion()));
                row.put("balancequant", format.getFormatQuan(vo.getValue(DetailBSKey.K_BALANCEQUANT), vo, qryvo.getSubjVersion()));
            }

            // 辅助项的pk、编码和名称
            Object assvosObj = vo.getValue(DetailBSKey.K_ASSVOS);
            if (row.get("mark") == null && assvosObj != null && assvosObj.getClass().isArray()) {
                AssVO[] assvos = (AssVO[]) assvosObj;
                for (int i = 0; i < assvos.length; i++) {
                    AssVO assvo = assvos[i];
                    String index = assIndexMap.get(assvo.getPk_Checktype());
                    row.put("checktypecode" + index, assvo.getChecktypecode());
                    row.put("checktypename" + index, assvo.getChecktypename());
                    row.put("checkvaluecode" + index, assvo.getCheckvaluecode());
                    row.put("checkvaluename" + index, assvo.getCheckvaluename());
                    row.put("classid" + index, assvo.getM_classid());
                    row.put("pk_checktype" + index, assvo.getPk_Checktype());
                    row.put("pk_checkvalue" + index, assvo.getPk_Checkvalue());
//                    row.put("showname" + index, ShowContentCenter.getShowAss(qryvo.getBaseAccountingbook(), new AssVO[] { assvo }));
                    //还原为源码 start
                    row.put("showname" + index, assvo.getCheckvaluename());
                    //end
                }
            }
            // 联查凭证、过滤
            if (vo.getValue(DetailBSKey.K_PK_VOUCHER) != null) {
                Map<String, Object> link = new HashMap<String, Object>();
                link.put("pk_voucher", vo.getValue(DetailBSKey.K_PK_VOUCHER));
                link.put("explanation", vo.getValue(DetailBSKey.K_EXPLANATION));
                link.put("debitlocamount", vo.getValue(DetailBSKey.K_DEBITLOCAMOUNT));
                link.put("creditlocamount", vo.getValue(DetailBSKey.K_CREDITLOCAMOUNT));
//				link.put("pk_unit",vo.getValue(DetailBSKey.K_PK_UNIT));
                AssVO[] assvos = (AssVO[]) vo.getValue(DetailBSKey.K_ASSVOS);
                if (assvos != null && assvos.length > 0) {
                    List<Map<String, String>> list = new ArrayList<Map<String, String>>(assvos.length);
                    for (AssVO assvo : assvos) {
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("pk_checktype", assvo.getPk_Checktype());
                        map.put("pk_checkvalue", assvo.getPk_Checkvalue());
                        list.add(map);
                    }
                    link.put("ass", list);
                }
                if (vo.getValue(DetailBSKey.K_ACCSUBJCODE) != null && vo.getValue(DetailBSKey.K_PK_ACCASOA) != null) {
                    link.put("accountingcode", vo.getValue(DetailBSKey.K_ACCSUBJCODE));
                }
                if (qryvo.getpk_accountingbook().length > 1) {
                    row.put("linkmsg", new String[]{
                            NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000299")/* @res "不支持多主体账簿过滤" */,
                    });
                }
                row.put("link", link);
            }
            data.add(row);
        }
        return data;
    }

    /**
     * 根据返回币种取汇率
     *
     * @param vo
     * @return
     * @throws Exception
     */
    private UFDouble getRadio(GlQueryVO qryvo, DetailBSVO vo) throws Exception {
        UFDouble radio = (UFDouble) vo.getValue(DetailBSKey.K_RATIO2);
        if (qryvo.getM_Return_CurrType() == CurrTypeConst.GROUP_RETURN) {
            radio = (UFDouble) vo.getValue(DetailBSKey.K_RATIO3);
        } else if (qryvo.getM_Return_CurrType() == CurrTypeConst.GLOBAL_RETURN) {
            radio = (UFDouble) vo.getValue(DetailBSKey.K_RATIO4);
        }
        return radio;
    }

    /**
     * 获取汇率转换的目标币种
     *
     * @param vo
     * @return
     * @throws Exception
     * @throws BusinessException
     */
    private String getCurrtypePK(GlQueryVO qryvo, DetailBSVO vo) throws Exception,
            BusinessException {
        String pk_currtype = (String) vo.getValue(DetailBSKey.K_PK_CURRTYPE);
        if (qryvo.getM_Return_CurrType() == CurrTypeConst.GROUP_RETURN
                && !Currency.isGroupRawConvertModel(InvocationInfoProxy.getInstance().getGroupId())) {
            pk_currtype = Currency.getLocalCurrPK(AccountBookUtil.getPk_org(qryvo.getBaseAccountingbook()));
        } else if (qryvo.getM_Return_CurrType() == CurrTypeConst.GLOBAL_RETURN
                && !Currency.isGlobalRawConvertModel(null)) {
            pk_currtype = Currency.getLocalCurrPK(AccountBookUtil.getPk_org(qryvo.getBaseAccountingbook()));
        }
        return pk_currtype;
    }

    /**
     * 设置GLQueryObj[]
     *
     * @param qryVO
     * @param json
     * @return
     * @throws BusinessException
     */
    @SuppressWarnings("unchecked")
    private void setQryObjs(GlQueryVO qryVO, Object json) throws BusinessException {
        if (json == null) {
            return;
        }
        Set<String> checktypeList = new HashSet<String>();
        List<GLQueryObj> glQueryObjs = new ArrayList<GLQueryObj>();
        List<Object> list = (List<Object>) json;
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> qryObjMap = (Map<String, Object>) (list.get(i));
            if (!StrTools.isEmptyStr(JsonUtils.getStrNULL(qryObjMap.get("name")))
                    && !NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000031")/** @res * "会计科目" */
                    .equals(JsonUtils.getStrNULL(qryObjMap.get("name")))) {
                checktypeList.add(JsonUtils.getStrNULL(qryObjMap.get("pk_checktype")));
            }
        }
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> qryObjMap = (Map<String, Object>) (list.get(i));
            if (StrTools.isEmptyStr(JsonUtils.getStrNULL(qryObjMap.get("name")))) {
                continue;
            }
            GLQueryObj glQueryObj = new GLQueryObj();
            glQueryObj.setAccEle(JsonUtils.getBoolean(qryObjMap.get("accEle")));
            glQueryObj.setAttrsValues(null);// 辅助属性余额表才用到
            glQueryObj.setHeadEle(JsonUtils.getBoolean(qryObjMap.get("headEle")));
            glQueryObj.setIncludeSub(JsonUtils.getBoolean(qryObjMap.get("includeSub")));
            glQueryObj.setLinkObj(null);
            glQueryObj.setDirty(false);
            glQueryObj.setType(JsonUtils.getStrNULL(qryObjMap.get("name")));
            glQueryObj.setTypeName(JsonUtils.getStrNULL(qryObjMap.get("name")));

            String pk_checkvalues = JsonUtils.getStrNULL(qryObjMap.get("pk_checkvalue"));
            if (NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000031")/** @res * "会计科目"*/
                    .equals(JsonUtils.getStrNULL(qryObjMap.get("name")))) {
                if (pk_checkvalues != null && pk_checkvalues.length() > 0) {
                    AccountVO[] accvos = AccountUtilGL.queryAccountVosByPks(pk_checkvalues.split(","), qryVO.getSubjVersion(), false);
                    if (accvos != null && accvos.length > 0) {
                        // 按code上下级排序
                        Arrays.sort(accvos, new Comparator<AccountVO>() {
                            @Override
                            public int compare(AccountVO o1, AccountVO o2) {
                                return o1.getCode().compareTo(o2.getCode());
                            }
                        });
                        AssVO[] accounts = new AssVO[accvos.length];
                        for (int j = 0; j < accvos.length; j++) {
                            accounts[j] = new AssVO();
                            accounts[j].setCheckvaluecode(accvos[j].getCode());
                            accounts[j].setCheckvaluename(accvos[j].getName());
                            accounts[j].setPk_Checkvalue(accvos[j].getPk_accasoa());
                        }
                        glQueryObj.setValueRange(accounts);
                    }
                } else {
                    AccountGLSimpleVO[] accvos = AccountUtilGL.queryAccByAss(
                            checktypeList.toArray(new String[0]),
                            qryVO.getBaseAccountingbook(),
                            qryVO.getSubjVersion());
                    if (accvos != null && accvos.length > 0) {
                        // 按code上下级排序
                        Arrays.sort(accvos, new Comparator<AccountGLSimpleVO>() {
                            @Override
                            public int compare(AccountGLSimpleVO o1, AccountGLSimpleVO o2) {
                                return o1.getCode().compareTo(o2.getCode());
                            }
                        });
                        AssVO[] accounts = new AssVO[accvos.length];
                        for (int j = 0; j < accvos.length; j++) {
                            accounts[j] = new AssVO();
                            accounts[j].setCheckvaluecode(accvos[j].getCode());
                            accounts[j].setCheckvaluename(accvos[j].getName());
                            accounts[j].setPk_Checkvalue(accvos[j].getPk_accasoa());
                        }
                        glQueryObj.setValueRange(accounts);
                    }
                }
                if (glQueryObj.getValueRange() == null) {
                    throw new BusinessException(NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000198")/*@res "没有对应的科目！"*/);
                }
            } else {
                String pk_checktype = JsonUtils.getStrNULL(qryObjMap.get("pk_checktype"));
                AccAssItemVO accassItemVO = AccAssGL.getAccAssItemVOByPk(pk_checktype);
                if (accassItemVO == null) {
                    Logger.error("assdetail: invalid pk_checktype:" + pk_checktype);
                    continue;
                }
                String checkvaluename = GLMultiLangUtil.getMultiName(accassItemVO);
                String checkvaluecode = accassItemVO.getCode();
                String classid = AccAssGL.getClassidByCheckTypePk(pk_checktype);
                if (!StrTools.isEmptyStr(pk_checkvalues)) {
                    String[] arrCheckvalues = pk_checkvalues.split(",");
                    AssVO[] assvos = new AssVO[arrCheckvalues.length];
                    for (int j = 0; j < assvos.length; j++) {
                        assvos[j] = new AssVO();
                        assvos[j].setPk_Checktype(pk_checktype);
                        assvos[j].setChecktypename(checkvaluename);
                        assvos[j].setChecktypecode(checkvaluecode);
                        assvos[j].setM_classid(classid);
                    }
                    // 自定义档案类型
                    if (FreeValueDefUtil.getInstance().isDefDoc(classid)) {
                        for (int j = 0; j < assvos.length; j++) {
                            assvos[j].setPk_Checkvalue(arrCheckvalues[j]);
                            assvos[j].setCheckvaluecode(arrCheckvalues[j]);
                            assvos[j].setCheckvaluename(arrCheckvalues[j]);
                        }
                    } else {
                        IGeneralAccessor accessor = new AssAccessorManager().getDBAccess(classid);
                        IBDData[] datas = accessor.getDocbyPks(arrCheckvalues);
                        Map<String, IBDData> map = new HashMap<String, IBDData>();
                        for (IBDData data : datas) {
                            map.put(data.getPk(), data);
                        }
                        for (int j = 0; j < assvos.length; j++) {
                            assvos[j].setPk_Checkvalue(arrCheckvalues[j]);
                            if (map.get(arrCheckvalues[j]) instanceof BankaccsubBDDataVO) {
                                assvos[j].setCheckvaluecode(((BankaccsubBDDataVO) map.get(arrCheckvalues[j])).getSubcode());
                                assvos[j].setCheckvaluename(((BankaccsubBDDataVO) map.get(arrCheckvalues[j])).getSubname().toString());
                            } else {
                                assvos[j].setCheckvaluecode(map.get(arrCheckvalues[j]).getCode());
                                assvos[j].setCheckvaluename(map.get(arrCheckvalues[j]).getName().getText());
                            }
                        }
                    }
                    glQueryObj.setValueRange(assvos);
                } else {
                    AssVO[] assvos = new AssVO[1];
                    assvos[0] = new AssVO();
                    assvos[0].setPk_Checktype(JsonUtils.getStrNULL(qryObjMap.get("pk_checktype")));
                    assvos[0].setCheckvaluename("ALL");
                    assvos[0].setChecktypename(GLMultiLangUtil.getMultiName(AccAssGL.getAccAssItemVOByPk(assvos[0].getPk_Checktype())));
                    assvos[0].setChecktypecode(AccAssGL.getAccAssItemVOByPk(assvos[0].getPk_Checktype()).getCode());
                    assvos[0].setM_classid(classid);
                    glQueryObj.setValueRange(assvos);
                }
            }
            glQueryObjs.add(glQueryObj);
        }
        qryVO.getFormatVO().setQryObjs(glQueryObjs.toArray(new GLQueryObj[glQueryObjs.size()]));
    }

    /**
     * 校验查询条件
     * <br>nc.ui.gl.assbalance.QueryDialogPanel.checkQryObjs(GlQryFormatVO qryFormatVo)
     *
     * @param qryVO
     * @throws BusinessException
     */
    public void checkQryObjs(GlQueryVO qryVO) throws BusinessException {
        if (qryVO.getDate() == null) {
            throw new BusinessException(NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000185")/*@res "请重新输入起始日期！"*/);
        }
        GlQryFormatVO qryFormatVo = qryVO.getFormatVO();
        int iKmAmount = 0;
        for (GLQueryObj qryObj : qryFormatVo.getQryObjs()) {
            if (!StrTools.isEmptyStr(qryObj.getType())) {
                if (qryObj.getType().equals(NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000031")/*@res "会计科目"*/)) {
                    iKmAmount++;
                } else if (qryObj.getValueRange()[0] != null && qryObj.getValueRange()[0].getCheckvaluename() != null //项目辅助项可能有名称为空的情况
                        && qryObj.getValueRange()[0].getCheckvaluename().equals("ALL")
                        && qryObj.getIncludeSub()) {
                    throw new BusinessException(
                            NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000187")/*@res "辅助项选空，不支持同时包含下级！"*/);
                }
            }
        }
        if (iKmAmount == 0) {
            throw new BusinessException(
                    NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000188")/*@res "没有选择设定会计科目查询对象信息！"*/);
        } else if (iKmAmount > 1) {
            throw new BusinessException(
                    NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000189")/*@res "会计科目查询对象信息不唯一！"*/);
        }

        GLQueryObj[] aQryObjs = qryFormatVo.getQryObjs();

        boolean blnIsChild = false;
        boolean blnAssIsChild = false;
        String sCorpTmp = AccountBookUtil.getPk_orgByAccountBookPk(qryVO.getBaseAccountingbook());
        boolean blnSubjAccIsInBody = false;
        boolean blnAssIsInBody = false;
        int iBodyItemCount = 0;
        for (int i = 0; i < aQryObjs.length; i++) {
            if (!blnIsChild || !blnAssIsChild) {
                if (!aQryObjs[i].getHeadEle()) {
                    if (aQryObjs[i].getType().equals(NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000031")/*@res "会计科目"*/)) {
                        if (!aQryObjs[i].getHeadEle()) {
                            blnSubjAccIsInBody = true;
                            iBodyItemCount++;
                        }
                        //如果是，隔开的科目
                        if (aQryObjs[i].getValueRange() != null && aQryObjs[i].getValueRange()[0].getCheckvaluecode().contains(",")) {
                            String[] acccode = aQryObjs[i].getValueRange()[0].getCheckvaluecode().split(",");
                            for (int j = 0; j < acccode.length; j++) {
                                for (int k = 0; k < acccode.length; k++) {
                                    if (j != k && acccode[j].startsWith(acccode[k])) {
                                        blnIsChild = true;
                                        break;
                                    }
                                }
                            }
                        } else {
                            for (int j = 0; j < aQryObjs[i].getValueRange().length; j++) {
                                for (int k = 0; k < aQryObjs[i].getValueRange().length; k++) {
                                    if (j != k
                                            && aQryObjs[i].getValueRange()[j]
                                            .getCheckvaluecode()
                                            .startsWith(aQryObjs[i].getValueRange()[k].getCheckvaluecode())) {
                                        blnIsChild = true;
                                        break;
                                    }
                                }
                            }
                        }
                    } else {
                        if (!aQryObjs[i].getHeadEle()) {
                            iBodyItemCount++;
                            blnAssIsInBody = true;
                        }
                        for (int j = 0; aQryObjs[i].getValueRange() != null
                                && j < aQryObjs[i].getValueRange().length; j++) {
                            if (aQryObjs[i].getIncludeSub()) {
                                try {
                                    AssVO[] assVos = CBalanceAssTool
                                            .getSubDocsTackle(
                                                    aQryObjs[i]
                                                            .getValueRange()[j],
                                                    sCorpTmp);
                                    for (int f = 0; f < assVos.length; f++) {
                                        for (int k = 0; k < aQryObjs[i]
                                                .getValueRange().length; k++) {
                                            if (assVos[f]
                                                    .getPk_Checkvalue()
                                                    .equals(
                                                            aQryObjs[i]
                                                                    .getValueRange()[k]
                                                                    .getPk_Checkvalue())) {
                                                blnAssIsChild = true;
                                                break;
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    throw new BusinessException(e.getMessage(), e);
                                }
                            }
                        }
                    }
                }
            }
        }

        //同一页显示可以显示上下级。
        if (blnIsChild && !(blnSubjAccIsInBody && iBodyItemCount == 1)) {
            qryFormatVo.setAssBalIncludeChildSubj(true);
            blnIsChild = false;
        }
        if (blnIsChild) {
            throw new BusinessException(
                    NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000190")/*@res "查询条件出现以下情况时，不支持科目之间有上下级关系：1、辅助明细帐查询；2、表体查询中有辅助核算； 3、选择多个单位，且“多单位排序方式”为“查询对象＋单位”；4、辅助余额表跨年。 请检查是否出现上述情况，修改查询条件后再试。"*/);
        } else {
            qryFormatVo.setIsSubjAccIncldFatherSon(false);
        }
        if (blnAssIsChild) {
            if (!(blnAssIsInBody && iBodyItemCount == 1)
                    || (qryFormatVo.getCorpDispLocation() == 0 && qryVO.getpk_accountingbook().length > 1)
            ) {
                throw new BusinessException(
                        NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000191")/*@res "查询条件出现以下情况时，不支持辅助核算之间有上下级关系：1、辅助明细帐查询；2、表体查询中大于一个查询对象； 3、选择多个单位，且“多单位排序方式”为“查询对象＋单位”；4、辅助余额表跨年。 请检查是否出现上述情况，修改查询条件后再试。"*/);
            } else {
                qryFormatVo.setIsAssIncldFatherSon(true);
            }
        }

        if (aQryObjs.length < 2) {
            throw new BusinessException(
                    NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000194")/*@res "没有选辅助核算类型，请重新选择！"*/);
            //MessageDialog.showErrorDlg(this, "错误",
            // "没有选具体科目,或者所选科目没有相同的辅助核算类型，请重新选定科目！");
        }
        UFDouble from = qryVO.getFormatVO().getBalanceRangeFrom();
        UFDouble to = qryVO.getFormatVO().getBalanceRangeTo();
        if (from == null) {
            from = UFDouble.ZERO_DBL;
        }
        if (to == null) {
            to = UFDouble.ZERO_DBL;
        }
        if (from.compareTo(to) > 0) {
            throw new BusinessException(
                    NCLangRes4VoTransl.getNCLangRes().getStrByID("20023030", "UPP20023030-000195")/*@res "余额范围查询条件信息输入有误(起始值大于终止值)！"*/);
        }
    }

    /**
     * 判断查询对象里是否有物料
     *
     * @param qryVO
     * @return
     */
    private boolean isExistsMaterial(GlQueryVO qryVO) {
        for (GLQueryObj qryObj : qryVO.getFormatVO().getQryObjs()) {
            if (qryObj.getValueRange() != null
                    && qryObj.getValueRange().length > 0
                    && IBDMetaDataIDConst.MATERIAL_V.equals(qryObj.getValueRange()[0].getM_classid())) {
//					&& qryObj.getValueRange()[0].getCheckvaluecode()!=null) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取Map<物料pk，计量单位pk>
     *
     * @param detailBSVOs
     * @return
     * @throws Exception
     */
    private Map<String, String> getMaterialMeasdoc(DetailBSVO[] detailBSVOs) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        // 取出辅助中的pk_material
        Set<String> pk_material = new HashSet<String>();
        for (DetailBSVO vo : detailBSVOs) {
            String materialPK = getMaterialPK(vo);
            if (!StrTools.isEmptyStr(materialPK)) {
                pk_material.add(materialPK);
            }
        }
        // 查询物料计量单位，组成Map<物料pk，计量单位pk>
        if (pk_material.size() > 0) {
            MaterialVO[] materialVOs = (MaterialVO[]) BDCacheQueryUtil.queryVOsByIDs(
                    MaterialVO.class,
                    MaterialVO.PK_MATERIAL,
                    pk_material.toArray(new String[pk_material.size()]),
                    new String[]{MaterialVO.PK_MEASDOC});
            if (materialVOs != null && materialVOs.length > 0) {
                for (MaterialVO materialVO : materialVOs) {
                    if (materialVO != null) {
                        map.put(materialVO.getPk_material(), materialVO.getPk_measdoc());
                    }
                }
            }
        }
        return map;
    }


    /**
     * 取出辅助中的pk_material
     *
     * @param vo
     * @return
     * @throws Exception
     */
    private String getMaterialPK(DetailBSVO vo) throws Exception {
        AssVO[] assvos = (AssVO[]) vo.getValue(DetailBSKey.K_ASSVOS);
        if (assvos != null) {
            for (AssVO assvo : assvos) {
                if (IBDMetaDataIDConst.MATERIAL_V.equals(assvo.getM_classid())) {
                    return assvo.getPk_Checkvalue();
                }
            }
        }
        return null;
    }

}
