/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.sg.raiseCapital.service;

import com.jeeplus.common.config.Global;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.sg.financial.erpcredit.util.SerializeUtil;
import com.jeeplus.modules.sg.managementcenter.activiti.utils.MyActiviUtils;
import com.jeeplus.modules.sg.picking.activiti.entity.*;
import com.jeeplus.modules.sg.picking.activiti.mapper.PickIngMapper;
import com.jeeplus.modules.sg.picking.activiti.mapper.ShowListMapper;
import com.jeeplus.modules.sg.raiseCapital.entity.RaiseCapital;
import com.jeeplus.modules.sg.raiseCapital.mapper.RaiseCapitalMapper;
import com.jeeplus.modules.sg.raiseCapital.utils.RaiseExportUtil;
import com.jeeplus.modules.sg.raiseCapital.utils.RaiseTemplate;
import com.jeeplus.modules.sys.entity.DictValue;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.test.one.dialog.mapper.Leave1Mapper;
import net.oschina.j2cache.CacheChannel;
import net.oschina.j2cache.J2Cache;
import net.oschina.j2cache.redis.RedisCacheProvider;
import net.oschina.j2cache.redis.RedisClient;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.method.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 提资模块Service
 */
@Service
@Transactional(readOnly = true)
public class RaiseCapitalService extends CrudService<RaiseCapitalMapper, RaiseCapital> {
	@Autowired
	private HttpServletRequest request;

	@Autowired
	private PickIngMapper pickIngMapper;

	@Autowired
	private ShowListMapper showListMapper;

	public RaiseCapital get(String id) {
		return super.get(id);
	}
	
	public List<RaiseCapital> findList(RaiseCapital raiseCapital) {
		return super.findList(raiseCapital);
	}
	
	public Page<RaiseCapital> findPage(Page<RaiseCapital> page, RaiseCapital raiseCapital) {
		return super.findPage(page, raiseCapital);
	}
	
	@Transactional(readOnly = false)
	public void save(RaiseCapital raiseCapital) {
		super.save(raiseCapital);
	}
	
	@Transactional(readOnly = false)
	public void delete(RaiseCapital raiseCapital) {
		super.delete(raiseCapital);
	}

	/**
	 * 导出自动决算书
	 * @param request
	 * @param response
	 */
	@Transactional(readOnly = false)
	public void getExport(String projectName,HttpServletRequest request, HttpServletResponse response){
		String id = UserUtils.getUser().getId();
		CacheChannel channel = J2Cache.getChannel();
		RedisClient client = ((RedisCacheProvider)channel.getL2Provider()).getRedisClient();
		HashMap<String, Object> newMap = (HashMap<String,Object>) SerializeUtil.deserialize(client.get().get(id.getBytes()));
		//模块表的数量
		List<ShowList> myList = (List<ShowList>)newMap.get("myList");
		//模块表
		List<PickList> newList = newAllList();
		ShowList showList = new ShowList();
		showList.setProjectName(projectName);
		//领料清单-从数据库
		List<ShowList> materialsList = showListMapper.findRaiseList(showList);


		RaiseCapital newRaise = (RaiseCapital) newMap.get("raiseCapital");

		RaiseTemplate raiseTemplate = new RaiseTemplate();
		File newFile = raiseTemplate.createNewFile();
		InputStream inputStream = null;
		XSSFWorkbook workbook = null;
		XSSFFont font=null;
		//模块表
		XSSFSheet sheetModular = null;
		//领料清单
		XSSFSheet sheetPickingList = null;
		try {
			inputStream = new FileInputStream(newFile);// 将excel文件转为输入流
			workbook = new XSSFWorkbook(inputStream);// 创建个workbook，
			font = workbook.createFont();
			sheetModular =workbook.getSheetAt(0);//模块表
			/*sheetModuleList = workbook.getSheetAt(1);//模块清单*/
			sheetPickingList = workbook.getSheetAt(1);//领料清单
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		try {
			// 写数据
			FileOutputStream fos = new FileOutputStream(newFile);
			RaiseExportUtil.getSheetModular(sheetModular,myList,newList,newRaise,workbook);//模块表
			/*RaiseExportUtil.getSheetModuleList(sheetModuleList,moduleList,workbook);//模块清单*/
			RaiseExportUtil.getSheetPickingList(sheetPickingList,materialsList,newRaise,workbook);//领料清单
            showListMapper.trunCate(projectName);
			workbook.write(fos);
			fos.flush();
			fos.close();
			InputStream fis = new BufferedInputStream(new FileInputStream(
					newFile));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			response.reset();
			response.setContentType("text/html;charset=UTF-8");
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/x-msdownload");
			String newName = URLEncoder.encode(projectName + "物料清册" + System.currentTimeMillis() + ".xlsx", "UTF-8");
			response.addHeader("Content-Disposition","attachment;filename=\"" + newName + "\"");
			response.addHeader("Content-Length", "" + newFile.length());
			toClient.write(buffer);
			toClient.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != inputStream) {
					inputStream.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * 遍历查询结构 大类 中类 小类
	 * 去除重复，记录大类
	 * 根据大类查询它的中类放入list并记录
	 */
	public List<PickList> newAllList() {
		PickIng entity = new PickIng();
		entity.setVersion(MyActiviUtils.findDic().getValue());
		//查询除所有数据
		List<PickIng> allList = pickIngMapper.findAllList(entity);
		//创建返回对象集合
		List<PickList> returnList = new ArrayList<>();

		//循环得到所有大类
		for (PickIng pickIng : allList) {
			boolean flag = false;
			for (PickList list : returnList) {
				if (pickIng.getMdBigClass().equals(list.getName())) {
					flag = true;
					break;
				}
			}
			if (flag == false) {
				//创建返回对象
				PickList pickList = new PickList();
				pickList.setName(pickIng.getMdBigClass());
				returnList.add(pickList);
			}
		}

		//循环所有的大类，与查出的数据做比对，相同的就放入同一个实体类
		for (PickList pList : returnList) {
			List<MdTheClass> mdTheClassList = new ArrayList<>();
			//获得大类
			String name = pList.getName();
			//遍历查询的所有数据，与大类做比对，相同的，将中类记录下来
			for (PickIng pickIng : allList) {
				boolean flag = false;
				//如果查出的数据中和记录下的大类一致，将中类放入大类的
				if (pickIng.getMdBigClass().equals(name)) {
					for (MdTheClass md : mdTheClassList) {
						if (md.getName().equals(pickIng.getMdTheClass())) {
							flag = true;
						}
					}
					if (flag == false) {
						//创建中类对象，包含种类名称及对应的小类集合
						MdTheClass mdTheClass = new MdTheClass();
						mdTheClass.setId(pickIng.getId());
						mdTheClass.setName(pickIng.getMdTheClass());
						mdTheClassList.add(mdTheClass);
					}
				}
			}
			pList.setMdTheClassList(mdTheClassList);
		}

		for (PickList pList : returnList) {
			List<MdTheClass> mdTheClassList = pList.getMdTheClassList();
			for (MdTheClass md : mdTheClassList) {
				//创建
				List<MdSmallClass> mdSmallClassList = new ArrayList<>();
				for (PickIng pc : allList) {
					if (md.getName().equals(pc.getMdTheClass()) && pList.getName().equals(pc.getMdBigClass())) {
						//创建小类对象
						MdSmallClass mdSmallClass = new MdSmallClass();
						mdSmallClass.setName(pc.getMdSmallClass());
						mdSmallClass.setId(pc.getId());
						mdSmallClass.setMdUnit(pc.getMdUnit());
						if (Global.SYS_TYPE.equals("2")) {
							if (pc.getMdImg() != null && !"".equals(pc.getMdImg())) {
								mdSmallClass.setMdImg("http://" + request.getServerName() + pc.getMdImg());
							}
						} else {
							mdSmallClass.setMdImg(pc.getMdImg());
						}
						mdSmallClassList.add(mdSmallClass);
					}
					md.setMdSmallClassList(mdSmallClassList);
				}
			}
		}
		return returnList;
	}

}