package cn.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import cn.util.core.IsKit;
import cn.util.core.LogKit;
import cn.util.core.TypeKit;
import cn.util.http.FileKit;
import cn.util.core.ServletKit;
import cn.util.string.JsonKit;
import cn.orm.abs.ISqlToyDao;
import cn.orm.sqltoy.dao.impl.SqlToyLazyDaoImpl;
import cn.orm.util.builder.BuildSQL;
import cn.report.excel.easyexcel.api.EasyExcel;
import cn.report.excel.easyexcel.api.ExcelReader;
import cn.report.excel.easyexcel.api.ExcelWriter;
import cn.report.excel.easyexcel.api.read.metadata.ReadSheet;
import cn.report.excel.easyexcel.api.write.metadata.WriteSheet;
import cn.report.excel.easyexcel.api.write.metadata.style.WriteCellStyle;
import cn.report.excel.easyexcel.api.write.style.HorizontalCellStyleStrategy;
import cn.report.excel.easyexcel.api.write.style.column.LongestMatchColumnWidthStyleStrategy;
import cn.report.excel.easyexcel.custom.SamDataListener;
import cn.report.excel.easyexcel.custom.SamTitleWriteHandler;
import cn.report.excel.util.EasyExcelUtil;
import cn.service.IEasyExcelService;


@Service
public class EasyExcelServiceImpl implements IEasyExcelService
{
	/**上传excel文件默认配置*/
	//默认是1，即0行为头，从第一行开始读取内容。后端处理上传的excel文件中标题所占行数
	private static int excelHeadRowNum = 1;
	/**页面JSON文件中数据表中的字段中英文对应关系*/
	//中文
	private static final String JSON_DB_FIELD_LABEL = "label";
	//字段名
	private static final String JSON_DB_FIELD_NAME = "name";


	public static void setParamExcelHeadRowNum(int num) {
		EasyExcelServiceImpl.excelHeadRowNum = num;
	}

	/**sqltoy*/
	@Autowired
	protected ISqlToyDao daoService;

	@Autowired
	protected SqlToyLazyDaoImpl daoService2;

	/**多sheet下载：主要处理VUE页面传来的参数。paramMap含有每个sheet所需参数.具体包括：
	 * FileName   导出文件名
	 * TableName  对应每个sheet的数据库表名 用,分割
	 * SheetName  对应每个sheet的名字 用,分割
	 * TitleName  对应每个sheet的一级标题 用,分割
	 * HeadField  每个sheet的表头信息。Map格式：key数据库字段：value对应excel表头字段
	 * WhereList 每个sheet的查询条件。json对象
	 * */
	public void exportSheets(Map<String, Object> paramMap) throws Exception
	{
		HttpServletResponse response = ServletKit.getResponse();
		String fileName = TypeKit.objToStr(paramMap.get("FileName"));
		FileKit.prepareRespond_xlsx(fileName, response);

		//需要读取数据的库表名称
		String tableName = TypeKit.objToStr(paramMap.get("TableName"));
		//excel表每个sheet的标题 后边subTitle
		String sheetName = TypeKit.objToStr(paramMap.get("SheetName"));
		//excel表的一级标题
		String titleName = TypeKit.objToStr(paramMap.get("TitleName"));
		//需要读取对应库表中的相关字段fieldStr

		String headField = TypeKit.objToStr(paramMap.get("HeadField"));
		//String headField = JSONObject.toJSONString(paramMap.get("HeadField"));
		if(IsKit.isNullOrEmpty(tableName) ||IsKit.isNullOrEmpty(headField)){
			throw new Exception();
		}
		String[] tableNameArry = tableName.split(",");
		String[] sheetNameArry = sheetName.split(",");
		String[] titleNameArry = titleName.split(";");
		String[] headFieldArry = headField.split(";");
		if(tableNameArry.length != headFieldArry.length) {
			throw new Exception();
		}	
		//查询每个表的条件
		List<Map<String, Object>> whereList = new ArrayList<Map<String, Object>>();
		String whereStr = TypeKit.objToStr(paramMap.get("WhereList"));
		if(IsKit.isNotNullOrEmpty(whereStr)) {
			//目前: 查询条件相同
			Map<String, Object> tempMap = JsonKit.json2Map_jackson(whereStr);
			if(IsKit.isNotNull(tempMap)) {
				whereList.add(tempMap);
			}
		}

		//一级标题	
		titleName = "满足条件的记录";
		if(IsKit.isNotNullOrEmpty(titleNameArry)) {
			titleName = titleNameArry[0];
		}
		//每个sheet的名字
		sheetName = "工作表";
		if(IsKit.isNotNullOrEmpty(sheetNameArry)) {
			sheetName = sheetNameArry[0];
		}
		ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
		WriteSheet writeSheet = null;
		int sheetSize = headFieldArry.length;
		//循环一次，写一个sheet
		for(int i=0; i<sheetSize; ++i) 
		{
			//查询条件
			Map<String,Object> whereMap = new HashMap<>();
			if(IsKit.isNotNullOrEmpty(whereList)) {
				whereMap = whereList.get(i);
			}
			//确定一级标题。可自动补全
			if(titleNameArry.length > i) {
				titleName = titleNameArry[i];
			}
			List<Map<String, Object>> headFieldList = new ArrayList<Map<String, Object>>();
			//每个sheet的表中字段与excel字段标题即二级标题的对应值（KV）
			headFieldList = JsonKit.jsonToList_gson(headFieldArry[i]);

			Map<String, Object> headFieldMap = new HashMap<String, Object>(); 
			headFieldMap = _getFieldTitleMap(headFieldList);			
			StringBuffer key = new StringBuffer();
			StringBuffer value = new StringBuffer();
			headFieldMap.forEach((k,v)->{key.append(k).append(",");value.append(v).append(",");});
			//拟查询的表字段
			String item = TypeKit.objToStr(key);
			if(IsKit.isNotNullOrEmpty(item)){
				item = item.substring(0,item.length()-1);
			}			
			//EXCEL报表的表头中文字段
			String subTitle = TypeKit.objToStr(value);
			if(IsKit.isNotNullOrEmpty(subTitle)){
				subTitle = subTitle.substring(0,subTitle.length()-1);
			}
			List<String> vList = Arrays.asList(subTitle.split(","))
					.stream().map(s -> (s.trim()))
					.collect(Collectors.toList());
			List<List<String>> head = EasyExcelUtil.head(vList,titleName);

			//从数据库中检索指定表中指定字段的内容
			tableName = tableNameArry[i];
			List<Map<String, Object>> data = daoService.getList_order(tableName,item,whereMap);
			List<List<String>> dataList = EasyExcelUtil.content(data); 
			//确定sheet的名字。可自动补全
			if(titleNameArry.length > i) {
				sheetName = sheetNameArry[i];
			}
			//每次都要创建writeSheet;必须指定sheetNo 而且sheetName必须不一样;
			writeSheet = EasyExcel.writerSheet(i,sheetName)
					.head(head)
					.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
					.registerWriteHandler(EasyExcelUtil.getStyleStrategy2())
					.build();
			excelWriter.write(dataList,writeSheet);//data
		}
		//多个sheet页填充数据结束之后，使用finish()。
		if (IsKit.isNotNullOrEmpty(excelWriter)) {
			excelWriter.finish();//关闭流，必须的
		}	
	}

	/** 利用多sheet上传数据.excel文件的
	 * 默认格式：
	 *  第一行为中文标题；数据行从第二行开始：
	 *  多个TableName之间用,分割；
	 *  JsonData多个excel的sheet的表头字段之间用；分割
	 * */
	public Integer importSheets(MultipartFile mFile,Map<String,Object> mapRecord) 
	{
		Integer result = -1;
		if(IsKit.isNullOrEmpty(mapRecord)){
			return result;	
		}
		String jsonStr = TypeKit.objToStr(mapRecord.get("JsonData"));
		if(IsKit.isNullOrEmpty(jsonStr)){
			return result;	
		}
		String[] jsonArry = jsonStr.split(";");
		if(IsKit.isNullOrEmpty(jsonArry)){
			return result;	
		}
		/***要写入数据的数据库表名*/
		String tableName = TypeKit.objToStr(mapRecord.get("TableName"));
		String[] tableArry = tableName.split(",");

		ArrayList<String> sqlList = new ArrayList<String>();
		SamDataListener excelListener = new SamDataListener();
		ExcelReader excelReader = null;
		InputStream inputStream = null;
		List<Map<String, Object>> listMap = null;
		Map<String, Object> fieldTitleMap = null;
		for(int i = 0; i < jsonArry.length; ++i ) 
		{
			/** 获取每个sheet的表头字段对应关系。每个Map的格式：
			 * {label=用户ID, name=user_id}【TSysUser.json】 
			 * 对应上传excel表的表头字段(label)和库表的字段(name)
			 */
			listMap = JsonKit.jsonToList_gson(jsonArry[i]);

			/**加工处理成map格式：{user_id=用户ID,...}*/
			fieldTitleMap = _getFieldTitleMap(listMap);
			try {
				inputStream = mFile.getInputStream();
				excelReader = EasyExcel.read(inputStream).build();
				ReadSheet readSheet = EasyExcel.readSheet(i)
						/**依据表头所在行excelHeadRowNum(从1开始)*/
						.headRowNumber(excelHeadRowNum)
						.registerReadListener(excelListener)
						.build();
				excelReader.read(readSheet);//excelReader.readAll();读取所有的
				/**从上传excel数据文件中获取表头信息。比如：{0=用户ID,...}*/
				Map<Integer, String> head = excelListener.getHead();
				/**从上传excel数据文件中获取表头所在行的下一行开始的数据信息。
				 * 比如：{{0=1, 1=103,...}*/
				List<Object> detail = excelListener.getData();
				ArrayList<String> sql = _genSQL(tableArry[i],fieldTitleMap,head,detail);

				sqlList = _mergeList(sqlList,sql);
				//清空list数据
				excelListener.getData().clear();
				excelListener.getHead().clear();
			} catch (Exception e) {
				LogKit.info(e);
				return result;
			}finally {
				if (IsKit.isNotNull(inputStream)) {
					try {
						inputStream.close();
					} catch (IOException e) {
						LogKit.info(e);
						return result;	
					}
				}
				if (IsKit.isNotNull(excelReader)) {
					excelReader.finish();
				}
			}
		}
		return daoService.executeBatch(sqlList);
	}
	
	/**合并List ListAddALL  */
	private <T> ArrayList<T> _mergeList(List<T> list1, List<T> list2)
	{
		ArrayList<T> mergeList = new ArrayList<>(list1);
		if(IsKit.isNotNullOrEmpty(list2)) {
			mergeList.addAll(list2);
		}
		return mergeList;
	}
	/**生成SQL语句*/
	private ArrayList<String> _genSQL(String tableName,Map<String, Object> resultMap,
			Map<Integer, String> head,List<Object> data)
	{
		if(IsKit.isNullOrEmpty(data)){
			return null;
		}
		//resultMap(表字段名：列中文名字)；head(excel列序号：表字段名 )
		Map<Integer, Object> mapPair = _getMapV(resultMap,head);//0=account
		Map<String, Object> mapT = new LinkedHashMap<String, Object>();
		ArrayList<String> sqlList = new ArrayList<String>();
		for (Object obj : data) {
			Map<String,Object> m = JsonKit.jsonObjToMap(obj);//0=号33(列序号=取值)
			mapT = _getMapK(mapPair,m);//account=号33(表字段=取值)
			List<Map<String, Object>> listRecord = new ArrayList<Map<String, Object>>();
			if(IsKit.isNotNullOrEmpty(mapT)){
				listRecord.add(mapT);
			}
			ArrayList<String> sql = BuildSQL.batchUpdateInsert(tableName,listRecord);
			sqlList = _mergeList(sqlList,sql);
		}
		return sqlList;
	}
	/**依据两个map中相同Key,构造一新的map: map1:0=account; map2:0=号33 ; 结果：account=号33*/
	private Map<String, Object> _getMapK(Map<Integer,Object> map1,Map<String, Object> map2)
	{
		Map<String, Object> mapResult = new HashMap<String, Object>();
		if(IsKit.isNullOrEmpty(map1)){
			return mapResult;
		}

		for(Map.Entry<Integer,Object> entry1 : map1.entrySet())
		{
			String m1Key = (entry1.getKey() == null) ? null : entry1.getKey().toString(); 
			Object m1Value = entry1.getValue();
			if(IsKit.isNotNullOrEmpty(map2)){
				for(Map.Entry<String, Object> entry2 : map2.entrySet()){
					String m2Key = entry2.getKey();
					Object m2Value = entry2.getValue();
					if (m1Key.equals(m2Key)) {//若两个map中相同key对应的value不相等
						m2Key = TypeKit.objToStr(m1Value);
						if(IsKit.isNotNullOrEmpty(m2Key)) {
							mapResult.put(m2Key,m2Value);
						}
					}
				}
			}
		} 
		return mapResult;
	}
	/**依据两个map中相同value,构造一新的map
	 * 传入：resultMap(map1:表字段名=列中文名字)；head(map2:excel列序号=表字段名 )
	 * 返回：0=account()
	 * */
	private Map<Integer,Object> _getMapV(Map<String, Object> map1,Map<Integer,String> map2)
	{
		Map<Integer, Object> mapResult = new HashMap<Integer,Object>();
		if(IsKit.isNullOrEmpty(map1)) {
			return mapResult;
		}
		for(Map.Entry<String, Object> entry1 : map1.entrySet())
		{
			String m1Key = entry1.getKey();
			Object m1Value = entry1.getValue();
			if(IsKit.isNotNullOrEmpty(map2)) {
				for(Map.Entry<Integer,String> entry2 : map2.entrySet()){
					Integer m2Key = entry2.getKey();
					Object m2Value = entry2.getValue();
					/**if (m1Key.equals(m2Value)) {
						mapResult.put(m2Key,m1Value);
					}*/
					if (m1Value.equals(m2Value)) {
						mapResult.put(m2Key,m1Key);
					}
				}
			}
		} 
		return mapResult;
	}	
	private Map<String, Object> _getFieldTitleMap(List<Map<String, Object>> listMap) 
	{
		if(IsKit.isNullOrEmpty(listMap)) {
			return null;
		}
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
		for (Map<String, Object> map : listMap) {
			String key = "";
			Object value = "";
			for (String k : map.keySet()) {
				// 根据指定的key取值
				if ((JSON_DB_FIELD_LABEL).equals(k)) {
					value = map.get(k);
				}
				// 根据指定的key取值
				else if ((JSON_DB_FIELD_NAME).equals(k)) {
					key = TypeKit.objToStr(map.get(k));
				}
			}
			if(IsKit.isNotNullOrEmpty(key)) {
				resultMap.put(key,value);
				key = "";
				value = "";
			}
		}
		return resultMap;
	}
	public void xbm() {}












	/**产生本地excel文件，数据dataList；String文件路径+文件名
	 * bigtitle一级标题,String []header二级标题
	 */
	@Override
	public void genLocalExcel(List<Map<String, Object>> dataList,
			String filePath,String bigtitle,String []header)
	{
		List<List<String>> data = EasyExcelUtil.content(dataList);

		// 内容样式
		WriteCellStyle contentWriteCellStyle = EasyExcelUtil.getContentStyle();
		HorizontalCellStyleStrategy horizontalCellStyleStrategy =
				new HorizontalCellStyleStrategy(EasyExcelUtil.getHeadStyle(), contentWriteCellStyle);

		ExcelWriter excelWriter = EasyExcel.write(filePath)
				//.password("1234")//加密
				.inMemory(true) //此项配置不能少
				.build();
		WriteSheet writeSheet = EasyExcel.writerSheet("报表内容")
				.head(EasyExcelUtil.head(header))
				// 第一行大标题样式设置
				.registerWriteHandler(new SamTitleWriteHandler(bigtitle,header))
				//设置默认样式及写入头信息开始的行数
				.relativeHeadRowIndex(excelHeadRowNum)         
				// 表头、内容样式设置
				.registerWriteHandler(horizontalCellStyleStrategy)
				//.registerWriteHandler(new SamCellDrawSlashHandler(1,0,2,1,text,slashType))
				.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
				.build();
		excelWriter.write(data, writeSheet);
		if (IsKit.isNotNull(writeSheet)) {
			excelWriter.finish();
		}
	}








	/////////////

	/**多sheet下载。
	 * paramMap  含有每个sheet所需参数.具体包括：
	 * FileName  导出文件名
	 * HeadFieldList 每个sheet的表头信息。Map格式：key数据库字段：value对应excel表头字段
	 * SheetList 每个sheet的一级标题、sheet名称、数据库
	 * WhereList 每个sheet的查询条件
	 * 注意：SheetList、HeadFieldList的长度应该一致
	 * @throws Exception */
	@Override
	public void exportSheets_map(Map<String, Object> paramMap) throws Exception
	{

		if(IsKit.isNullOrEmpty(paramMap)) {
			throw new Exception();
		}

		HttpServletResponse response = ServletKit.getResponse();
		String fileName = TypeKit.objToStr(paramMap.get("FileName"));
		FileKit.prepareRespond_xlsx(fileName, response);

		//每个sheet的一级标题、sheet名称、数据库
		String sheetStr = TypeKit.objToStr(paramMap.get("SheetList"));

		List<Map<String,Object>> sheetList = new ArrayList<Map<String,Object>>();
		sheetList = JsonKit.jsonToList_gson(sheetStr);

		if(IsKit.isNullOrEmpty(sheetList)) {
			throw new Exception();
		}

		//需要读取对应每个库表中的相关字段
		String headFieldStr = TypeKit.objToStr(paramMap.get("HeadFieldList"));
		List<Map<String, Object>> headFieldList = new ArrayList<Map<String, Object>>();
		headFieldList = JsonKit.jsonToList_gson(headFieldStr);
		if(IsKit.isNullOrEmpty(headFieldList)) {
			throw new Exception();
		}

		if(sheetList.size() != headFieldList.size()) {
			throw new Exception();
		}

		//查询每个表的条件
		List<Map<String, Object>> whereList = new ArrayList<Map<String, Object>>();
		String whereStr = TypeKit.objToStr(paramMap.get("WhereList"));
		if(IsKit.isNotNullOrEmpty(whereStr)) {
			whereList = JsonKit.jsonToList_gson(whereStr);
		}

		ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();

		WriteSheet writeSheet = null;
		int sheetSize = headFieldList.size();

		//循环一次，写一个sheet
		for(int i=0; i<sheetSize; ++i) 
		{
			Map<String,Object> sheetMap = sheetList.get(i);
			Map<String,Object> headFieldMap = headFieldList.get(i);

			Map<String,Object> whereMap = new HashMap<>();
			if(IsKit.isNotNullOrEmpty(whereList)) {
				whereMap = whereList.get(i);
			}
			//excel表的一级标题
			String title = TypeKit.objToStr(sheetMap.get("Title"));
			//excel表每个sheet的标题
			String sheetName = TypeKit.objToStr(sheetMap.get("SheetName"));
			//需要读取数据的库表名称(与每个sheet相对应)
			String tableName = TypeKit.objToStr(sheetMap.get("TableName"));

			//每个sheet的表中字段与excel字段标题即二级标题的对应值（KV）
			StringBuffer key = new StringBuffer();
			StringBuffer value = new StringBuffer();
			headFieldMap.forEach((k,v)->{key.append(k).append(",");value.append(v).append(",");});
			//查询字段
			String item = TypeKit.objToStr(key);
			if(IsKit.isNotNullOrEmpty(item)){
				item = item.substring(0,item.length()-1);
			}

			String subTitle = TypeKit.objToStr(value);
			if(IsKit.isNotNullOrEmpty(subTitle)){
				subTitle = subTitle.substring(0,subTitle.length()-1);
			}
			List<String> vList = Arrays.asList(subTitle.split(","))
					.stream().map(s -> (s.trim()))
					.collect(Collectors.toList());

			List<List<String>> head = EasyExcelUtil.head(vList,title);

			//String[] header = subTitle.split(",");
			//从数据库中检索指定表中指定字段的内容
			//String where = BuildWhere.genQueryWrapper(tableName,whereMap,"");
			//List<Map<String, Object>> data = service.query(tableName,item,where);
			List<Map<String, Object>> data = daoService.getList(tableName,item,whereMap);

			List<List<String>> dataList = EasyExcelUtil.content(data); 

			//每次都要创建writeSheet;必须指定sheetNo 而且sheetName必须不一样;
			writeSheet = EasyExcel.writerSheet(i,sheetName)
					.head(head)//一级和二级标题样式一样
					/** 第一行大标题样式设置
					        .head(EasyExcelUtil.head(header))
							.registerWriteHandler(new SamTitleWriteHandler(title,header))
							.relativeHeadRowIndex(1)
					 */
					.registerWriteHandler(EasyExcelUtil.getStyleStrategy())
					//统一列宽
					.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
					.build();
			excelWriter.write(dataList,writeSheet);//data
		}
		System.out.println("W5-19:" );
		//多个sheet页填充数据结束之后，使用finish()。
		if (IsKit.isNotNullOrEmpty(excelWriter)) {
			excelWriter.finish();//关闭流，必须的
		}	
	}

	///////////////////////////////////////////////////////////////////
	/**多sheet下载。此方法待验证
	 * paramMap  含有每个sheet所需参数.具体包括：
	 * FileName  导出文件名
	 * HeadFieldList 每个sheet的表头信息。Map格式：key数据库字段：value对应excel表头字段
	 * SheetList 每个sheet的一级标题、sheet名称
	 * SQLList 对应每个sheet的SQL查询语句
	 * 注意：SheetList、HeadFieldList的长度应该
	 * @throws Exception */
	@Override
	public void exportSheets_sql(Map<String, Object> paramMap) throws Exception
	{
		if(IsKit.isNullOrEmpty(paramMap)) {
			throw new Exception();
		}

		HttpServletResponse response = ServletKit.getResponse();
		String fileName = TypeKit.objToStr(paramMap.get("FileName"));
		FileKit.prepareRespond_xlsx(fileName, response);

		//每个sheet的一级标题、sheet名称、数据库
		String sheetStr = TypeKit.objToStr(paramMap.get("SheetList"));
		List<Map<String,Object>> sheetList = new ArrayList<Map<String,Object>>();
		sheetList = JsonKit.jsonToList_gson(sheetStr);
		if(IsKit.isNullOrEmpty(sheetList)) {
			throw new Exception();
		}

		//需要读取对应每个库表中的相关字段
		String headFieldStr = TypeKit.objToStr(paramMap.get("HeadFieldList"));
		List<Map<String, Object>> headFieldList = new ArrayList<Map<String, Object>>();
		headFieldList = JsonKit.jsonToList_gson(headFieldStr);
		if(IsKit.isNullOrEmpty(headFieldList)) {
			throw new Exception();
		}

		if(sheetList.size() != headFieldList.size()) {
			throw new Exception();
		}
		//查询每个表的SQL语句
		List<String> sqlList = new ArrayList<String>();
		String sqlStr = TypeKit.objToStr(paramMap.get("SQLList"));
		if(IsKit.isNotNullOrEmpty(sqlStr)) {
			sqlList = new JsonKit<String>().jsonToList_jackson(sqlStr,String.class);
		}
		if(sheetList.size() != sqlList.size()) {
			throw new Exception();
		}

		ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
		WriteSheet writeSheet = null;
		int sheetSize = headFieldList.size();
		//循环一次，写一个sheet
		for(int i=0; i<sheetSize; ++i) 
		{
			Map<String,Object> sheetMap = sheetList.get(i);
			Map<String,Object> headFieldMap = headFieldList.get(i);

			//excel表的一级标题
			String title = TypeKit.objToStr(sheetMap.get("Title"));
			//excel表每个sheet的标题
			String sheetName = TypeKit.objToStr(sheetMap.get("SheetName"));

			//每个sheet的表中字段与excel字段标题即二级标题的对应值（KV）
			StringBuffer key = new StringBuffer();
			StringBuffer value = new StringBuffer();
			headFieldMap.forEach((k,v)->{
				key.append(k).append(",");value.append(v).append(",");}
					);
			//查询字段
			String item = TypeKit.objToStr(key);
			if(IsKit.isNotNullOrEmpty(item)){
				item = item.substring(0,item.length()-1);
			}
			String subTitle = TypeKit.objToStr(value);
			if(IsKit.isNotNullOrEmpty(subTitle)){
				subTitle = subTitle.substring(0,subTitle.length()-1);
			}
			List<String> vList = Arrays.asList(subTitle.split(","))
					.stream().map(s -> (s.trim()))
					.collect(Collectors.toList());
			List<List<String>> head = EasyExcelUtil.head(vList,title);
			//从数据库中检索指定表中指定字段的内容
			//List<Map<String, Object>> data = service.executeQuery(sqlList.get(i));
			List<Map<String, Object>> data = daoService.getListBySql(sqlList.get(i));
			List<List<String>> dataList = EasyExcelUtil.content(data); 

			//每次都要创建writeSheet;必须指定sheetNo 而且sheetName必须不一样;
			writeSheet = EasyExcel.writerSheet(i,sheetName)
					.head(head)
					.registerWriteHandler(EasyExcelUtil.getStyleStrategy())
					.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
					.build();
			excelWriter.write(dataList,writeSheet);//data
		}

		//多个sheet页填充数据结束之后，使用finish()。
		if (IsKit.isNotNullOrEmpty(excelWriter)) {
			excelWriter.finish();//关闭流，必须的
		}	
	}













}