JdlServiceImpl.java 7.97 KB
package com.bsth.service.oil.impl;

import java.io.File;
import java.io.FileInputStream;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.bsth.entity.report.Ticket;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.bsth.entity.oil.Jdl;
import com.bsth.repository.oil.JdlRepository;
import com.bsth.service.impl.BaseServiceImpl;
import com.bsth.service.oil.JdlService;
import com.bsth.util.ReportUtils;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

@Service
public class JdlServiceImpl extends BaseServiceImpl<Jdl, Integer> implements JdlService {
	
	@Autowired
	JdlRepository repository;

	@Autowired
	JdbcTemplate jdbcTemplate;

	@Autowired
	private TransactionTemplate transactionTemplate;

	@Override
	public String importExcel(File file, String gsbm, String gsName, String fgsbm, String fgsName) {
		gsbm="99";
		gsName="青浦公交";
		fgsbm="100";
		fgsName="青浦公交";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		DecimalFormat df = new DecimalFormat("######0.00");
		List<String> textList = new ArrayList<String>();
		try {
			POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
			HSSFWorkbook wb = new HSSFWorkbook(fs);
			HSSFSheet sheet = wb.getSheetAt(0);
			String n=sheet.getSheetName();
			String y=n.split("年")[0];
			if(n.split("年").length<2){
				return "报表日期读取失败";
			}
			String m=n.split("年")[1].split("月")[0];
			if(y.length()==2){
				y="20"+y;
			}
			if(m.length()==1){
				m="0"+m;
			}
			System.out.println(y+"-"+m);
			// 取得总行数
			int rowNum = sheet.getLastRowNum() + 1;
			// 取得总列数
			int cellNum = sheet.getRow(0).getLastCellNum();
			HSSFRow row = null;
			HSSFCell cell = null;
			for(int i = 2; i < rowNum; i++){
				row = sheet.getRow(i);
				if (row == null){
					continue;
				}
				String text = "";
				for(int j = 0; j < cellNum; j++){
					cell = row.getCell(j);
					if(cell == null){
						text += ",";
						continue;
					}
					if(cell.getCellType()==2){//处理公式类数据
						try {
							text +=(cell.getNumericCellValue()+ ",");
						} catch (IllegalStateException e) {
							text +=(cell.getRichStringCellValue()+ ",");
						}
					}else {
						text += String.valueOf(cell) + ",";
					}
				}
				String[] split = (text+";").split(",");
				String str = "";
				for(int j = 0; j < split.length && j < 5; j++){
					str += split[j];
				}
				if(str.trim().length() == 0)
					continue;
				textList.add(text + ";");
			}
			String rq = y+"-"+m+"-"+"01";//日期
			List<Jdl> jdlList=new ArrayList<>();
			for(int i = 0; i < textList.size(); i++){
				String text = textList.get(i);
				String[] split = text.split(",");
				String plate = split[2].trim();//车牌号
				if ("合计".equals(plate)){
					break;
				}
				String nbbm = split[3].trim();//内部编号
				if ("".equals(nbbm)){
					continue;
				}
				double jdl = Double.valueOf(split[4].trim().length()!=0?split[4]:"0");//加注量

				String jsy= "";//驾驶员工号
				String jdz = "";//能源站
				String remarks = "";//备注
				Jdl j=new Jdl();
				j.setGsBm(gsbm);
				j.setGsName(gsName);
				j.setFgsBm(fgsbm);
				j.setFgsName(fgsName);
				j.setNbbm(nbbm);
				j.setJdl(jdl);
				j.setJdz(jdz);
				j.setRemarks(remarks);
				j.setCreaterDate(new Date());
				j.setJsy(jsy);
				j.setPlate(plate);
				jdlList.add(j);
			}
			transactionTemplate.execute(new TransactionCallbackWithoutResult() {
				@Override
				public void doInTransactionWithoutResult(TransactionStatus status) {
					//删除
					jdbcTemplate.update("delete from bsth_c_jdl where rq =+rq");
					//重新写入
							jdbcTemplate.batchUpdate("insert into bsth_c_jdl(gs_bm,gs_name,fgs_bm,fgs_name,rq,nbbm,jdl,jdz,remarks,jsy,plate)" +
									" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", new BatchPreparedStatementSetter() {
								@Override
								public void setValues(PreparedStatement ps, int i) throws SQLException {
									Jdl jdl = jdlList.get(i);
									ps.setString(1, jdl.getGsBm());
									ps.setString(2, jdl.getGsName());
									ps.setString(3, jdl.getFgsBm());
									ps.setString(4, jdl.getFgsName());
									ps.setString(5, rq);
									ps.setString(6, jdl.getNbbm());
									ps.setString(7, df.format(jdl.getJdl()));
									ps.setString(8, jdl.getJdz());
									ps.setString(9, jdl.getRemarks());
									ps.setString(10, jdl.getJsy());
									ps.setString(11, jdl.getPlate());
								}
								@Override
								public int getBatchSize() {
									return jdlList.size();
								}
							});
				}
			});
			wb.close();
			fs.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "文件导入失败";
		} finally {
			file.delete();
		}
		return "文件导入成功";
	}

	@Override
	public Map<String, Object> query(Map<String, Object> map) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		Integer page = Integer.valueOf(map.containsKey("page")?map.get("page").toString():"0");
		StringBuffer sql=new StringBuffer("SELECT * FROM bsth_c_jdl where 1=1 ");
		if(map.get("rq")!=null && !"".equals(map.get("rq").toString())){
			sql.append("and rq>='"+map.get("rq")+"'");
		}
		if(map.get("nbbm")!=null && !"".equals(map.get("nbbm").toString())){
			sql.append("and nbbm='"+map.get("nbbm")+"'");
		}
		List<Jdl> query = jdbcTemplate.query(sql.toString(), BeanPropertyRowMapper.newInstance(Jdl.class));
		
		if(!map.containsKey("type")){
			
			int end = (page+1)*10>query.size()?query.size():(page+1)*10;
			modelMap.put("dataList", query.subList(page*10, end));
			modelMap.put("totalPages", query.size()%10>0?query.size()/10+1:query.size()/10);
			
		} else if(map.get("type").toString().equals("export")){
			SimpleDateFormat sdfMonth = new SimpleDateFormat("yyyy-MM-dd"),
					sdfSimple = new SimpleDateFormat("yyyyMMdd");
			
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			for(Jdl jdl : query){
				Map<String, Object> m = new HashMap<String, Object>();
				m.put("rq", sdfMonth.format(jdl.getRq()));
				m.put("nbbm", jdl.getNbbm());
				m.put("jdl", jdl.getJdl());
				m.put("jdz", jdl.getJdz());
				m.put("plate", jdl.getPlate());
				m.put("remarks", jdl.getRemarks());
				list.add(m);
			}
			
		/*	List<Iterator<?>> listI = new ArrayList<Iterator<?>>();
			Map<String, Object> m = new HashMap<String, Object>();
			ReportUtils ee = new ReportUtils();
			try {
				listI.add(list.iterator());
				String path = this.getClass().getResource("/").getPath()+"static/pages/forms/";
				ee.excelReplace(listI, new Object[] { m }, path+"mould/export_Jdl.xls",
						path+"export/车辆充电量" + sdfSimple.format(sdfMonth.parse(rq)) + ".xls");
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}*/
		}
		return modelMap;
	}

}