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 java.util.regex.Matcher;
import java.util.regex.Pattern;

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.Finance2Mapper;
import lingtao.net.util.ExcelUtils;

@Service
public class Finance2Service {

	@Autowired
	private Finance2Mapper finance2Mapper;

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

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

	public Msg deleteDataByFilename(String filename, String realname) {
		try {
			finance2Mapper.deleteDataByFilename(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();
				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", "mm");
				if (remark.indexOf("mm") == -1 && remark.indexOf("cm") == -1) {
					System.out.println(remark);
					System.out.println("=================");
				}
				// 判断数据是否已经存在

				/*
				 * String checkAccountNumber = finance2Mapper.checkAccountNumber(orderNumber);
				 * if (StringUtils.isNotEmpty(checkAccountNumber)) { continue; }
				 */

				// 数量
				String count = "#";
				// 拼版数
				String number = "#";
				// 所需张数
				double zhang = 0;
				try {
					// 处理备注
					String cutSizeStr = remark;
					String cutCountStr = remark;
					number = cutSize(cutSizeStr);
					count = cutCount(cutCountStr);
					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);
				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) {
			finance2Mapper.insertForeach(list);
		}
		in.close();
		return Msg.success();

	}

	private String cutCount(String remark) {
		remark = remark.replaceAll(" ", "").replace("x", "X").replace("×", "X").replace("(", "（").replace(")", "）");
		String countStr = "";
		String numberStr = "";
		Integer number;
		Integer count;
		int indexM = remark.indexOf("m");
		int indexZhang = remark.indexOf("张");
		int indexGe = remark.indexOf("个");
		int indexTao = remark.indexOf("套");
		int indexMei = remark.indexOf("枚");
		if (remark.indexOf("张") != -1 && indexZhang - indexM < 15) {
			if (remark.indexOf("m-") == -1) {
				countStr = remark.substring(remark.indexOf("m") + 1, remark.indexOf("张"));
			} else {
				countStr = remark.substring(remark.indexOf("m-") + 2, remark.indexOf("张"));
			}
		} else if (remark.indexOf("个") != -1 && indexGe - indexM < 15) {
			if (remark.indexOf("m-") == -1) {
				countStr = remark.substring(remark.indexOf("m") + 1, remark.indexOf("个"));
			} else {
				countStr = remark.substring(remark.indexOf("m-") + 2, remark.indexOf("个"));
			}
		} else if (remark.indexOf("套") != -1 && indexTao - indexM < 15) {
			if (remark.indexOf("m-") == -1) {
				countStr = remark.substring(remark.indexOf("m") + 1, remark.indexOf("套"));
			} else {
				countStr = remark.substring(remark.indexOf("m-") + 2, remark.indexOf("套"));
			}
		} else if (remark.indexOf("枚") != -1 && indexMei - indexM < 15) {
			if (remark.indexOf("m-") == -1) {
				countStr = remark.substring(remark.indexOf("m") + 1, remark.indexOf("枚"));
			} else {
				countStr = remark.substring(remark.indexOf("m-") + 2, remark.indexOf("枚"));
			}
		}
		// 第一个“款”的位置
		int firstK = countStr.indexOf("款");
		// 第一个“各”的位置
		int firstGe = countStr.indexOf("各");
		// 第二个“款”的位置
		int countStrSecondK = countStr.indexOf("款", firstK + 1);
		// 第3个“款”的位置
		int countStrThirdK = countStr.indexOf("款", countStrSecondK + 1);
		if (countStrSecondK > 0 && countStrThirdK > 0) {
			return "#";
		}
		// “共***张”
		if (countStr.contains("共")) {
			String[] split = countStr.split("共");
			countStr = split[1].replaceAll("[^(0-9)]", "");
			return "" + countStr;
		}
		// “合计***张”
		if (countStr.contains("合计")) {
			String[] split = countStr.split("合计");
			countStr = split[1].replaceAll("[^(0-9)]", "");
			return "" + countStr;
		}
		// “总的***张”
		if (countStr.contains("总")) {
			String[] split = countStr.split("总");
			countStr = split[1].replaceAll("[^(0-9)]", "");
			return "" + countStr;
		}
		// “***款各***张”
		if (firstGe > 0) {
			String[] split = countStr.split("各");
			numberStr = split[0];
			countStr = split[1];
			numberStr = numberStr.replaceAll("[^(0-9)]", "");
			countStr = countStr.replaceAll("[^(0-9)]", "");
			if (StringUtils.isEmpty(numberStr)) {
				return "#";
			}
			number = Integer.valueOf(numberStr);
			count = Integer.valueOf(countStr);
			if (number == 1 || count == 1) {
				return "" + number * count;
			}
			return number + "*" + count;
		}
		// **款**张
		if (firstK > 0) {
			String[] split = countStr.split("款");
			numberStr = split[0];
			countStr = split[1];
			if (countStrSecondK > 0) {
				countStr = split[2];
			}
			numberStr = numberStr.replaceAll("[^(0-9)]", "");
			countStr = countStr.replaceAll("[^(0-9)]", "");
			if (StringUtils.isEmpty(numberStr)) {
				return "#";
			}
			number = Integer.valueOf(numberStr);
			count = Integer.valueOf(countStr);
			if (number == 1 || count == 1) {
				return "" + number * count;
			}
			return number + "*" + count;
		}
		countStr = countStr.replaceAll("[^(0-9)]", "");
		return countStr;
	}

	private String cutSize(String remark) {
		remark = remark.replaceAll(" ", "").replace("x", "X").replace("×", "X").replace("(", "（").replace(")", "）")
				.replace("专版打印", "").replace("下", "").replace("上", "").replace("专版", "").replace("-", "")
				.replace("多拍返10元", "");
		// 第一个X的位置
		int firstX = remark.indexOf("X");
		// 第二个X的位置
		int secondX = remark.indexOf("X", firstX + 1);
		int secondmm = remark.indexOf("mm", remark.indexOf("mm") + 1);
		if (secondX > 0 && secondmm > 0) {
			return "#";
		}
		// System.out.println(remark);
		String size = "";
		double length;
		double width;
		// 提取整数/小数的正则
		String regex = "([1-9]\\d*\\.?\\d+)|(0\\.\\d*[1-9])|(\\d+)";
		if (remark.indexOf("mm") == -1 && remark.indexOf("cm") != -1) {
			String l = remark.substring(remark.indexOf("X") - 3, remark.indexOf("X"));
			String w = remark.substring(remark.indexOf("X") + 1, remark.indexOf("cm"));
			// 如果l里有小数点，往前数5位
			if (l.indexOf(".") != -1) {
				Pattern pattern = Pattern.compile(regex);
				l = remark.substring(remark.indexOf("X") - 5, remark.indexOf("X"));
				Matcher matcher = pattern.matcher(l);
				while (matcher.find()) {
					l = matcher.group();
				}
			} else {
				l = l.replaceAll("[^(0-9)]", "");
			}
			size = l + "X" + w;
			String[] split = size.split("X");
			length = Double.valueOf(split[0]) * 10 + 4;
			if ("按比例".equals(split[1])) {
				width = Double.valueOf(split[0]) * 10 + 4;
			} else {
				width = Double.valueOf(split[1]) * 10 + 4;
			}
		} else {
			String l = remark.substring(remark.indexOf("X") - 3, remark.indexOf("X"));
			String w = remark.substring(remark.indexOf("X") + 1, remark.indexOf("mm"));
			// 如果l里有小数点，往前数5位
			if (l.indexOf(".") != -1) {
				if (l.indexOf(".") != -1) {
					l = remark.substring(remark.indexOf("X") - 5, remark.indexOf("X"));
					Pattern pattern = Pattern.compile(regex);
					Matcher matcher = pattern.matcher(l);
					while (matcher.find()) {
						l = matcher.group();
					}
				}
			} else {
				l = l.replaceAll("[^(0-9)]", "");
			}
			size = l + "X" + w;
			String[] split = size.split("X");
			length = Double.valueOf(split[0]) + 4;
			if ("按比例".equals(split[1])) {
				width = Double.valueOf(split[0]) + 4;
			} else {
				width = Double.valueOf(split[1]) + 4;
			}
		}

		double l = 390;
		double w = 272;
		if (length == l + 4) {
			return "1";
		}
		if ((length > l || width > w) && (length > w || width > l))
			return "#";
		// 一张纸 390*272 能做多少个此类尺寸的产品
		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();
	}

}
