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

import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.sg.financial.erpcredit.entity.ErpCredit;
import com.jeeplus.modules.sg.financial.erpcredit.entity.ErpCreditMaterial;
import com.jeeplus.modules.sg.financial.settlement.entity.MaintainData;
import com.jeeplus.modules.sg.financial.settlement.entity.ProjectBudget;
import com.jeeplus.modules.sg.financial.settlement.mapper.DataMaintenanceMapper;
import com.jeeplus.modules.sg.financial.settlement.mapper.ProjectBudgetMapper;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;


@Service
@Transactional(readOnly = true)
public class ProjectBudgetService extends CrudService<ProjectBudgetMapper, ProjectBudget> {

	@Autowired
	private ProjectBudgetMapper projectBudgetMapper;

	public static Map<String, CellStyle> styles;

	@Override
	public ProjectBudget get(String id) {
		return super.get(id);
	}
	
	@Override
	public List<ProjectBudget> findList(ProjectBudget projectBudget) {
		return super.findList(projectBudget);
	}

	/**
	 * 查询概预算分页数据，这里实际调用mapper的findList方法
	 * projectId查询，projectIds精准匹配
	 * @param page 分页对象
	 * @param projectBudget
	 * @return
	 */
	@Override
	public Page<ProjectBudget> findPage(Page<ProjectBudget> page, ProjectBudget projectBudget) {
		return super.findPage(page, projectBudget);
	}

	public Page<ProjectBudget> findFinancePage(Page<ProjectBudget> page,ProjectBudget projectBudget) {
		dataRuleFilter(projectBudget);
		projectBudget.setPage(page);
		page.setList(projectBudgetMapper.findFinancialInspection(projectBudget));
		return page;
	}

	@Transactional(readOnly = false)
	public void update(ProjectBudget projectBudget) {
		projectBudgetMapper.update(projectBudget);
	}

	@Override
	@Transactional(readOnly = false)
	public void save(ProjectBudget projectBudget) {
		super.save(projectBudget);
	}

	/**
	 * 保存财务项目概预算信息情况
	 * */
	@Transactional(readOnly = false)
	public String saveList(List<ProjectBudget> list) {
		String str = "";
		List<ProjectBudget> insertList = new ArrayList<>();
		List<ProjectBudget> updateList = new ArrayList<>();
		//查询出所有现在存在的项目概预算信息，判断项目编号是否存在，存在的更新，不存在的插入
		List<ProjectBudget> allList = projectBudgetMapper.findAllProjectId();
		if (allList.size() > 0) {
			for(ProjectBudget b : list){
				for (ProjectBudget a : allList) {
					if (a.getProjectId().equals(b.getProjectId())) {
						b.preInsert();
						updateList.add(b);
					}
				}
			}
			//获得需要更新的项目信息，其它项目信息则插入
			Iterator<ProjectBudget> iterator = list.iterator();
			while (iterator.hasNext()) {
				ProjectBudget next = iterator.next();
				for (ProjectBudget u :
						updateList) {
					if (next.getProjectId().equals(u.getProjectId())) {
						iterator.remove();
					}
				}
			}
			if (list.size() > 0) {
				for (ProjectBudget a :
						list) {
					insertList.add(a);
				}
			}
			if (insertList.size() > 0) {
				for (ProjectBudget p :
						insertList) {
					p.preInsert();
				}
			}
		}else {
			for(ProjectBudget b : list){
				b.preInsert();
				insertList.add(b);
			}
		}
		//插入
		if (insertList.size() > 0) {
			projectBudgetMapper.insertList(insertList);
			str += "概预算信息插入" + insertList.size() + "条-";
		}
		//更新
		if (updateList.size() > 0) {
			projectBudgetMapper.updateList(updateList);
			str += "概预算信息更新" + updateList.size() + "条-";
		}
		return str;
	}

	@Override
	@Transactional(readOnly = false)
	public void delete(ProjectBudget projectBudget) {
		super.delete(projectBudget);
	}

	public void exportHeard( HttpServletResponse response){
		InputStream inputStream = null;
		XSSFWorkbook workbook = null;
		try {
			String path = (getSispPath() + "excelmodel/maintainDataImport.xlsx");
//			String path = "D:/IDEA workspace/sg_audit/target/classes/freemarker/excelmodel/maintainDataImport.xlsx";
			File file = new File(path);
			inputStream = new FileInputStream(file);// 将excel文件转为输入流
			workbook = new XSSFWorkbook(inputStream);// 创建个workbook，
			String str = URLEncoder.encode("概预算基本信息导入模板.xlsx", "UTF8");
			OutputStream outputStream = response.getOutputStream();
			response.reset();
			response.setHeader("Content-Disposition", "attachment;filename="+str);
			response.setContentType("application/vnd.ms-excel;charset=UTF-8");
			workbook.write(outputStream);
			outputStream.flush();
			outputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
	}


	public  String getSispPath() {
		String sispPath = this.getClass().getResource("/").getPath()+ "freemarker/";
		return sispPath;
	}


/*	private  void convertDataToRow(ProjectBudget projectBudget, Row row){
		int cellNum = 0;
		Cell cell;
		cell = row.createCell(cellNum++);
		cell.setCellStyle(styles.get("data"));
		if (null != maintainData.getProjectId()) {
			cell.setCellValue(maintainData.getProjectId());
		} else {
			cell.setCellValue("");
		}
		cell = row.createCell(cellNum++);
		cell.setCellStyle(styles.get("data"));
		if (null != maintainData.getDesignUnits()) {
			cell.setCellValue(maintainData.getDesignUnits());
		} else {
			cell.setCellValue("");
		}
		cell = row.createCell(cellNum++);
		cell.setCellStyle(styles.get("data"));
		if (null != maintainData.getConstructionUnits()) {
			cell.setCellValue(maintainData.getConstructionUnits());
		} else {
			cell.setCellValue("");
		}
		cell = row.createCell(cellNum++);
		cell.setCellStyle(styles.get("data"));
		if (null != maintainData.getAddress()) {
			cell.setCellValue(maintainData.getAddress());
		} else {
			cell.setCellValue("");
		}
		cell = row.createCell(cellNum++);
		cell.setCellStyle(styles.get("data"));
		if (null != maintainData.getProperty()) {
			cell.setCellValue(maintainData.getProperty());
		} else {
			cell.setCellValue("");
		}
		cell = row.createCell(cellNum++);
		cell.setCellStyle(styles.get("data"));
		if (null != maintainData.getInvestment()) {
			cell.setCellValue(maintainData.getInvestment());
		} else {
			cell.setCellValue("");
		}
		cell = row.createCell(cellNum++);
		cell.setCellStyle(styles.get("data"));
		if (null != maintainData.getStartDate()) {
			cell.setCellValue(DateUtils.formatDate(maintainData.getStartDate()));

		} else {
			cell.setCellValue("");
		}
		cell = row.createCell(cellNum++);
		cell.setCellStyle(styles.get("data"));
		if (null != maintainData.getEndDate()) {
			cell.setCellValue(DateUtils.formatDate(maintainData.getEndDate()));
		} else {
			cell.setCellValue("");
		}
		cell = row.createCell(cellNum++);
		cell.setCellStyle(styles.get("data"));
		if (null != maintainData.getApprovalNumber()) {
			cell.setCellValue(maintainData.getApprovalNumber());
		} else {
			cell.setCellValue("");
		}
		cell = row.createCell(cellNum++);
		cell.setCellStyle(styles.get("data"));
		if (null != maintainData.getBuildingFee()) {
			cell.setCellValue(maintainData.getBuildingFee());
		} else {
			cell.setCellValue("");
		}
		cell = row.createCell(cellNum++);
		cell.setCellStyle(styles.get("data"));
		if (null != maintainData.getInstallFee()) {
			cell.setCellValue(maintainData.getInstallFee());
		} else {
			cell.setCellValue("");
		}

		cell = row.createCell(cellNum++);
		cell.setCellStyle(styles.get("data"));
		if (null != maintainData.getEquipmentFee()) {
			cell.setCellValue(maintainData.getEquipmentFee());
		} else {
			cell.setCellValue("");
		}
		cell = row.createCell(cellNum++);
		cell.setCellStyle(styles.get("data"));
		if (null != maintainData.getMaterialFee()) {
			cell.setCellValue(maintainData.getMaterialFee());
		} else {
			cell.setCellValue("");
		}
		cell = row.createCell(cellNum++);
		cell.setCellStyle(styles.get("data"));
		if (null != maintainData.getDesignFee()) {
			cell.setCellValue(maintainData.getDesignFee());
		} else {
			cell.setCellValue("");
		}
		cell = row.createCell(cellNum++);
		cell.setCellStyle(styles.get("data"));
		if (null != maintainData.getSupervisionFee()) {
			cell.setCellValue(maintainData.getSupervisionFee());
		} else {
			cell.setCellValue("");
		}
		cell = row.createCell(cellNum++);
		cell.setCellStyle(styles.get("data"));
		if (null != maintainData.getPreliminaryWorkFee()) {
			cell.setCellValue(maintainData.getPreliminaryWorkFee());
		} else {
			cell.setCellValue("");
		}
		cell = row.createCell(cellNum++);
		cell.setCellStyle(styles.get("data"));
		if (null != maintainData.getDamages()) {
			cell.setCellValue(maintainData.getDamages());
		} else {
			cell.setCellValue("");
		}
		cell = row.createCell(cellNum++);
		cell.setCellStyle(styles.get("data"));
		if (null != maintainData.getManagementFee()) {
			cell.setCellValue(maintainData.getManagementFee());
		} else {
			cell.setCellValue("");
		}
		cell = row.createCell(cellNum++);
		cell.setCellStyle(styles.get("data"));
		cell.setCellValue(maintainData.getDesignFee()+maintainData.getSupervisionFee()+maintainData.getPreliminaryWorkFee()
				+maintainData.getDamages()+maintainData.getManagementFee());

		cell = row.createCell(cellNum++);
		cell.setCellStyle(styles.get("data"));
		cell.setCellValue(maintainData.getDesignFee()+maintainData.getSupervisionFee()+maintainData.getPreliminaryWorkFee()
				+maintainData.getDamages()+maintainData.getManagementFee()+maintainData.getBuildingFee()+maintainData.getInstallFee()
				+maintainData.getEquipmentFee()+maintainData.getMaterialFee());

	}*/

	private  Map<String, CellStyle> createStyles(Workbook wb) {
		Map<String, CellStyle> styles = new HashMap<String, CellStyle>();

		CellStyle style = wb.createCellStyle();
		style.setAlignment(CellStyle.ALIGN_CENTER);
		style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		Font titleFont = wb.createFont();
		titleFont.setFontName("Arial");
		titleFont.setFontHeightInPoints((short) 16);
		titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
		style.setFont(titleFont);
		styles.put("title", style);

		style = wb.createCellStyle();
		style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		style.setBorderRight(CellStyle.BORDER_THIN);
		style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
		style.setBorderLeft(CellStyle.BORDER_THIN);
		style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
		style.setBorderTop(CellStyle.BORDER_THIN);
		style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
		style.setBorderBottom(CellStyle.BORDER_THIN);
		style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
		Font dataFont = wb.createFont();
		dataFont.setFontName("Arial");
		dataFont.setFontHeightInPoints((short) 10);
		style.setFont(dataFont);
		styles.put("data", style);

		style = wb.createCellStyle();
		style.cloneStyleFrom(styles.get("data"));
		style.setAlignment(CellStyle.ALIGN_LEFT);
		styles.put("data1", style);

		style = wb.createCellStyle();
		style.cloneStyleFrom(styles.get("data"));
		style.setAlignment(CellStyle.ALIGN_CENTER);
		styles.put("data2", style);

		style = wb.createCellStyle();
		style.cloneStyleFrom(styles.get("data"));
		style.setAlignment(CellStyle.ALIGN_RIGHT);
		styles.put("data3", style);

		style = wb.createCellStyle();
		style.cloneStyleFrom(styles.get("data"));
//		style.setWrapText(true);
		style.setAlignment(CellStyle.ALIGN_CENTER);
		style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
		style.setFillPattern(CellStyle.SOLID_FOREGROUND);
		Font headerFont = wb.createFont();
		headerFont.setFontName("Arial");
		headerFont.setFontHeightInPoints((short) 10);
		headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
		headerFont.setColor(IndexedColors.BLACK.getIndex());
		style.setFont(headerFont);
		style.setFillForegroundColor(HSSFColor.WHITE.index);
		styles.put("header", style);

		return styles;
	}

	public List<ProjectBudget> findFinancialInspection(ProjectBudget projectBudget) {
		return projectBudgetMapper.findFinancialInspection(projectBudget);
	}


	/**
	 * 修改项目检查状态
	 */
	@Transactional(readOnly = false)
	public void updateCheck(String projectId, String check, String number) {
		projectBudgetMapper.updateCheck(projectId, check, number);
	}
}