package cn.myapps.runtime.report.service;

import cn.myapps.common.auth.IUser;
import cn.myapps.common.ModelSuffix;
import cn.myapps.common.CommonDAO;
import cn.myapps.common.dao.report.FileSystemReportDAO;
import cn.myapps.common.data.ParamsTable;
import cn.myapps.common.exception.CommonException;
import cn.myapps.common.model.datasource.DataSource;
import cn.myapps.common.model.report.QueryColumnInfo;
import cn.myapps.common.model.report.Report;
import cn.myapps.common.model.view.AbstractView;
import cn.myapps.common.model.view.Column;
import cn.myapps.common.util.StringUtil;
import cn.myapps.designtime.common.service.DesignTimeServiceManager;
import cn.myapps.designtime.datasource.service.DataSourceDesignTimeService;
import cn.myapps.designtime.form.service.FormDesignTimeService;
import cn.myapps.designtime.view.service.ViewDesignTimeService;
import cn.myapps.runtime.common.service.AbstractRunTimeProcessBean;
import cn.myapps.runtime.common.service.RunTimeServiceManager;
import cn.myapps.runtime.dynaform.PermissionType;
import cn.myapps.runtime.dynaform.document.ejb.Document;
import cn.myapps.runtime.dynaform.document.ejb.DocumentProcess;
import cn.myapps.runtime.dynaform.document.ejb.Item;
import cn.myapps.runtime.dynaform.form.ejb.*;
import cn.myapps.runtime.macro.runner.IRunner;
import cn.myapps.runtime.macro.runner.JavaScriptFactory;
import cn.myapps.report.engine.ReportEngine;
import cn.myapps.runtime.report.model.DRDataSource;
import cn.myapps.common.util.cache.MemoryCacheUtil;
import net.sf.json.JSONObject;
import net.sf.dynamicreports.report.builder.column.ColumnBuilder;
import net.sf.dynamicreports.report.builder.datatype.DataTypes;
import net.sf.dynamicreports.report.definition.datatype.DRIDataType;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static net.sf.dynamicreports.report.builder.DynamicReports.col;

/**
 * @author Happy
 *
 */
@Service
public class ReportServiceImpl extends AbstractRunTimeProcessBean<Report> implements
		ReportService {
	private static final long serialVersionUID = 712365638612148766L;

	@Autowired
	private RuntimeOpenQueryService runtimeOpenQueryService;

	private DataSourceDesignTimeService dataSourceService;

	public ReportServiceImpl() {
		try {
			this.dataSourceService = DesignTimeServiceManager.dataSourceDesignTimeService();

		} catch (Exception e ) {
			e.printStackTrace();
		}
	}

	private String getQueryString(String js, AbstractView view, ParamsTable params, IUser user) throws Exception {

		StringBuffer label = new StringBuffer();
		label.append("VIEW(").append(view.getId())
				.append(")." + view.getName()).append(".FilterScript");
		IRunner runner = JavaScriptFactory.getInstance(user.getSessionid(),
				view.getApplicationid());
		runner.initBSFManager(null, params, user,
				new ArrayList<ValidateMessage>());
		Object result = runner.run(view, label.toString(), js);
		if (result != null && result instanceof String) {
			return (String) result;
		}
		return null;
	}

	@Override
	protected CommonDAO<Report> getDao() {
		return new FileSystemReportDAO(Report.class);
	}

	@Override
	public String getPathSuffix() {
		return ModelSuffix.REPORT_PATH_SUFFIX;
	}

	@Override
	public String getFileSuffix() {
		return ModelSuffix.REPORT_FILE_SUFFIX;
	}

	/**
	 * 根据脚本调用IRunner产生查询sql
	 * @param params
	 * @param user
	 * @param sDoc
	 * @param sqlParamList
	 * @param report
	 * @return
	 * @throws Exception
	 */
	public String getQueryString(ParamsTable params, IUser user, Document sDoc, List<Object> sqlParamList,
								 Report report) throws Exception {
		String sql = "";
		StringBuffer label = new StringBuffer();
		label.append("VIEW(").append(report.getId()).append(")." + report.getName()).append(".SqlFilterScript");

		IRunner runner = JavaScriptFactory.getInstance(user.getSessionid(), report.getApplicationid());
		runner.initBSFManager(sDoc, params, user, new ArrayList<ValidateMessage>());
		//执行前清除JavaScript缓存
		JavaScriptFactory.clear();
		Object object = runner.run(report, label.toString(), report.getDataSourceSqlScript());
		if (object != null && object instanceof String) {
			sql = (String) object;
		} else if (object != null && object instanceof Map) {
			Map<String, Object> sqlMap = (HashMap) object;
			sql = (String) sqlMap.get("sql");
			if (sqlMap.get("sqlParamList") instanceof List) {
				sqlParamList.addAll((List) sqlMap.get("sqlParamList"));
			}
		}
		return sql;
	}

	@Override
	public String generateDynamicReportByViewDataSource(Report report, Collection<Document> data,ParamsTable params,IUser user) throws Exception {
		Report viewDataSourceReport = getViewDataSourceReport(report,data,params,user);
		ReportEngine engine = ReportEngine.getInstance();
		String path = engine.exportHtml(viewDataSourceReport, params, user);
		return path;
	}

	public String generateExcelByViewDataSource(Report report, Collection<Document> data,ParamsTable params,IUser user) throws Exception {
		Report viewDataSourceReport = getViewDataSourceReport(report,data,params,user);
		ReportEngine engine = ReportEngine.getInstance();
		String path = engine.exportExcel(viewDataSourceReport, params, user);
		return path;
	}

	public String generatePdfByViewDataSource(Report report, Collection<Document> data,ParamsTable params,IUser user) throws Exception {
		Report viewDataSourceReport = getViewDataSourceReport(report,data,params,user);
		ReportEngine engine = ReportEngine.getInstance();
		String path = engine.exportPdf(viewDataSourceReport, params, user);
		return path;
	}

	public String generateExcelByProcedure(Report report, IUser user, ParamsTable params) throws Exception {
		ReportEngine engine = ReportEngine.getInstance();
		// 创建DynamicReport数据源和列信息
		String applicationId = report.getApplicationid();
		String procedureScript = report.getProcedureScript();
		String dataSourceName = report.getDataSourceName();
		// 获取数据源
		DataSource dataSource = dataSourceService.getDataSourceByName(dataSourceName, applicationId );

		// 创建search document
		Document searchDocument = null;
		String searchFormId = report.getDataSourceSearchForm();
		if (!StringUtils.isBlank(searchFormId)) {
			FormDesignTimeService fs = DesignTimeServiceManager.formDesignTimeService();
			Form searchForm = fs.doView(searchFormId);
			searchDocument = searchForm.createDocument(params, user); // getSearchDocument(view);
		}
		// 脚本加上查询表单通过IRUNNER执行后得出最终的结果
		IRunner runner = JavaScriptFactory.getInstance(user.getSessionid(), applicationId);
		runner.initBSFManager(searchDocument, params, user, new ArrayList<ValidateMessage>());
		//执行前清除JavaScript缓存
		JavaScriptFactory.clear();
		//执行iscript脚本
		Object object = runner.run(report, "Report[" + report.getName() + "]-" + report.getId(), procedureScript);
		if(object instanceof  String){
			procedureScript = (String)object;
		}
		runtimeOpenQueryService.generateDynamicReportDataSourceByProcedure(report, procedureScript, dataSource.getDriverClass(), dataSource.getUrl(), dataSource.getUsername(), dataSource.getPassword());

		String path = engine.exportExcel(report, params, user);
		return path;
	}

	//获取自定义数据源的列信息
	@Override
	public List<QueryColumnInfo> getCustomColumnsInfos(String customDataIscript, Report report, ParamsTable params, IUser user, String applicationId) throws Exception {

		if (report == null ) {
			report = new Report();
			report.setId("TEMP_REPORT_ID");
			report.setName("TEMP_REPORT_NAME");
			report.setApplicationid(applicationId);
		}
		IRunner runner = JavaScriptFactory.getInstance(user.getSessionid(), report.getApplicationid());
		runner.initBSFManager(null, params, user, new ArrayList<ValidateMessage>());
		//执行前清除JavaScript缓存
		JavaScriptFactory.clear();
		Object object = runner.run(report,"Report[" + report.getName() + "]-" + report.getId(), customDataIscript);
		List<QueryColumnInfo> columnInfos = new ArrayList<>();
		if (object instanceof DRDataSource) {
			DRDataSource drDataSource = (DRDataSource)object;
			//获取数据源中的列名和列类型
			List<Map<String, Object>> values = drDataSource.getValues();
			for(Map m : values ){

				for(Object key: m.keySet()){
					QueryColumnInfo columnInfo = new QueryColumnInfo();
					//列名
					String columnName = (String)key;
					//列类型
					String className = m.get(key).getClass().getName();
					columnInfo.setColumnClassName(className);
					columnInfo.setColumnTypeName(className);
					columnInfo.setColumnLabel(columnName);
					columnInfo.setColumnName(columnName);
					//插入到列信息中
					columnInfos.add(columnInfo);
				}
				break;
			}
		} else {
			throw new Exception("Report[" + report.getName() + "]脚本运算结果不合法，请返回DRDataSource类型！");
		}
		return columnInfos;
	}

	@Override
	public String generateDynamicReportByCustomDataSource(Report report, ParamsTable params, IUser user) throws Exception {
		ReportEngine engine = ReportEngine.getInstance();
		String customScript = report.getDataSourceCustomScript();
		IRunner runner = JavaScriptFactory.getInstance(user.getSessionid(), report.getApplicationid());
		runner.initBSFManager(null, params, user, new ArrayList<ValidateMessage>());
		//执行前清除JavaScript缓存
		JavaScriptFactory.clear();
		//执行iscript脚本
		Object object = runner.run( report,"Report[" + report.getName() + "]-" + report.getId(), customScript);
		//判断脚本返回的类型是否正确
		if (object instanceof DRDataSource) {
			DRDataSource drDataSource = (DRDataSource)object;
			//创建一个数据源并塞入数据
			DRDataSource dataSource = new DRDataSource(drDataSource.getColumns());
			List<Map<String, Object>> values = drDataSource.getValues();
			//从自定义数据中拿出数据塞入数据源
			for(Map value : values){
				dataSource.add(value.values().toArray());
			}
			report.setDrDataSource(dataSource);

			List<QueryColumnInfo> columnInfos = getCustomColumnsInfos(customScript,report,params,user,report.getApplicationid());
			// 创建列信息
			if (columnInfos.size() > 0 ) {
				List<ColumnBuilder> colms = new ArrayList<>();
				Iterator<QueryColumnInfo> iter = columnInfos.iterator();
				while (iter.hasNext()) {
					QueryColumnInfo queryColumnInfo = iter.next();
					String columnClassName = queryColumnInfo.getColumnClassName();

					colms.add(col.column(queryColumnInfo.getColumnLabel(), queryColumnInfo.getColumnName(), (DRIDataType) DataTypes.detectType(columnClassName)));    //colms.add(col.column("Item", "item", (DRIDataType)DataTypes.detectType("java.lang.String")));//type.stringType()));
				}
				report.setReportColumnInfos(colms);

			} else {
				report.setReportColumnInfos(null);
			}

		} else {
			throw new Exception("Report[" + report.getName() + "]脚本运算结果不合法，请返回DRDataSource类型！");
		}
		String path = engine.exportHtml(report, params, user);
		return path;
	}

	@Override
	public String generateDynamicReportByFormDataSource(Report report, ParamsTable params, IUser user, String docid) throws Exception {
		Report formDataSourceReport =getFormData(report,params,user,docid);
		ReportEngine engine = ReportEngine.getInstance();
		String path = engine.exportHtml(formDataSourceReport, params, user);
		return path;
	}

	@Override
	public String generatePdfByFormDataSource(Report report, ParamsTable params, IUser user, String docid) throws Exception {
		Report formDataSourceReport =getFormData(report,params,user,docid);
		ReportEngine engine = ReportEngine.getInstance();
		String path = engine.exportPdf(formDataSourceReport, params, user);
		return path;
	}

	public Report getFormData(Report report,ParamsTable params,IUser user,String docid) throws Exception{
		FormDesignTimeService formService = DesignTimeServiceManager.formDesignTimeService();
		Form form = formService.doView(report.getFormId());
		DocumentProcess dProcess = RunTimeServiceManager.documentProcess(
				report.getApplicationid());
		Document doc = (Document) dProcess.doView(docid);
		if (doc == null) {
			//表示为新建
			doc = (Document) MemoryCacheUtil.getFromPrivateSpace(docid, user);
		} else {
			doc.setSubDocuments(doc.getChilds());
			doc = form.recalculateDocument(doc, params, user);
		}
		if (doc == null) {
			doc = new Document();
		}
		IRunner runner = JavaScriptFactory.getInstance(user.getSessionid(), form.getApplicationid());
		//获取表单字段
		Collection<FormField> fields = form.getFields();
		List<String> nameList = new LinkedList<>();
		//数据集
		List<String> data = new LinkedList<>();
		for(FormField formField: fields){
			//判断类型是否选项卡
			if(formField instanceof TabField){
				Collection<Tab> tabs = ((TabField) formField).getTabs();
				if(tabs !=null && tabs.size()>0){
					for(Tab tab : tabs){
						Form tabForm = formService.doView(tab.getFormId());
						//获取表单字段
						tabForm.inited();
						Collection<FormField> tabFields = tabForm.getFields();
						for(FormField field : tabFields){
							nameList.add(field.getName());
							data.add(field.getText(doc,runner,user));
						}
					}

				}

			}else{
				nameList.add(formField.getName());
				data.add(formField.getText(doc,runner,user));
			}
		}
		//创建数据源
		DRDataSource drDataSource = new DRDataSource(nameList.toArray(new String[fields.size()]));
		drDataSource.add(data.toArray());

		report.setDrDataSource(drDataSource);

		List<QueryColumnInfo> columnInfos = this.getFormColumnsInfos(report.getFormId());
		// 创建列信息
		if (columnInfos.size() > 0 ) {
			List<ColumnBuilder> colms = new ArrayList<>();
			Iterator<QueryColumnInfo> iter = columnInfos.iterator();
			while (iter.hasNext()) {
				QueryColumnInfo queryColumnInfo = iter.next();
				String columnClassName = queryColumnInfo.getColumnClassName();

				colms.add(col.column(queryColumnInfo.getColumnLabel(), queryColumnInfo.getColumnName(), (DRIDataType) DataTypes.detectType(columnClassName)));    //colms.add(col.column("Item", "item", (DRIDataType)DataTypes.detectType("java.lang.String")));//type.stringType()));
			}
			report.setReportColumnInfos(colms);

		} else {
			report.setReportColumnInfos(null);
		}
		return report;
	}

	//获取视图数据源的列信息
	@Override
	public List<QueryColumnInfo> getViewColumnsInfos(String viewId) throws Exception{
		ViewDesignTimeService vProcess = DesignTimeServiceManager.viewDesignTimeService();
		AbstractView view = vProcess.doView(viewId);
		List<QueryColumnInfo> columnInfos = new ArrayList<>();
		//获取视图中的所有列
		List<Column> columns = view.getColumns();
		for(Column column : columns){
			//只取字段类型的列
			if(!column.getType().equals(Column.COLUMN_TYPE_FIELD)){
				continue;
			}
			QueryColumnInfo columnInfo = new QueryColumnInfo();
			//字段类型
			if(column.getType().equals("COLUMN_TYPE_FIELD")){
				columnInfo.setColumnName(column.getFormField().getName());
				columnInfo.setColumnLabel(column.getFormField().getName());
				columnInfo.setColumnTypeName(column.getFormField().getFieldtype());
			}else{
				columnInfo.setColumnName(column.getName());
				columnInfo.setColumnLabel(column.getName());
				columnInfo.setColumnTypeName("COLUMN_TYPE_SCRIPT");
			}
			//获取列的类型
			System.out.println(columnInfo.getColumnTypeName());

//			if(column.getFormField().getFieldtype().equals("VALUE_TYPE_DATE")){
//				columnInfo.setColumnClassName("java.util.String");
//			}
//			else
//			if(column.getFormField().getFieldtype().equals("VALUE_TYPE_NUMBER")){
//				columnInfo.setColumnClassName("java.lang.Double");
//			}else {
//                columnInfo.setColumnClassName("java.lang.String");
//            }
			//视图获取的数据皆为String类型
			columnInfo.setColumnClassName("java.lang.String");
			columnInfos.add(columnInfo);

		}
		return columnInfos;
	}

	/**
	 * 获取查询结果列信息
	 * @author laiq
	 * @param sql
	 * @param dataSourceName
	 * @param applicationId
	 * @param user
	 * @param report
	 * @param params
	 * @return
	 * @throws CommonException
	 */
	public List<QueryColumnInfo> getQueryColumnInfos(String sql, String dataSourceName, String applicationId, IUser user, Report report, ParamsTable params ) throws Exception {
		List<QueryColumnInfo> resultQueryColumnInfos = null;

		// 获取数据源
		DataSource dataSource = dataSourceService.getDataSourceByName(dataSourceName, applicationId );
		if (dataSource == null ) {
			CommonException irptException = new CommonException();
			StringBuffer exceptionMsgSB = new StringBuffer();
			exceptionMsgSB.append("获取数据源为空!");
			irptException.setExceptionMsg(exceptionMsgSB.toString());
			throw irptException;
		}

		System.out.println("dataSourceFileName:" + dataSource.getUri());
		System.out.println("dataSourceName:" + dataSourceName );
		System.out.println("url:" + dataSource.getUrl());

		// 获取最终的查询SQL，查询脚本加上查询表单通过IRUNNER执行后得出最终的结果
		// 创建search document
		if (report == null ) {
			report = new Report();
			report.setId("TEMP_REPORT_ID");
			report.setName("TEMP_REPORT_NAME");
			report.setApplicationid(applicationId);
		}
		report.setDataSourceSqlScript(sql);
		// 运行IRunner获取最终查询sql
		List<Object> sqlParamList = new ArrayList<Object>();
		String finalSql = this.getQueryString(params, user, null, sqlParamList, report );

		if (StringUtils.isBlank(finalSql)) {
			CommonException irptException = new CommonException();
			StringBuffer exceptionMsgSB = new StringBuffer();
			exceptionMsgSB.append("最终的查询sql为空!");
			irptException.setExceptionMsg(exceptionMsgSB.toString());
			throw irptException;
		}

		// 获取查询结果列信息
		resultQueryColumnInfos = runtimeOpenQueryService.getQueryColumnInfos(finalSql, dataSource.getDriverClass(), dataSource.getUrl(), dataSource.getUsername(), dataSource.getPassword());

		return resultQueryColumnInfos;

	}

	@Override
	public List<QueryColumnInfo> getFormColumnsInfos(String formId) throws Exception {
		FormDesignTimeService fProcess = DesignTimeServiceManager.formDesignTimeService();
		Form form = fProcess.doView(formId);
		//获取表单字段
		form.inited();
		Collection<FormField> fields = form.getFields();
		List<QueryColumnInfo> queryColumnInfos = new ArrayList<>();
		for(FormField field : fields){
			if(field instanceof TabField){
				Collection<Tab> tabs = ((TabField) field).getTabs();
				if(tabs !=null && tabs.size()>0){
					for(Tab tab : tabs){
						if (tab.getType().equals("form")) {
							Form tabForm = fProcess.doView(tab.getFormId());
							//获取表单字段
							tabForm.inited();
							Collection<FormField> tabFields = tabForm.getFields();
							for(FormField formField : tabFields){
								QueryColumnInfo queryColumnInfo = new QueryColumnInfo();
								queryColumnInfo.setColumnName(formField.getName());
								queryColumnInfo.setColumnLabel(formField.getName());
								queryColumnInfo.setColumnTypeName(formField.getFieldtype());
								queryColumnInfo.setColumnClassName("java.lang.String");
								queryColumnInfos.add(queryColumnInfo);
							}
						}
					}

				}
			}else {
				QueryColumnInfo queryColumnInfo = new QueryColumnInfo();
				queryColumnInfo.setColumnName(field.getName());
				queryColumnInfo.setColumnLabel(field.getName());
				queryColumnInfo.setColumnTypeName(field.getFieldtype());
				queryColumnInfo.setColumnClassName("java.lang.String");
				queryColumnInfos.add(queryColumnInfo);
			}
		}
		return queryColumnInfos;
	}

	@Override
	public String generateDynamicReportByProcedure(Report report, IUser user, ParamsTable params) throws Exception {
		ReportEngine engine = ReportEngine.getInstance();
		// 创建DynamicReport数据源和列信息
		String applicationId = report.getApplicationid();
		String procedureScript = report.getProcedureScript();
		String dataSourceName = report.getDataSourceName();
		// 获取数据源
		DataSource dataSource = dataSourceService.getDataSourceByName(dataSourceName, applicationId );

		// 创建search document
		Document searchDocument = null;
		String searchFormId = report.getDataSourceSearchForm();
		if (!StringUtils.isBlank(searchFormId)) {
			FormDesignTimeService fs = DesignTimeServiceManager.formDesignTimeService();
			Form searchForm = fs.doView(searchFormId);
			searchDocument = searchForm.createDocument(params, user); // getSearchDocument(view);
		}
		// 脚本加上查询表单通过IRUNNER执行后得出最终的结果
		IRunner runner = JavaScriptFactory.getInstance(user.getSessionid(), applicationId);
		runner.initBSFManager(searchDocument, params, user, new ArrayList<ValidateMessage>());
		//执行前清除JavaScript缓存
		JavaScriptFactory.clear();
		//执行iscript脚本
		Object object = runner.run(report, "Report[" + report.getName() + "]-" + report.getId(), procedureScript);
		if(object instanceof  String){
			procedureScript = (String)object;
		}
		runtimeOpenQueryService.generateDynamicReportDataSourceByProcedure(report, procedureScript, dataSource.getDriverClass(), dataSource.getUrl(), dataSource.getUsername(), dataSource.getPassword());

		String path = engine.exportHtml(report, params, user);

		if (StringUtil.isBlank(path)) {
			return "产生报表失败!";
		}

		return path;
	}

	/**
	 *      根据报表Id产生报表HTML返回访问路径
	 * @author laiq
	 * @param reportId
	 * @param user
	 * @param params
	 * @throws CommonException
	 */
	public String generateDynamicReportByReportId(String reportId, IUser user, ParamsTable params ) throws Exception {
		ReportEngine engine = ReportEngine.getInstance();
		Report sqlDataSourceReport = getSqlDataSourceReport(reportId,user,params);
		String path = engine.exportHtml(sqlDataSourceReport, params, user);

		if (StringUtil.isBlank(path)) {
			return "产生报表失败!";
		}

		return path;

	}

	/**
	 *      根据报表Id产生excel文件，并返回路径
	 * @author laiq
	 * @param reportId
	 * @param user
	 * @param params
	 * @throws CommonException
	 */
	public String generateExcelByReportId(String reportId, IUser user, ParamsTable params ) throws Exception {
		ReportEngine engine = ReportEngine.getInstance();
		Report sqlDataSourceReport = getSqlDataSourceReport(reportId,user,params);
		String path = engine.exportExcel(sqlDataSourceReport, params, user);

		return path;

	}

	/**
	 *      根据报表Id产生pdf文件，并返回路径
	 * @param reportId
	 * @param user
	 * @param params
	 * @throws CommonException
	 */
	public String generatePdfByReportId(String reportId, IUser user, ParamsTable params ) throws Exception {
		ReportEngine engine = ReportEngine.getInstance();
		Report sqlDataSourceReport = getSqlDataSourceReport(reportId,user,params);
		String path = engine.exportPdf(sqlDataSourceReport, params, user);

		return path;

	}
	private Report getSqlDataSourceReport(String reportId, IUser user, ParamsTable params)throws Exception{
		Report report = this.doView(reportId);
		// 创建DynamicReport数据源和列信息
		String applicationId = report.getApplicationid();
		String dataSourceName = report.getDataSourceName();
		// 获取数据源
		DataSource dataSource = dataSourceService.getDataSourceByName(dataSourceName, applicationId );

		System.out.println("dataSourceFileName:" + dataSource.getUri());
		System.out.println("dataSourceName:" + dataSourceName );
		System.out.println("url:" + dataSource.getUrl());

		// 获取最终的查询SQL，查询脚本加上查询表单通过IRUNNER执行后得出最终的结果
		// 创建search document
		Document searchDocument = null;
		String searchFormId = report.getDataSourceSearchForm();
		if (!StringUtils.isBlank(searchFormId)) {
			FormDesignTimeService fs = DesignTimeServiceManager.formDesignTimeService();
			Form searchForm = fs.doView(searchFormId);
			searchDocument = searchForm.createDocument(params, user); // getSearchDocument(view);
		}
		// 运行IRunner获取最终查询sql
		List<Object> sqlParamList = new ArrayList<Object>();
		String finalSql = this.getQueryString(params, user, searchDocument, sqlParamList, report);

		runtimeOpenQueryService.generateDynamicReportDataSource(report, finalSql, dataSource.getDriverClass(), dataSource.getUrl(), dataSource.getUsername(), dataSource.getPassword());
		return report;
	}

	private Report getViewDataSourceReport(Report report, Collection<Document> data,ParamsTable params,IUser user) throws Exception{

		String viewId = report.getViewId();
		ViewDesignTimeService vProcess = DesignTimeServiceManager.viewDesignTimeService();
		AbstractView view = vProcess.doView(viewId);
		IRunner runner = JavaScriptFactory.getInstance(user.getSessionid(), view.getApplicationid());
		Collection<Item> items = new LinkedList<>();
		Map<String,Object> itemsData = new HashMap<>();
		//列名集合
		List<Object> columnNameList = new LinkedList<>();
		List<Column> viewColumns = view.getColumns();
		for(Column column:viewColumns){
			//获取列名
			String name = column.getFieldName();
			columnNameList.add(name);
		}

		//创建数据源
		DRDataSource drDataSource = new DRDataSource(columnNameList.toArray(new String[viewColumns.size()]));

		for(Document doc:data){
			List<Object> list = new LinkedList<>();

			List<Column> columns = view.getColumns();
			for (Column column : columns) {
				try {
					runner.initBSFManager(doc, params, user, new ArrayList<ValidateMessage>());
					FormField field = column.getFormField();
					Map<String, Object> map = field.toAttributes(doc, runner, user, PermissionType.VIEW);
					//column.getFormField().recalculate(runner, doc, user);

					String value = column.getText(doc, runner, user);
					if (column.getType().equals(Column.COLUMN_TYPE_SCRIPT) ||
							(column.getShowType() != Column.SHOW_TYPE_VALUE &&
									(field.getClass().getSimpleName().equals("TreeDepartmentField") || field.getClass().getSimpleName().equals("DepartmentField") || field.getClass().getSimpleName().equals("UserField")))) {
						map.remove("value");
						map.put("value", value);
					}
					map.put("buttonType", StringUtil.isBlank(column.getButtonType())?"":column.getButtonType());
					map.put("templateFromId", StringUtil.isBlank(column.getTemplateForm())?"":column.getTemplateForm());
					if (!StringUtil.isBlank(column.getDecimalsNum())) {
						String columnName = column.getFieldName();
						switch(columnName){
							case "$StateLabel":
								try {//兼容历史数据，没有按照json格式存储情况
									String json =value.substring(1, value.length()-1);
									JSONObject stateLabelJson=JSONObject.fromObject(json);
									String stateLabel = stateLabelJson.getJSONArray("nodes").getJSONObject(0).getString("stateLabel");
									value = stateLabel;
									map.put("value", value);
								} catch (Exception e) {
								}
								break;
							case "$PrevAuditNode":
								value=value.substring(1, value.length()-1);
								JSONObject prevAuditNodeJson=JSONObject.fromObject(value);
								String prevAuditNode = prevAuditNodeJson.getString("prevAuditNode");
								value = prevAuditNode;
								map.put("value", value);
								break;
							case "$PrevAuditUser":
								value=value.substring(1, value.length()-1);
								JSONObject prevAuditUserJson=JSONObject.fromObject(value);
								String prevAuditUser = prevAuditUserJson.getString("prevAuditUser");
								value = prevAuditUser;
								map.put("value", value);
								break;
						}
					}

					String columnValue = (String)map.get("value");
					if (columnValue==null || columnValue.equals("")) {
						Item item = doc.findItem(field.getName());
						if(item != null){
							columnValue = item.getTextvalue();
						}
						map.put("value", columnValue);
					}
					list.add(map.get("value"));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			//向数据源插入数据
			drDataSource.add(list.toArray());
		}

		report.setDrDataSource(drDataSource);
		List<QueryColumnInfo> columnInfos = this.getViewColumnsInfos(viewId);
		// 创建列信息
		if (columnInfos.size() > 0 ) {
			List<ColumnBuilder> colms = new ArrayList<>();
			Iterator<QueryColumnInfo> iter = columnInfos.iterator();
			while (iter.hasNext()) {
				QueryColumnInfo queryColumnInfo = iter.next();
				String columnClassName = queryColumnInfo.getColumnClassName();

				colms.add(col.column(queryColumnInfo.getColumnLabel(), queryColumnInfo.getColumnName(), (DRIDataType) DataTypes.detectType(columnClassName)));    //colms.add(col.column("Item", "item", (DRIDataType)DataTypes.detectType("java.lang.String")));//type.stringType()));
			}
			report.setReportColumnInfos(colms);

		} else {
			report.setReportColumnInfos(null);
		}
		return report;
	}


	@Override
	public List<Report> list(String parentId, String pathSuffix, String fileSuffix, String name) throws Exception {
		return null;
	}
}