package lingtao.net.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import lingtao.net.bean.Finance;
import lingtao.net.bean.Msg;
import lingtao.net.bean.SysUser;
import lingtao.net.dao.Finance3Mapper;
import lingtao.net.util.ExcelUtils;

@Service
public class Finance5Service {

	@Autowired
	private Finance3Mapper finance3Mapper;

	public List<Finance> getFinance(Finance finance) {
		return finance3Mapper.getFinance5(finance);
	}

	public List<String> getAllFilename(String creator) {
		return finance3Mapper.getAllFilename5(creator);
	}

	public Msg deleteDataByFilename(String filename, String realname) {
		try {
			finance3Mapper.deleteDataByFilename5(filename, realname);
			return Msg.success();
		} catch (Exception e) {
			return Msg.fail();
		}
	}

	public Msg ajaxUploadExcel(MultipartFile file) throws Exception {
		if (file.isEmpty()) {
			throw new Exception("文件不存在！");
		}
		SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
		InputStream in = null;
		List<List<Object>> listob = null;
		List<Finance> list = new ArrayList<Finance>(1000);
		try {
			in = file.getInputStream();
			listob = new ExcelUtils().getBankListByExcel(in, file.getOriginalFilename());
		} catch (IOException e) {
			e.printStackTrace();
		}
		String filename = file.getOriginalFilename();
		System.out.println(filename);
		for (int i = 0; i < listob.size(); i++) {
			synchronized (this) {
				Finance vo = new Finance();
				List<Object> lo = listob.get(i);
				if (lo.size() == 0 || lo.size() == 1 || lo.get(6) == "") {
					System.out.println("++++++++++++++");
					continue;
				}

				String addTime = String.valueOf(lo.get(0)).trim();
				if(addTime.equals("日期")) {
					continue;
				}
				String supplier = String.valueOf(lo.get(1)).trim();
				String shopname = String.valueOf(lo.get(2)).trim();
				String kind = String.valueOf(lo.get(3)).trim();
				String kind2 = String.valueOf(lo.get(4)).trim();
				String orderNumber = String.valueOf(lo.get(5)).trim();
				String remark = String.valueOf(lo.get(6)).trim();
				remark = remark.replace("MM", "mm").replace("CM", "cm");
				if (remark.indexOf("mm") == -1 && remark.indexOf("cm") == -1) {
					System.out.println(remark);
					System.out.println("=================");
				}

				// 数量
				String count = "#";
				// 拼版数
				String number = "#";
				// 所需张数
				double zhang = 0;
				String total = "";
				try {
					// 处理备注
					remark = remark.replace("，", ",");
					number = cutSize(remark);
					count = cutCount(remark);
					if(remark.indexOf(",") > 0) {
						String[] countList = count.split(",");
						String[] numberList = number.split(",");
						for(int j = 0;j < countList.length; j++) {
							if (countList[j].equals("#") || numberList[j].equals("#")) {
								zhang = 0;
							}else {
								zhang = Math.ceil(Double.valueOf(countList[j]) / Double.valueOf(numberList[j]));
							}
							total += ","+zhang;
						}
						total = total.substring(1);
					}else {
						if (count != "#" && number != "#") {
							if (count.contains("*")) {
								String[] countSplit = count.split("\\*");
								System.out.println(Double.valueOf(countSplit[0]));
								System.out.println(Double.valueOf(countSplit[1]));
								zhang = Math.ceil(Double.valueOf(countSplit[0]) * Double.valueOf(countSplit[1])
										/ Double.valueOf(number));
							} else {
								zhang = Math.ceil(Double.valueOf(count) / Double.valueOf(number));
							}
						}
						orderNumber = remark.substring(remark.indexOf("（") + 1, remark.indexOf("）"));
					}
				} catch (Exception e) {
					System.out.println(remark);
//					return Msg.fail(remark);
				}
				if (StringUtils.isNotEmpty(addTime)) {
					Date javaDate = HSSFDateUtil.getJavaDate(Double.parseDouble(addTime));
					vo.setAddTime(javaDate);
				}
//				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
//				Date add_date = formatter.parse(addTime);// 把字符串转为日期格式
				vo.setSupplier(supplier);
				vo.setShopname(shopname);
				vo.setKind(kind);
				vo.setKind2(kind2);
				vo.setOrderNumber(orderNumber);
				vo.setFilename(filename);
				vo.setCount(count);
				vo.setNumber(number);
				if(total.length() > 0) {
					vo.setZhang(total);
				}else {
					vo.setZhang(String.valueOf(zhang));
				}
				vo.setRemark(remark);
				vo.setCreator(user.getRealname());
				list.add(vo);
				// finance2Mapper.insertSelective(vo);
			}
		}
		if (list.size() == 0) {
			return Msg.fail("上传失败，请检查文件表头是否正确");
		} else if (list.size() > 0) {
			finance3Mapper.insertForeach5(list);
		}
		in.close();
		return Msg.success();

	}

	private String cutCount(String remark) {
		int number = 0, count = 0, index = 0;
		String totalCount = "";
		String counts = "";
		String[] countList = {};
		if(	remark.indexOf(",") > 0) {//合包的拼版计算
			String[] total = remark.split(",");
			for(int i = 0 ;i < total.length; i++) {
				String[] lists = total[i].split("-");
				for(int j = 0; j < lists.length; j++) {
					index = lists[j].indexOf("mm");
					if(index == -1) {
						index = lists[j].indexOf("cm");
					}
					
					if(index > 0) {
						counts = lists[j+1];
						break;
					}
				}
				
				if(counts.indexOf("各") > 0 && counts.indexOf("共") < 0) {
					countList = counts.split("款");
					number = Integer.valueOf(countList[0].replace("各", ""));
					count = Integer.valueOf(countList[1].substring(1, countList[1].length()-1));
					totalCount += "," + count * number;
				}else if(counts.indexOf("共") > 0){
					int coutIndex = counts.indexOf("共");
					String countValue = counts.substring(coutIndex, counts.length()-1);
					count = Integer.valueOf(countValue);
					totalCount += "," + count;
				}else {
					totalCount += "," + Integer.valueOf(counts.substring(0, counts.length()-1)) * 1;
				}
			}	
			totalCount = totalCount.substring(1);
			return  totalCount;
		}else {//单款尺寸
			String[] list = remark.split("-");
			for(int m = 0;m < list.length; m++) {
				index = list[m].indexOf("mm");
				if(index == -1) {
					index = list[m].indexOf("cm");
				}
				if(index > 0) {
					counts = list[m+1];
					break;
				}
			}

			if(counts.indexOf("各") > 0 && counts.indexOf("共") < 0 ) {
				countList = counts.split("款");
				countList[1].substring(0, countList[1].length()-1);
				number = Integer.valueOf(countList[0].replace("各", ""));
				count = Integer.valueOf(countList[1].substring(1, countList[1].length()-1));
				count = count * number;
			}else if(counts.indexOf("共") > 0){
				int coutIndex = counts.indexOf("共");
				String countValue = counts.substring(coutIndex+1, counts.length()-1);
				count = Integer.valueOf(countValue);
			}else {
				count = Integer.valueOf(counts.substring(0, counts.length()-1)) * 1;
			}
			
			return  String.valueOf(count);
		}
	}

	private String cutSize(String remark) {
		double length = 0,width = 0;
		int sizeIndex = 0;
		String totalSize = "";
		String size = "";
		String[] sizeList = {};
		double l = 440,w = 310;
		if(	remark.indexOf(",") > 0) {//合包的拼版计算
			String[] total = remark.split(",");
			for(int i = 0 ;i < total.length; i++) {
				String[] lists = total[i].split("-");
				for(int j = 0; j < lists.length; j++) {
					sizeIndex = lists[j].indexOf("mm");
					if(sizeIndex == 0) {
						sizeIndex = lists[j].indexOf("cm");
					}
					
					if(sizeIndex > 0) {
						size = lists[j].replace("mm", "");
						size = size.replace("cm", "");
						break;
					}	
				}
				
				if(size.indexOf("×") > 0 ) {
					sizeList = size.split("×");
				}else if(size.indexOf("x") > 0){
					sizeList = size.split("x");
				}
				
				length = Double.valueOf(sizeList[0]);
				width = Double.valueOf(sizeList[1]);
				
				//+3mm出血
				length += 6;
				width += 6;
				
				if (length == l + 6 ) {
					totalSize = String.valueOf(w/width);
					continue;
				}else if(width == w + 6) {
					totalSize = String.valueOf(l/length);
					continue;
				}else if ((length > l || width > w) && (length > w || width > l)) {
					totalSize = "#";
					continue;
				}
					
				// 一张纸 能做多少个此类尺寸的产品
				double max = Math.max(Math.floor(l / length) * Math.floor(w / width),
						Math.floor(l / width) * Math.floor(w / length));
				
				totalSize += "," + String.valueOf(max);
			}
			
			if(totalSize.indexOf("#") != 0) {
				totalSize = totalSize.substring(1);
			}
			
			return totalSize;
		}else {
			String[] list = remark.split("-");
			for(int m = 0;m < list.length; m++) {
				sizeIndex = list[m].indexOf("mm");
				if(sizeIndex == 0) {
					sizeIndex = list[m].indexOf("cm");
				}
				
				if(sizeIndex > 0) {
					size = list[m].replace("mm", "");
					size = size.replace("cm", "");
					break;
				}
			}
			
			if(size.indexOf("×") > 0 ) {
				sizeList = size.split("×");
			}else if(size.indexOf("x") > 0){
				sizeList = size.split("x");
			}
			
			length = Double.valueOf(sizeList[0]);
			width = Double.valueOf(sizeList[1]);
			//+3mm出血
			length += 6;
			width += 6;
			
			if (length == l + 6 ) {
				return String.valueOf(w/width);
			}else if(width == w + 6) {
				return String.valueOf(l/length);
			}else if ((length > l || width > w) && (length > w || width > l)) {
				return "#";
			}
			// 一张纸 能做多少个此类尺寸的产品
			double max = Math.max(Math.floor(l / length) * Math.floor(w / width),
					Math.floor(l / width) * Math.floor(w / length));
			return String.valueOf(max);
		}
	}

	@SuppressWarnings("resource")
	public void excel(HttpServletResponse response, Finance finance) throws Exception {
		response.setCharacterEncoding("UTF-8");
		List<Finance> financesList = new ArrayList<Finance>();
		SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
		finance.setCreator(user.getRealname());
		financesList = getFinance(finance);

		// 创建excel文件
		HSSFWorkbook wb = new HSSFWorkbook();
		// 创建sheet页
		HSSFSheet sheet = wb.createSheet("总表");
		String filename = "";
		// 创建标题行
		HSSFRow titleRow = sheet.createRow(0);
		titleRow.createCell(0).setCellValue("日期");
		titleRow.createCell(1).setCellValue("供应商");
		titleRow.createCell(2).setCellValue("店铺");
		titleRow.createCell(3).setCellValue("大类别");
		titleRow.createCell(4).setCellValue("小类别");
		titleRow.createCell(5).setCellValue("订单号");
		titleRow.createCell(6).setCellValue("文件名");
		titleRow.createCell(7).setCellValue("数量");
		titleRow.createCell(8).setCellValue("拼版数");
		titleRow.createCell(9).setCellValue("张数");
		titleRow.createCell(10).setCellValue("导入人");
		titleRow.createCell(11).setCellValue("导入日期");
		// 遍历将数据放到excel列中
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		for (Finance finances : financesList) {
			filename = finance.getFilename();
			HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
			dataRow.createCell(0).setCellValue("");
			if (finances.getAddTime() != null) {
				dataRow.createCell(0).setCellValue(formatter.format(finances.getAddTime()));
			}
			dataRow.createCell(1).setCellValue(finances.getSupplier());
			dataRow.createCell(2).setCellValue(finances.getShopname());
			dataRow.createCell(3).setCellValue(finances.getKind());
			dataRow.createCell(4).setCellValue(finances.getKind2());
			dataRow.createCell(5).setCellValue(finances.getOrderNumber());
			dataRow.createCell(6).setCellValue(finances.getRemark());
			dataRow.createCell(7).setCellValue(finances.getCount());
			dataRow.createCell(8).setCellValue(finances.getNumber());
			dataRow.createCell(9).setCellValue(finances.getZhang());
			dataRow.createCell(10).setCellValue(finances.getCreator());
			dataRow.createCell(11).setCellValue(formatter.format(finances.getCreateDate()));
		}

		// 设置下载时客户端Excel的名称
		response.setContentType("application/octet-stream;charset=utf-8");
		response.setHeader("Content-Disposition",
				"attachment;filename=" + new String(filename.getBytes(), "iso-8859-1"));// + ".xls"

		OutputStream ouputStream = response.getOutputStream();
		wb.write(ouputStream);
		ouputStream.flush();
		ouputStream.close();
	}

}
