package nc.util.hbbb.input.hbreportdraft;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import nc.bs.framework.common.NCLocator;
import nc.itf.bd.cust.baseinfo.ICustSupQueryService;
import nc.itf.hbbb.hbrepstru.HBRepStruUtil;
import nc.pub.iufo.basedoc.IDName;
import nc.pub.iufo.cache.IUFOCacheManager;
import nc.pub.iufo.cache.MeasureCache;
import nc.pub.iufo.cache.UFOCacheManager;
import nc.pub.iufo.exception.UFOSrvException;
import nc.util.bd.intdata.MultiLangTextUtil;
import nc.util.hbbb.HBKeyGroupUtil;
import nc.util.hbbb.MeasureDataProxy;
import nc.util.hbbb.MeasurePubDataUtil;
import nc.util.hbbb.hbscheme.HBSchemeSrvUtils;
import nc.util.hbbb.measure.MeasureUtil;
import nc.util.hbbb.pub.HBPubItfService;
import nc.util.hbbb.pub.util.StrTools;
import nc.util.hbbb.service.HBBaseDocItfService;
import nc.util.hbbb.workdraft.head.IProjectCellHead;
import nc.util.hbbb.workdraft.head.ProjectCellHeadFactory;
import nc.util.hbbb.workdraft.head.ProjectHead;
import nc.util.hbbb.workdraft.pub.IWorkDraft;
import nc.vo.bd.cust.CustSupplierVO;
import nc.vo.corg.ReportCombineStruMemberWithCodeNameVO;
import nc.vo.iufo.data.MeasureDataVO;
import nc.vo.iufo.data.MeasurePubDataVO;
import nc.vo.iufo.data.RepDataVO;
import nc.vo.iufo.keydef.KeyGroupVO;
import nc.vo.iufo.keydef.KeyVO;
import nc.vo.iufo.measure.MeasureVO;
import nc.vo.iufo.storecell.IStoreCell;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDouble;
import nc.vo.ufoc.workdrafttemp.MeasureInfoVO;
import nc.vo.ufoc.workdrafttemp.WorkDraftTempVO;

import com.ufida.iufo.pub.tools.AppDebug;
import com.ufsoft.iuforeport.tableinput.applet.IRepDataParam;
import com.ufsoft.table.AreaPosition;
import com.ufsoft.table.Cell;
import com.ufsoft.table.CellPosition;
import com.ufsoft.table.CellsModel;

/**
 * 动态区工作底稿明细
 * 
 * @author jiaah
 * 
 */
public class HBBBDynDraftTableHandler extends HBBBDraftTableInputActionHandler {

	@Override
	public CellsModel loadDraftCellsModel(String strRepPK, IRepDataParam param,
			IWorkDraft workdraft) throws Exception {
		return doDynRepDraft(strRepPK, param, workdraft);// 内部交易采集表底稿展现

	}

	protected ProjectHead getDynProject() {
		return ProjectHead.DYNUNIONREPORT;
	}

	/**
	 * 动态表底稿展现
	 * 
	 * @param strRepPK
	 * @param param
	 * @param workdraft
	 * @return
	 * @throws UFOSrvException
	 * @throws BusinessException
	 * @throws Exception
	 */
	protected CellsModel doDynRepDraft(String strRepPK, IRepDataParam param,
			IWorkDraft workdraft) throws UFOSrvException, BusinessException,
			Exception {

		lstAll = new ArrayList<Cell[]>();

		// 返回合并范围的组织
		String pk_unionorg = param.getPubData().getKeywordByPK(KeyVO.CORP_PK);
		setSchemevo(HBSchemeSrvUtils.getHBSchemeByHBSchemeId(param.getTaskPK()));
		String hbRepStruVersionPK = getHBRepStruPK(param.getPubData(), schemevo);
		String innercode = HBPubItfService.getRemoteUnionReport().getInnerCode(
				hbRepStruVersionPK, pk_unionorg);
		if (null == innercode || innercode.trim().length() == 0) {
			throw new BusinessException(nc.vo.ml.NCLangRes4VoTransl
					.getNCLangRes().getStrByID("pub_0", "01830001-0502"));// "当前合并公司没有找到inner code"
		}
		// X轴需要显示的公司的数量及pk组合
		String[] corps = getShowOrgs(hbRepStruVersionPK, innercode);

		setParamPubData(param.getPubData());
		// 返回keymap
		KeyVO[] keys = param.getPubData().getKeyGroup().getKeys();
		String[] keywords = param.getPubData().getKeywords();
		Map<String, String> keyMap = new HashMap<String, String>();
		for (int i = 0; i < keys.length; i++) {
			keyMap.put(keys[i].getPk_keyword(), keywords[i]);
		}
		keyMap.put(KeyVO.CORP_PK, pk_unionorg);

		// 合并pubdataVO
		MeasurePubDataVO unionPubDataVO = MeasurePubDataUtil.getMeasurePubdata(
				schemevo.getVersion(), true, pk_unionorg,
				schemevo.getPk_keygroup(), keyMap,
				schemevo.getPk_accperiodscheme());
		// 底稿的标题cell
		IProjectCellHead createProduct = ProjectCellHeadFactory.getInstance()
				.CreateProduct(getDynProject(), corps, workdraft, null, true);

		// 1.1 添加表头名称-合并利润表工作底稿
		Cell[] titlecells = createProduct.getTitleCells(param.getReportPK(),
				workdraft);
		lstAll.add(titlecells);
		lstAll.add(new Cell[] { null });
		lstAll.add(new Cell[] { null });

		// 1.2 添加关键字信息
		// 标题所占行数
		int iTitleRow = 3;
		// 获取底稿关键字信息
		Cell[] keywordCell = getKeywordCell(iTitleRow, param);
		lstAll.add(keywordCell);
		// 准备要显示的指标
		MeasureCache measureCache = UFOCacheManager.getSingleton()
				.getMeasureCache();
		if (workdraft.getMesurevos() != null) {
			loadMeasureByReportPK = workdraft.getMesurevos();
		} else {
			loadMeasureByReportPK = measureCache.loadMeasureByReportPK(param
					.getReportPK());
		}

		// 1.3 添加列头名称显示
		Cell[] headCells = createProduct.getProjectHeadCells();
		lstAll.add(headCells);

		// 1.4 添加第二层列头名称<原表、抵销、净表> 最后一列的净表变成合并
		Cell[] cell2Title = getCell2Title(corps);
		lstAll.add(cell2Title);

		// 1.5 准备合并子公司原动态表数据
		//xiangymf  专向用加的方法  ncm 
		setSrcDynReportVOS(workdraft,corps, param.getRepOrgPK(), param.getReportPK(),
				hbRepStruVersionPK);
		// 数据加载从第5行开始
		int row = 5;
		loadMeasureByReportPK = MeasureUtil.getSortByPositionMeasureVOs(
				loadMeasureByReportPK, strRepPK);
		List<MeasureVO> dynMeasures = new ArrayList<MeasureVO>();
		for (MeasureVO vo : loadMeasureByReportPK) {
			String mainKeyGroup = unionPubDataVO.getKType();
			if (!vo.getKeyCombPK().equals(mainKeyGroup)) {
				dynMeasures.add(vo);
			}
		}
		// 1.6 提取动态区指标：数据按行加载
		loadMeasureByReportPK = dynMeasures.toArray(new MeasureVO[dynMeasures
				.size()]);
		if (loadMeasureByReportPK != null && loadMeasureByReportPK.length > 0) {
			String pk_wordraft = workdraft.getPk_workdrafttemp();
			WorkDraftTempVO draftvo = workdraft.getWorkDraftTempVO();
			if (pk_wordraft != null && draftvo != null
					&& draftvo.getPk_report().equals(workdraft.getPk_report())) {
				MeasureInfoVO[] measinfovos = workdraft.getMeasinfovos();// 底稿上设置的指标
				ConcurrentHashMap<String, MeasureVO> measmap = new ConcurrentHashMap<String, MeasureVO>();// 当前报表上所有的指标
				for (MeasureVO vo : loadMeasureByReportPK) {
					measmap.put(vo.getCode(), vo);
				}
				// 只是按照单位按列展示：逐行加载底稿数据
				if (measinfovos == null)
					throw new Exception(nc.vo.ml.NCLangRes4VoTransl
							.getNCLangRes()
							.getStrByID("pub_0", "01830005-0309")/*
																 * @res
																 * "工作底稿未设置显示指标"
																 */);
				Set<MeasureVO> drafMeasures = new HashSet<MeasureVO>();
				for (int j = 0; j < measinfovos.length; j++) {
					MeasureVO vo = measmap.get(measinfovos[j].getPk_measure());
					if (vo != null)
						drafMeasures.add(vo);
				}
				// 工作底稿需要显示的指标
				loadMeasureByReportPK = drafMeasures
						.toArray(new MeasureVO[drafMeasures.size()]);
			}

			// 判断动态区关键字是否是对方单位编码
			KeyGroupVO subKeyGroup = IUFOCacheManager.getSingleton()
					.getKeyGroupCache()
					.getByPK(loadMeasureByReportPK[0].getKeyCombPK());
			String pk_dynValues = HBKeyGroupUtil.getPk_dynKeyValue(subKeyGroup,
					schemevo.getPk_keygroup());
			boolean bDicCorp = true;
			// 动态区底稿关键字显示 edit by dongjch 2015-06-09
			if (!pk_dynValues.equals(KeyVO.DIC_CORP_PK)) {
				bDicCorp = false;
				KeyVO keyvo = subKeyGroup.getKeyByKeyPk(pk_dynValues);
				headCells[0].setValue(keyvo.getChangeName());
			} else {
				headCells[0]
						.setValue((nc.vo.ml.NCLangRes4VoTransl.getNCLangRes()
								.getStrByID("pub_0", "01830003-0069")/*
																	 * @res
																	 * "对方单位"
																	 */));
			}
			// 准备每一类单元格的数据：如公司原表、抵销、净表、合计、小计等数据
			HBBBDynDraftSrcData srcDataObj = new HBBBDynDraftSrcData(strRepPK,
					schemevo, unionPubDataVO, srcDynRepMap, getNotLeafOrgs(
							hbRepStruVersionPK, innercode), getShowOrgs(
							hbRepStruVersionPK, innercode),
					loadMeasureByReportPK, bDicCorp);

			// 1.7 数据按行加载,从第5行开始加载，按行按单元格加载
			loadDataFromRow5(workdraft, corps, row, srcDataObj, bDicCorp);
			// 1.8 处理工作底稿的显示，合并各个多层表头的单元格
			CellsModel result = processUnionCell(param, corps, titlecells,
					headCells, srcDataObj);
			return result;
		}
		return null;
	}

	/**
	 * 对方单位是客商的时候，加载客商名称
	 * 
	 * @param oppOrgPks
	 * @return
	 */
	protected Map<String, String> getCustNameMap(String[] oppOrgPks) {
		Map<String, String> custNameMap = new HashMap<String, String>();
		try {
			ICustSupQueryService custQry = NCLocator.getInstance().lookup(
					ICustSupQueryService.class);
			CustSupplierVO[] custs = custQry.queryCustSupVO(oppOrgPks);
			if (custs != null && custs.length > 0) {
				for (CustSupplierVO vo : custs) {
					custNameMap.put(vo.getPk_cust_sup(),
							MultiLangTextUtil.getCurLangText(vo));
				}
			}
		} catch (BusinessException e) {
			AppDebug.debug(e.getMessage());
		}
		return custNameMap;
	}

	/**
	 * 逐个单元格加载指定数据
	 * 
	 * @param workdraft
	 * @param corps
	 * @param row
	 * @param srcDataObj
	 */
	protected void loadDataFromRow5(IWorkDraft workdraft, String[] corps,
			int row, HBBBDynDraftSrcData srcDataObj, boolean bDicCorp) {

		// TODO:最好是不是按照组织编码排序呢？
		String[] oppOrgPks = srcDataObj.getColumnOrgs();
		// 查出所有客商
		Map<String, String> custNameMap = new HashMap<String, String>();
		if (oppOrgPks != null && oppOrgPks.length > 0) {
			if (!bDicCorp) {
				custNameMap = getCustNameMap(oppOrgPks);
			}
			// 根据每个对方组织加载该行数据
			// 组织编码、指标、单位1原表、单位1抵销、单位1净表、单位2原表、单位2抵销、单位2净表、合计原表、合计抵销、合计合并。
			// +1 是最后一行是合计
			for (int j = 0; j < oppOrgPks.length + 1; j++) {
				String pk_opporg = null;
				if (j != oppOrgPks.length) {
					pk_opporg = oppOrgPks[j];
				}
				int col = 0;
				// 1、动态区关键字列0
				Cell[] cells = null;
				if (j != oppOrgPks.length) {
					if (bDicCorp)
						cells = new Cell[] { IProjectCellHead.getDynNameCellBy(
								row, col, pk_opporg) };
					else
						cells = new Cell[] { IProjectCellHead
								.getDynNameCellByCust(row, col,
										custNameMap.get(pk_opporg), pk_opporg) };// 客商名称
				} else {// 最后一组合计单元格生成
					Cell proejctCell = IProjectCellHead.getHeadCellBy(row, col,
							nc.vo.ml.NCLangRes4VoTransl.getNCLangRes()
									.getStrByID("pub_0", "01830008-0152"));// "合计"
					cells = new Cell[] { proejctCell };
				}
				col++;

				for (int i = 0; i < loadMeasureByReportPK.length; i++) {
					Cell[] cellRow = cells;
					// 2、指标名称列1
					Cell meacells = IProjectCellHead.getValueCellBy(row, col,
							loadMeasureByReportPK[i]);
					// Cell meacells = IProjectCellHead.getHeadCellBy(row, col,
					// loadMeasureByReportPK[i].getName());
					cellRow = StrTools.add(cellRow, meacells);
					col++;

					HashSet<String> hashset = new HashSet<String>();
					if (workdraft.getShoworgs() != null) {
						hashset.addAll(Arrays.asList(workdraft.getShoworgs()));
					} else {
						for (int n = 0; n < corps.length; n++) {
							hashset.add(corps[n].substring(0, 20));
						}
					}

					// 3、每个单位对应的原表、抵销、净额列
					if (j != oppOrgPks.length) {
						for (int m = 0; m < corps.length; m++) {
							String pk_org = corps[m].substring(0, 20);
							String key = pk_org + pk_opporg;
							if (hashset.contains(pk_org)) {
								cellRow = StrTools.add(cellRow,
										IProjectCellHead.getDynDataCellByType(
												row, col,
												loadMeasureByReportPK[i],
												srcDynRepMap.get(key), 0));// 0表示原表
								col++;
								cellRow = StrTools.add(cellRow,
										IProjectCellHead.getDynDataCellByType(
												row, col,
												loadMeasureByReportPK[i],
												srcDataObj.getDynDXRepMap()
														.get(key), 1));// 1表示抵销
								col++;
								// 净表列
								cellRow = StrTools.add(cellRow,
										IProjectCellHead.getDynDataCellBy(row,
												col, loadMeasureByReportPK[i],
												srcDataObj.getDynCleanRepMap()
														.get(key)));
								col++;

							}
						}
						// 合计列
						cellRow = StrTools.add(cellRow, IProjectCellHead
								.getDynDataCellBy(
										row,
										col,
										loadMeasureByReportPK[i],
										srcDataObj.getDyntotalSepMap().get(
												pk_opporg)));
						col++;
						// 抵销列
						cellRow = StrTools.add(cellRow, IProjectCellHead
								.getDynDataCellBy(
										row,
										col,
										loadMeasureByReportPK[i],
										srcDataObj.getDyntotalDXMap().get(
												pk_opporg)));
						col++;
						// 合并列
						Cell dataCellBy = IProjectCellHead.getDynDataCellBy(
								row, col, loadMeasureByReportPK[i], srcDataObj
										.getDyntotalUnionMap().get(pk_opporg));
						cellRow = StrTools.add(cellRow, dataCellBy);
					} else { // 4、合计行数据
						for (int m = 0; m < corps.length; m++) {
							String pk_org = corps[m].substring(0, 20);
							if (hashset.contains(pk_org)) {
								cellRow = StrTools
										.add(cellRow,
												IProjectCellHead
														.getDynDataCellBy(
																row,
																col,
																loadMeasureByReportPK[i],
																srcDataObj
																		.getDynSumByColumnSepMap()
																		.get(pk_org)));
								col++;
								cellRow = StrTools
										.add(cellRow,
												IProjectCellHead
														.getDynDataCellBy(
																row,
																col,
																loadMeasureByReportPK[i],
																srcDataObj
																		.getDynSumByColumnContrastMap()
																		.get(pk_org)));
								col++;
								// 净表数据
								cellRow = StrTools
										.add(cellRow,
												IProjectCellHead
														.getDynDataCellBy(
																row,
																col,
																loadMeasureByReportPK[i],
																srcDataObj
																		.getDynSumByColumnCleanMap()
																		.get(pk_org)));
								col++;
							}
						}
						// 合计数
						cellRow = StrTools
								.add(cellRow,
										IProjectCellHead
												.getDynDataCellBy(
														row,
														col,
														loadMeasureByReportPK[i],
														srcDataObj
																.getDynSumByColumnSepMap()
																.get(HBBBDynDraftSrcData.TOTALCOLUMNORG)));
						col++;
						// 抵销数
						cellRow = StrTools
								.add(cellRow,
										IProjectCellHead
												.getDynDataCellBy(
														row,
														col,
														loadMeasureByReportPK[i],
														srcDataObj
																.getDynSumByColumnContrastMap()
																.get(HBBBDynDraftSrcData.TOTALCOLUMNORG)));
						col++;
						// 合并数
						Cell dataCellBy = IProjectCellHead.getDynDataCellBy(
								row,
								col,
								loadMeasureByReportPK[i],
								srcDataObj.getDynSumByColumnCleanMap().get(
										HBBBDynDraftSrcData.TOTALCOLUMNORG));
						cellRow = StrTools.add(cellRow, dataCellBy);
					}
					lstAll.add(cellRow);
					row++;
				}

				// 5、小计行数据
				if (j != oppOrgPks.length) {
					Cell[] cellRow = cells;
					Cell meacells = IProjectCellHead.getHeadCellBy(row, col,
							nc.vo.ml.NCLangRes4VoTransl.getNCLangRes()
									.getStrByID("pub_0", "01830001-0332"));// "小计"
					cellRow = StrTools.add(cellRow, meacells);
					col++;

					for (int m = 0; m < corps.length; m++) {
						String key = corps[m].substring(0, 20) + pk_opporg;
						cellRow = StrTools.add(cellRow, IProjectCellHead
								.getDynSumDataCellBy(row, col, srcDataObj
										.getDynSumByOrgSepRepMap().get(key)));
						col++;
						cellRow = StrTools.add(cellRow, IProjectCellHead
								.getDynSumDataCellBy(row, col, srcDataObj
										.getDynSumByOrgContrastRepMap()
										.get(key)));
						col++;
						cellRow = StrTools.add(cellRow, IProjectCellHead
								.getDynSumDataCellBy(row, col, srcDataObj
										.getDynSumByOrgCleanRepMap().get(key)));
						col++;
					}
					String key = HBBBDynDraftSrcData.TOTALCOLUMNORG + pk_opporg;
					// 合计数
					cellRow = StrTools.add(cellRow, IProjectCellHead
							.getDynSumDataCellBy(row, col, srcDataObj
									.getDynSumByOrgSepRepMap().get(key)));
					col++;
					// 抵销数
					cellRow = StrTools.add(cellRow, IProjectCellHead
							.getDynSumDataCellBy(row, col, srcDataObj
									.getDynSumByOrgContrastRepMap().get(key)));
					col++;
					// 合并数
					Cell dataCellBy = IProjectCellHead.getDynSumDataCellBy(row,
							col, srcDataObj.getDynSumByOrgCleanRepMap()
									.get(key));
					cellRow = StrTools.add(cellRow, dataCellBy);
					lstAll.add(cellRow);
				}
				row++;
			}
		}
	}

	/**
	 * 返回动态表的第二层表头：原表抵销净表等
	 * 
	 * @param corps
	 * @return
	 */
	protected Cell[] getCell2Title(String[] corps) {
		int width = 1 + 1 + (corps.length + 1) * 3;
		Cell[] cell2Title = new Cell[width];
		for (int i = width - (corps.length + 1) * 3; i < width; i++) {
			cell2Title[i] = null;
			if (i >= width - (corps.length + 1) * 3) {
				cell2Title[i] = IProjectCellHead.getHeadCellBy(
						5,
						i,
						nc.vo.ml.NCLangRes4VoTransl.getNCLangRes().getStrByID(
								"pub_0", "01830008-0150"));// "原表"
				i = i + 1;
				cell2Title[i] = IProjectCellHead.getHeadCellBy(
						5,
						i,
						nc.vo.ml.NCLangRes4VoTransl.getNCLangRes().getStrByID(
								"pub_0", "01830008-0151"));// "抵销"
				i = i + 1;
				if (i == width - 1)
					cell2Title[i] = IProjectCellHead.getHeadCellBy(5, i,
							nc.vo.ml.NCLangRes4VoTransl.getNCLangRes()
									.getStrByID("pub_0", "01830001-0276"));// "合并"
				else
					cell2Title[i] = IProjectCellHead.getHeadCellBy(5, i,
							nc.vo.ml.NCLangRes4VoTransl.getNCLangRes()
									.getStrByID("pub_0", "01830008-0146"));// "净表"
			}
		}
		return cell2Title;
	}

	/**
	 * 处理工作底稿的显示问题 如表头和列的单元格合并，公司的 原表、抵销、净额的合并
	 * 
	 * @param param
	 * @param corps
	 * @param titlecells
	 * @param headCells
	 * @return
	 * @throws BusinessException
	 */
	protected CellsModel processUnionCell(IRepDataParam param, String[] corps,
			Cell[] titlecells, Cell[] headCells, HBBBDynDraftSrcData srcDataObj)
			throws BusinessException {
		CellsModel result = CellsModel.getInstance(
				lstAll.toArray(new Object[0][0]), true);
		CellPosition start = CellPosition.getInstance(1, 0);

		// 合计所有列数-原表、抵销、净表
		int trow = (corps.length + 1) * 3 + 2;

		AreaPosition area = AreaPosition.getInstance(1, 0, trow, 0);
		result.getCombinedAreaModel().combineCell(area);
		Cell head = null;
		for (Cell cvo : titlecells) {
			if (null != cvo) {
				head = cvo;
				break;
			}
		}

		Cell headCell = null;
		for (Cell cvo : headCells) {
			if (null != cvo) {
				headCell = cvo;
				break;
			}
		}

		// 表头行合并：动态区底稿的公司表头合并抵销节点
		for (int i = 0; i < 2; i++) {
			AreaPosition areax = AreaPosition.getInstance(4, i, 1, 2);
			result.getCombinedAreaModel().combineCell(areax);
		}

		for (int j = trow - (corps.length + 1) * 3; j < trow - 1; j = j + 3) {
			AreaPosition areax = AreaPosition.getInstance(4, j, 3, 1);
			result.getCombinedAreaModel().combineCell(areax);

			CellPosition w = CellPosition.getInstance(4, j);
			Cell cell = result.getCell(w);
			cell.setFormat(headCell.getFormat());
			String title = cell.getValue().toString();
			cell.setValue(title.substring(0, title.length() - 2));
		}

		// 列合并：第一列相同公司的区域合并
		String[] oppOrgPks = srcDataObj.getColumnOrgs();
		if (oppOrgPks != null) {
			for (int j = 0; j < oppOrgPks.length + 1; j++) {
				if (j == oppOrgPks.length) {
					AreaPosition areax = AreaPosition.getInstance(6
							+ (loadMeasureByReportPK.length + 1) * j, 0, 1,
							loadMeasureByReportPK.length);// +
															// loadMeasureByReportPK.length*j
					result.getCombinedAreaModel().combineCell(areax);
				} else {
					AreaPosition areax = AreaPosition.getInstance(6
							+ (loadMeasureByReportPK.length + 1) * j, 0, 1,
							loadMeasureByReportPK.length + 1);// +
																// loadMeasureByReportPK.length*j
					result.getCombinedAreaModel().combineCell(areax);
				}

				CellPosition w = CellPosition.getInstance(6
						+ (loadMeasureByReportPK.length + 1) * j, 0);// +
																		// loadMeasureByReportPK.length*j
																		// + 1
				Cell cell = result.getCell(w);
				cell.setFormat(headCell.getFormat());
				cell.setValue(cell.getValue().toString());
			}
		}

		// 将关键字的第二个后面的两个单元格合并
		int j = 1;
		for (int i = 1; i < getKeyword(param.getPubData()).length; i++) {
			AreaPosition keyarea = AreaPosition.getInstance(3, j, 2, 1);
			result.getCombinedAreaModel().combineCell(keyarea);
			j = j + 2;
		}

		// 动态设置列的长度尺寸
		int rowNum = result.getRowNum();
		int maxLenth = 0;
		AreaPosition area2 = AreaPosition.getInstance(1, 0, 1, rowNum);
		Cell[][] cells = result.getCells(area2);
		for (int i = 0; i < cells.length; i++) {
			Cell[] cells2 = cells[i];
			if (cells2[0] != null) {
				Object value = cells2[0].getValue();
				if (value != null && value instanceof String) {
					String projectname = (String) value;
					int length = projectname.length();
					if (length > maxLenth)
						maxLenth = length;
				} else if (value != null && value instanceof MeasureVO) {
					String projectname = ((MeasureVO) value).toString();
					int length = projectname.length();
					if (length > maxLenth)
						maxLenth = length;
				}
			}
		}
		UFDouble div = new UFDouble(maxLenth + 3).div(new UFDouble(10));
		UFDouble multiply = div.multiply(new UFDouble(100));
		result.getColumnHeaderModel().setSize(0, multiply.intValue());
		result.getCell(start).setFormat(head.getFormat());
		result.getCell(start).setValue(head.getValue());
		result.setDirty(false);

		// 设置指标名称列的长度
		maxLenth = 0;
		area2 = AreaPosition.getInstance(1, 1, 1, rowNum);
		cells = result.getCells(area2);
		for (int i = 0; i < cells.length; i++) {
			Cell[] cells2 = cells[i];
			if (cells2[0] != null) {
				Object value = cells2[0].getValue();
				if (value != null && value instanceof String) {
					String projectname = (String) value;
					int length = projectname.length();
					if (length > maxLenth)
						maxLenth = length;
				} else if (value != null && value instanceof MeasureVO) {
					String projectname = ((MeasureVO) value).toString();
					int length = projectname.length();
					if (length > maxLenth)
						maxLenth = length;
				}
			}
		}
		div = new UFDouble(maxLenth + 6).div(new UFDouble(10));
		multiply = div.multiply(new UFDouble(100));
		result.getColumnHeaderModel().setSize(1, multiply.intValue());
		result.getCell(start).setFormat(head.getFormat());
		result.getCell(start).setValue(head.getValue());
		result.setDirty(false);

		return result;
	}

	/**
	 * 设置动态表的每个组织对的数据
	 * 
	 * @param corps
	 * @param unionorg
	 * @param pk_report
	 * @param Pk_hbrepstru
	 * @throws BusinessException
	 */
	//xiangymf  专向用加的方法  ncm
	@Override
	protected void setSrcDynReportVOS(String[] corps, String unionorg,
			String pk_report, String Pk_hbrepstru) throws BusinessException {
		setSrcDynReportVOS(null, corps, unionorg, pk_report, Pk_hbrepstru);
	}

	/**
	 * 设置动态表的每个组织对的数据
	 * 
	 * @param corps
	 * @param unionorg
	 * @param pk_report
	 * @param Pk_hbrepstru
	 * @throws BusinessException
	 */
	//xiangymf  专向用加的方法  ncm
	@Override
	protected void setSrcDynReportVOS(IWorkDraft workdraft, String[] corps,
			String unionorg, String pk_report, String Pk_hbrepstru)
			throws BusinessException {
		// 得到虚实对应关系
		String[] orgs = new String[corps.length];
		for (int i = 0; i < corps.length; i++) {
			orgs[i] = corps[i].substring(0, 20);
		}
		Map<String, UFBoolean> entityorg = HBRepStruUtil.getBooleanEntityOrgs(
				orgs, Pk_hbrepstru);
		MeasureVO meass = null;
		// 如此多的校验就是为了 专项用 ,其余逻辑走else ;;; start xiangymf
		if (workdraft != null && workdraft.getCells() != null
				&& workdraft.getCells()[0][0].getValue() instanceof IDName
				&& workdraft.getMesurevos() != null
				&& workdraft.getMesurevos().length == 1) {
			meass = workdraft.getMesurevos()[0];
			KeyGroupVO keygroupVo = UFOCacheManager.getSingleton()
					.getKeyGroupCache().getByPK(meass.getKeyCombPK());
			Cell[][] cellss = workdraft.getCells();
			// 获取对方单位pk;
			IDName iDName = (IDName) cellss[0][0].getValue();
			String pk = iDName.getPk();
			for (String pk_org : corps) {
				try {
					pk_org = pk_org.substring(0, 20);
					boolean isXuUnit = entityorg.get(pk_org) == null ? false
							: entityorg.get(pk_org).booleanValue();

					MeasurePubDataVO pubdata = new MeasurePubDataVO();
					pubdata.setKType(meass.getKeyCombPK());
					pubdata.setAccSchemePK(getHbschemevo()
							.getPk_accperiodscheme());
					// KeyGroupVO keygroupVo1 =
					// UFOCacheManager.getSingleton().getKeyGroupCache().getByPK(meass.getKeyCombPK());
					pubdata.setKeyGroup(keygroupVo);
					pubdata.setKeywordByPK(KeyVO.CORP_PK, pk_org);
					pubdata.setKeywordByPK(KeyVO.DIC_CORP_PK, pk);
					// pubdata = MeasurePubDataUtil.getMeasurePubData(pubdata,
					// getParamPubData(), new String[] { KeyVO.CORP_PK });

					RepDataVO[] vos = null;
					pubdata = getMeasureData(pubdata, pk_org, true, pk_report);
					MeasureDataVO[] datas = MeasureDataProxy.getRepData(
							new String[] { pubdata.getAloneID() },
							new MeasureVO[] { meass });
					if (null != datas && datas.length > 0) {

						Map<String, UFDouble> map = new HashMap<String, UFDouble>();
						boolean isAllZero = true;

						for (MeasureDataVO datavo : datas) {
							if (datavo.getMeasureVO().getType() == IStoreCell.TYPE_NUMBER
									|| datavo.getMeasureVO().getType() == IStoreCell.TYPE_BIGDECIMAL) {
								UFDouble value = new UFDouble(
										datavo.getDataValue());
								if (!value.equals(UFDouble.ZERO_DBL)
										&& isAllZero) {
									isAllZero = false;
								}
								map.put(datavo.getCode(), value);
							} else
								map.put(datavo.getCode(), UFDouble.ZERO_DBL);
							// xiangymf 将查询指标为0的数据全部过滤掉

						}

						KeyGroupVO subKeyGroup = IUFOCacheManager
								.getSingleton()
								.getKeyGroupCache()
								.getByPK(datas[0].getMeasureVO().getKeyCombPK());
						String pk_dynValues = HBKeyGroupUtil.getPk_dynKeyValue(
								subKeyGroup, schemevo.getPk_keygroup());

						// 对方单位编码关键字，不通用
						// JIAAH 虚单位，个别报表数据设置为null
						if (isXuUnit) {
							srcDynRepMap
									.put(pk_org
											+ pubdata
													.getKeywordByPK(pk_dynValues),
											new HashMap<String, UFDouble>());
						} else
							srcDynRepMap
									.put(pubdata.getKeywordByPK(KeyVO.CORP_PK)
											+ pubdata
													.getKeywordByPK(pk_dynValues),
											map);
					} else {

					}

				} catch (Exception e) {
					throw new BusinessException(e.getMessage());
				}
			}
			// 如此多的校验就是为了 专项用 其余逻辑走else ;;; start xiangymf
		} else {
			for (String pk_org : corps) {
				try {
					pk_org = pk_org.substring(0, 20);
					boolean isXuUnit = entityorg.get(pk_org) == null ? false
							: entityorg.get(pk_org).booleanValue();

					RepDataVO[] vos = null;
					MeasurePubDataVO pubdata = null;
					pubdata = getMeasureData(pk_org, true, pk_report);
					vos = HBPubItfService.getRemoteRepDataQry().loadRepData(
							pk_report, pk_org, pubdata, Pk_hbrepstru);
					MeasurePubDataVO[] allPubDataVos = vos[0].getPubDatas();
					Set<MeasurePubDataVO> dynPubDataVos = new HashSet<MeasurePubDataVO>();
					for (MeasurePubDataVO vo : allPubDataVos) {
						if (!vo.getKType().equals(pubdata.getKType())) {
							dynPubDataVos.add(vo);

						}
					}

					for (MeasurePubDataVO vo : dynPubDataVos) {
						MeasureDataVO[] datas = vos[0].getMeasureDatas(vo);
						if (null != datas && datas.length > 0) {
							Map<String, UFDouble> map = new HashMap<String, UFDouble>();
							for (MeasureDataVO datavo : datas) {
								if (datavo.getMeasureVO().getType() == IStoreCell.TYPE_NUMBER
										|| datavo.getMeasureVO().getType() == IStoreCell.TYPE_BIGDECIMAL)
									map.put(datavo.getCode(), new UFDouble(
											datavo.getDataValue()));
								else
									map.put(datavo.getCode(), UFDouble.ZERO_DBL);
							}

							KeyGroupVO subKeyGroup = IUFOCacheManager
									.getSingleton()
									.getKeyGroupCache()
									.getByPK(
											datas[0].getMeasureVO()
													.getKeyCombPK());
							String pk_dynValues = HBKeyGroupUtil
									.getPk_dynKeyValue(subKeyGroup,
											schemevo.getPk_keygroup());

							// 对方单位编码关键字，不通用
							// JIAAH 虚单位，个别报表数据设置为null
							if (isXuUnit) {
								srcDynRepMap
										.put(pk_org
												+ vo.getKeywordByPK(pk_dynValues),
												new HashMap<String, UFDouble>());
							} else
								srcDynRepMap
										.put(vo.getKeywordByPK(KeyVO.CORP_PK)
												+ vo.getKeywordByPK(pk_dynValues),
												map);
						}
					}
				} catch (UFOSrvException e) {
					nc.bs.logging.Logger.error(e.getMessage(), e);
					throw new BusinessException(e.getMessage());
				} catch (Exception e) {
					throw new BusinessException(e.getMessage());
				}
			}
		}
	}

	/**
	 * 返回参与当前合并组织的所有下级组织，作为x轴显示的所有的组织
	 * 
	 * @param hbRepStruVersionPK
	 * @param innercode
	 * @return
	 */
	protected String[] getShowOrgs(String hbRepStruVersionPK, String innercode) {
		String[] corps = new String[0];
		try {
			ReportCombineStruMemberWithCodeNameVO[] vers = HBBaseDocItfService
					.getRemoteHBRepStru()
					.queryReportCombineStruMemberWithCodeByInnercode(
							hbRepStruVersionPK, innercode);
			List<String> lst = new ArrayList<String>();
			if (vers != null) {
				for (ReportCombineStruMemberWithCodeNameVO vo : vers) {
					lst.add(vo.getPk_org() + vo.getInnercode());
				}
			}
			corps = lst.toArray(new String[lst.size()]);// 得到参与当前合并组织的所有下级组织
		} catch (BusinessException e) {
			AppDebug.debug(e.getMessage());
		}
		return corps;
	}

	/**
	 * 返回参与当前合并组织的所有非末级组织，作为抵销数据查询的时候的待查组织
	 * 
	 * @param hbRepStruVersionPK
	 * @param innercode
	 * @return
	 */
	protected String[] getNotLeafOrgs(String hbRepStruVersionPK,
			String innercode) {
		String[] corps = new String[0];
		try {
			String[] orgs = getShowOrgs(hbRepStruVersionPK, innercode);
			String[] orgNotLeaf = new String[orgs.length];
			for (int i = 0; i < orgs.length; i++) {
				orgNotLeaf[i] = orgs[i].substring(0, 20);
			}
			Map<String, UFBoolean> map = HBBaseDocItfService
					.getRemoteHBRepStru().isLeafMembers(orgNotLeaf,
							hbRepStruVersionPK);
			List<String> lst = new ArrayList<String>();
			if (map != null) {
				for (Map.Entry<String, UFBoolean> enter : map.entrySet()) {
					if (!enter.getValue().booleanValue())
						lst.add(enter.getKey());
				}
			}
			corps = lst.toArray(new String[lst.size()]);// 当前合并组织的所有非末级组织
		} catch (BusinessException e) {
			AppDebug.debug(e.getMessage());
		}
		return corps;
	}
}
