/**
 * 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.common.utils.StringUtils;
import com.jeeplus.common.utils.time.DateUtil;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.sg.financial.settlement.entity.MaintainData;
import com.jeeplus.modules.sg.financial.settlement.mapper.DataMaintenanceMapper;
import com.jeeplus.modules.sg.financial.settlement.util.ExcelWriter;
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.*;
import java.net.URLEncoder;
import java.util.*;


@Service
@Transactional(readOnly = true)
public class DataMaintenanceService extends CrudService<DataMaintenanceMapper, MaintainData> {

	@Autowired
	private DataMaintenanceMapper dataMaintenanceMapper;

	public static Map<String, CellStyle> styles;

	public MaintainData get(String id) {
		return super.get(id);
	}
	
	public List<MaintainData> findList(MaintainData maintainData) {
		return super.findList(maintainData);
	}

	/**
	 * 查询概预算分页数据，这里实际调用mapper的findList方法
	 * 该方法有一个特点，projectId模糊匹配，projectIds精准匹配
	 * @param page 分页对象
	 * @param maintainData
	 * @return
	 */
	public Page<MaintainData> findPage(Page<MaintainData> page, MaintainData maintainData) {
		return super.findPage(page, maintainData);
	}
	
	@Transactional(readOnly = false)
	public void save(MaintainData maintainData) {
		super.save(maintainData);
	}

	@Transactional(readOnly = false)
	public void saveList(List<MaintainData> list) {
		for(MaintainData maintainData : list){
			maintainData.preInsert();
		}
		dataMaintenanceMapper.insertList(list);
	}
	
	@Transactional(readOnly = false)
	public void delete(MaintainData maintainData) {
		super.delete(maintainData);
	}

	@Transactional(readOnly = false)
    public void deleteData(String projectId){
        dataMaintenanceMapper.deleteData(projectId);
    }

    //判断erp是否存在
    public List<MaintainData> getJudge(){
		MaintainData maintainData1 = new MaintainData();
		List<MaintainData> maintainDatas = dataMaintenanceMapper.findList(maintainData1);//得到维护表所有数据
		return maintainDatas;
	}

	public void export(MaintainData maintainData , HttpServletResponse response){
		InputStream inputStream = null;
		XSSFWorkbook workbook = null;
		try {
			String path = (getSispPath() + "excelmodel/maintainDataExport.xlsx");
			List<MaintainData> dataList = dataMaintenanceMapper.findList(maintainData);
//			String path = "D:/IDEA workspace/sg_audit/target/classes/freemarker/excelmodel/maintainDataExport.xlsx";
			File file = new File(path);
			inputStream = new FileInputStream(file);// 将excel文件转为输入流
			workbook = new XSSFWorkbook(inputStream);// 创建个workbook
			styles = createStyles(workbook);  //创建样式
			int rowNum = 3;
			Sheet sheet = workbook.getSheetAt(0);
			for (Iterator<MaintainData> it = dataList.iterator(); it.hasNext(); ) {
				MaintainData data = it.next();
				if (data == null) {
					continue;
				}
				//输出行数据
				Row row = sheet.createRow(rowNum++);
				convertDataToRow(data, row);
			}
			String st = DateUtils.formatDate(new Date(),"yyyyMMddHHmmss");
			String str = URLEncoder.encode("概预算基本信息"+st+".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 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(MaintainData maintainData, 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;
	}
	
}