package com.foreverwin.mesnac.common.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.foreverwin.mesnac.common.mapper.CustomReportConfigMapper;
import com.foreverwin.mesnac.common.mapper.CustomReportMapper;
import com.foreverwin.mesnac.common.model.*;
import com.foreverwin.mesnac.common.service.CustomReportInterface;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *
 * @Title:  CustomReportImpl.java
 * @Package com.knsdev.service.impl
 * @Description: 自定义报表 接口实现
 * @author: Andy
 * @date:   2020年10月15日 下午1:21:56
 * @version V1.0
 *
 * @History 操作记录
 * 2020年10月15日 下午1:21:56 Andy add
 *
 */
@Service
public class CustomReportImpl implements CustomReportInterface {

	@Autowired
	private CustomReportConfigMapper customReportConfigMapper;
	@Autowired
	private CustomReportMapper customReportMapper;


	@Override
	public CustomReportConfig Load(String site, String reportid) throws Exception {

		CustomReportConfig config=new CustomReportConfig();

		//2020-11-6 andy, 因所有的 site共用配置，所以此处site直接给*
		//String mainHandle="CustomReportBO:"+site+","+reportid;
		String mainHandle="CustomReportBO:*,"+reportid;

		Map<String, Object> param = new HashMap<String, Object>();
		param.put("SITE", "*");
		param.put("REPORT_ID", reportid);

		//2020-11-6 andy, 因所有的 site共用配置，所以此处site直接给*
		//自定义报表_主要模块 数据
		//List<Map<String,Object>> map=logicService.executeQuery(site, QUERY_MAIN_SQL, param);
		//List<Map<String,Object>> map=logicService.executeQuery("*", QUERY_MAIN_SQL, param);
		List<CustomReportMainmodel> map = customReportConfigMapper.selectMain("*", reportid);

		if(map.size()<1)
		{
			//40025.simple = 查询无资料
			//throw Exceptions.convert(new BasicBOBeanException(40025,new Data()));
			throw new RuntimeException("查询无资料");
		}else
		{
			if(map.get(0).getConditionSqlConfig()==null || map.get(0).getConditionSqlConfig().trim().length()<1)
			{
				//70502.simple=请在检索语句配置栏填写 SQL语句
				//throw Exceptions.convert(new BasicBOBeanException(70502,new Data()));
				throw new RuntimeException("请在检索语句配置栏填写 SQL语句 ");
			}

			//获取 Z_CUSTOM_REPORT_MAINMODEL 表中相关字段
			config.setHandle(map.get(0).getHandle()==null?"":map.get(0).getHandle());
			config.setSite(site);
			config.setReportID(reportid);
			config.setReportTitle(map.get(0).getReportTitle()==null?"":map.get(0).getReportTitle().trim());
			config.setReportDESC(map.get(0).getReportDesc()==null?"":map.get(0).getReportDesc().toString().trim());
			config.setConditionSQLConfig(map.get(0).getConditionSqlConfig()==null?"":map.get(0).getConditionSqlConfig().toString().trim());
			config.setDisplayType(map.get(0).getDisplayType()==null?"":map.get(0).getDisplayType().toString().trim());
			config.setTimeRefresh(map.get(0).getTimeRefresh()==null?"0":map.get(0).getTimeRefresh().toString());
			config.setBackgroundColor(map.get(0).getBackgroundColor()==null?"":map.get(0).getBackgroundColor().toString().trim());
			config.setFontColor(map.get(0).getFontColor()==null?"":map.get(0).getFontColor().toString().trim());
			config.setPageSize(map.get(0).getPageSize()==null?"0":map.get(0).getPageSize().toString());
			config.setUser(map.get(0).getModifyUser()==null?"":map.get(0).getModifyUser().toString().trim());
		}

		param=null;

		//自定义报表_检索条件配置 数据

		List<CustomReportSearchConditionConfig> conditionConfigList=new ArrayList<CustomReportSearchConditionConfig>();

		param=new HashMap<String, Object>();
		param.put("MAINHANDLE", mainHandle);


		//map=logicService.executeQuery(site, QUERY_SEARCHCONDITIONCONFIG_SQL, param);
		List<CustomReportSearchConditionConfig> searchConditionMap = customReportConfigMapper.selectSearchConditionConfig( mainHandle );

		for(int i=0;i<searchConditionMap.size();i++)
		{
			CustomReportSearchConditionConfig searchConditionConfig=new CustomReportSearchConditionConfig();
			searchConditionConfig.setSeq(searchConditionMap.get(i).getSeq()==null?0:searchConditionMap.get(i).getSeq());
			searchConditionConfig.setConditionName(searchConditionMap.get(i).getConditionName()==null?"":searchConditionMap.get(i).getConditionName().toString());
			searchConditionConfig.setConditionField(searchConditionMap.get(i).getConditionField()==null?"":searchConditionMap.get(i).getConditionField().toString());
			searchConditionConfig.setFieldType(searchConditionMap.get(i).getFieldType()==null?"":searchConditionMap.get(i).getFieldType().toString());
			searchConditionConfig.setDailogCheckboxSQL(searchConditionMap.get(i).getDailogCheckboxSQL()==null?"":searchConditionMap.get(i).getDailogCheckboxSQL().toString());
			searchConditionConfig.setRequiredType(searchConditionMap.get(i).getRequiredType()==null?"":searchConditionMap.get(i).getRequiredType().toString());
			searchConditionConfig.setRowID(searchConditionMap.get(i).getRowID()==null?1:searchConditionMap.get(i).getRowID());
			searchConditionConfig.setColumnID(searchConditionMap.get(i).getColumnID()==null?1:searchConditionMap.get(i).getColumnID());
			searchConditionConfig.setColumnWidthPercent(searchConditionMap.get(i).getColumnWidthPercent()==null?1:searchConditionMap.get(i).getColumnWidthPercent());
			conditionConfigList.add(searchConditionConfig);
		}

		//更新检索条件栏位的值
		int k=0;
		for(CustomReportSearchConditionConfig searchConditionConfig:conditionConfigList)
		{
			if (searchConditionConfig.getDailogCheckboxSQL().trim().isEmpty()) {

				conditionConfigList.get(k).setFieldValueList(new ArrayList());
			} else {
				String dictOrSql = searchConditionConfig.getDailogCheckboxSQL();
				if (dictOrSql.startsWith("SELECT".toUpperCase())) {
					//当 弹出复选框数据获取SQL 有值时，依SQL获取相应的字段值列表
					//List<Map<String, Object>> result=logicService.executeQuery(site, searchConditionConfig.getDailogCheckboxSQL().trim(), new HashMap<String,Object>());
					List<Map<String, Object>> result = customReportMapper.executeSqlQuery(dictOrSql.trim());
					if (result.size() > 0) {
						List<Map<String, Object>> lst = new ArrayList<>();
						for (Map<String, Object> m : result) {
							Map<String, Object> _map = new HashMap<>();
							for (String key : m.keySet()) {
								_map.put("key", m.get(key));
								_map.put("text", m.get(key));
								break;
							}
							lst.add(_map);
						}
						conditionConfigList.get(k).setFieldValueList(lst);
					}
				} else if (dictOrSql.contains("*") && dictOrSql.contains(";")) {
					String[] dictOrSqlArray = dictOrSql.split(";");
					if (dictOrSqlArray != null && dictOrSqlArray.length > 0) {
						List<Map<String, Object>> mapList = new ArrayList<>();

						Map<String, Object> _map = null;
						for (int i = 0; i < dictOrSqlArray.length; i++) {
							String keyValue =  dictOrSqlArray[i];
							if (!keyValue.contains("*")) {
								continue;
							}
							_map = new HashMap<>();
							_map.put("key", keyValue.split("\\*")[0]);
							_map.put("text", keyValue.split("\\*")[1]);
							mapList.add(_map);
						}
						conditionConfigList.get(k).setFieldValueList(mapList);
					}
				}
			}

			k++;
		}

		config.setSearchConditionConfigList(conditionConfigList);

		//自定义报表_检索结果列配置
		List<CustomReportSearchResultColumnConfig> resultColumnConfigList=new ArrayList<CustomReportSearchResultColumnConfig>();

		//map=logicService.executeQuery(site, QUERY_RESULTCOLUMNCONFIG_SQL, param);
		List<CustomReportSearchResultColumnConfig> resultColumnMap = customReportConfigMapper.selectResultColumnConfig( mainHandle );

		for(int i=0;i<resultColumnMap.size();i++)
		{
			CustomReportSearchResultColumnConfig resultColumnConfig=new CustomReportSearchResultColumnConfig();
			resultColumnConfig.setSeq(resultColumnMap.get(i).getSeq()==null?"0":resultColumnMap.get(i).getSeq().toString());
			resultColumnConfig.setColumnField(resultColumnMap.get(i).getColumnField()==null?"":resultColumnMap.get(i).getColumnField().toString().trim());
			resultColumnConfig.setColumnName(resultColumnMap.get(i).getColumnName()==null?"":resultColumnMap.get(i).getColumnName().toString().trim());
			resultColumnConfig.setColumnWidthPercent(resultColumnMap.get(i).getColumnWidthPercent()==null?"1":resultColumnMap.get(i).getColumnWidthPercent().toString().trim());
			resultColumnConfigList.add(resultColumnConfig);
		}

		config.setSearchResultColumnList(resultColumnConfigList);

		param=null;
		map=null;

		return config;
	}

	/* (non-Javadoc)
	 * @see com.knsdev.service.CustomReportInterface#Query(java.lang.String)
	 */
	@Override
	public List<Map<String, Object>> Query(String condition) throws Exception {

		JSONObject object = JSONObject.parseObject(condition);
		String site=object.getString("site");
		String reportID=object.getString("reportID");

		if((site==null || site.trim().isEmpty()) || (reportID==null || reportID.trim().isEmpty()))
		{
			//70501.simple=站点、报表作业编号均不能为空
			//throw Exceptions.convert(new BasicBOBeanException(70501,new Data()));
			throw new RuntimeException("站点、报表作业编号均不能为空");
		}

		//1.获取检索语句配置

		String querySentence="";

		Map<String, Object> param = new HashMap<String, Object>();
		param.put("SITE", "*");
		param.put("REPORT_ID", reportID);

		//List<Map<String,Object>> map=logicService.executeQuery("*", GET_QUERY_SENTENCE_SQL, param);
		List<CustomReportMainmodel> map= customReportMapper.selectQuerySentence("*",reportID);
		if(map.size()>0)
		{
			querySentence=map.get(0).getConditionSqlConfig()==null?"":map.get(0).getConditionSqlConfig();
		}

		if(querySentence.trim().isEmpty())
		{
			throw new RuntimeException("请在检索语句配置栏填写 SQL语句");
		}


		//2.依定的规则 检索语句中需替换的内容 以 :开头，所以此处依:先做下判断是否有需替换的内容
		if(querySentence.indexOf(":")>1)
		{
			//处理需替换的数据
			param = new HashMap();
			param.put("MAINHANDLE", "CustomReportBO:*,"+reportID);

			//map=logicService.executeQuery(site, QUERY_DYNSQLCONFIG_SQL, param);
			List<CustomReportSearchConditionDynSQLConfig> dynSqlConfigMap = customReportConfigMapper.selectDynSqlConfig( "CustomReportBO:*,"+reportID );

			for(int i=0;i<dynSqlConfigMap.size();i++)
			{
				if(dynSqlConfigMap.get(i).getDynConditionReplaceField()==null || dynSqlConfigMap.get(i).getDynConditionReplaceField().trim().isEmpty() || dynSqlConfigMap.get(i).getDynamicConditionSQL()==null || dynSqlConfigMap.get(i).getDynamicConditionSQL().trim().isEmpty() || dynSqlConfigMap.get(i).getConditionField()==null || dynSqlConfigMap.get(i).getConditionField().trim().isEmpty())
				{
					//70503.simple=自定义报表配置的‘检索条件动态SQL配置’模块 各栏位均需填写有效值
					//throw Exceptions.convert(new BasicBOBeanException(70503,new Data()));
					throw new RuntimeException("自定义报表配置的‘检索条件动态SQL配置’模块 各栏位均需填写有效值");
				}


				if( dynSqlConfigMap == null || dynSqlConfigMap.get(i)==null || object.getString(dynSqlConfigMap.get(i).getConditionField()) == null)
				{
					querySentence=querySentence.replaceAll(dynSqlConfigMap.get(i).getDynConditionReplaceField().trim(), " ");

				}else
				{

					// 2020-11-5 andy ,
					//因在 检索条件动态SQL配置 时输入的动态条件SQL为 AND SFC=@SFC 或 AND SFC IN(@SFC)  所以跟前台商定 当有多个值时，中间用 , 分隔；后台接收后做处理
					String[] vlsp=object.getString(dynSqlConfigMap.get(i).getConditionField().trim()).split(",");
					StringBuilder sb=new StringBuilder();
					int j=0;
					for(int k=0;k<vlsp.length;k++)
					{
						j++;
						if(j<vlsp.length)
						{
							sb.append("'"+vlsp[k].toString().trim()+"',");
						}else
						{
							sb.append("'"+vlsp[k].toString().trim()+"'");
						}
					}
					querySentence=querySentence.replaceAll(dynSqlConfigMap.get(i).getDynConditionReplaceField().trim(), dynSqlConfigMap.get(i).getDynamicConditionSQL().trim().replace("@"+dynSqlConfigMap.get(i).getConditionField().trim(), sb.toString())
							.replace("#"+dynSqlConfigMap.get(i).getConditionField().toString().trim(), "'%"+sb.toString().substring(1, sb.toString().length()-1)+"%'"));
					// queryMap.put(map.get(i).get("DYN_CONDITION_REPLACE_FIELD").toString().trim(), map.get(i).get("DYNAMIC_CONDITION_SQL").toString().trim().replace("@"+map.get(i).get("CONDITION_FIELD").toString().trim(), object.optString(map.get(i).get("CONDITION_FIELD").toString().trim())));
				}
			}

		}


		//替换站点 2021/08/19
		querySentence = querySentence.replace(":SITE","\'"+site+"\'");

		//3.执行查询
		//List<Map<String, Object>> result=logicService.executeQuery(site, querySentence,siteParam);
		List<Map<String, Object>> result= customReportMapper.executeSqlQuery( querySentence );

		//2020-11-17 andy add;解决value值为null时，转json会被移除的问题
		for(int i=0;i<result.size();i++)
		{
			for(Map.Entry<String, Object> entry:result.get(i).entrySet())
			{
				if(entry.getValue()==null)
				{
					result.get(i).put(entry.getKey(), " ");
				}
			}
		}

		return result;
	}
}
