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.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.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.FinanceExtract;
import lingtao.net.bean.Msg;
import lingtao.net.bean.SysUser;
import lingtao.net.dao.FinanceExtractMapper;
import lingtao.net.util.ExcelUtils;

@Service
public class FinanceExtractService {

	@Autowired
	private FinanceExtractMapper financeExtractMapper;

	public List<FinanceExtract> getFinanceExtract(FinanceExtract financeExtract) {
		return financeExtractMapper.getFinanceExtract(financeExtract);
	}

	public List<String> getFilename_extract(String creator) {
		return financeExtractMapper.getFilename_extract(creator);
	}

	public Msg deleteDataByFilename(String filename, String realname) {
		try {
			financeExtractMapper.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<FinanceExtract> list = new ArrayList<FinanceExtract>(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) {
				FinanceExtract vo = new FinanceExtract();
				List<Object> lo = listob.get(i);
				if (lo.size() == 0 || lo.get(1) == "") {
					System.out.println("++++++++++++++");
					continue;
				}
				String orderNumber = String.valueOf(lo.get(0)).trim();
				String remark = String.valueOf(lo.get(1)).trim();
				if (remark.indexOf("mm") == -1 && remark.indexOf("cm") == -1) {
					System.out.println(remark);
					System.out.println("=================");
				}
				// 尺寸
				String size = "#";
				// 长
				String length = "#";
				// 宽
				String width = "#";
				// 高
				String height = "#";
				// 数量
				String count = "#";
				try {
					// 处理备注
					String cutSizeStr = remark;
					String cutCountStr = remark;
					size = cutSize(cutSizeStr);
					if (size != "#" || !"#".equals(size)) {
						if (size.contains("+")) {
							String[] sizeSplit = size.split("\\+");
//							System.out.println(Double.valueOf(sizeSplit[0]));
//							System.out.println(Double.valueOf(sizeSplit[1]));
							length = sizeSplit[0];
							width = sizeSplit[1];
						}
					}
					count = cutCount(cutCountStr);
					orderNumber = remark.substring(remark.indexOf("（") + 1, remark.indexOf("）"));
				} catch (Exception e) {
					System.out.println(remark);
				}
				vo.setOrderNumber(orderNumber);
				vo.setFilename(filename);
				vo.setLength(length);
				vo.setWidth(width);
				vo.setHeight(height);
				vo.setCount(count);
				vo.setRemark(remark);
				vo.setCreator(user.getRealname());
				list.add(vo);
			}
		}
		if (list.size() == 0) {
			return Msg.fail("上传失败，请检查文件表头是否正确");
		} else if (list.size() > 0) {
			financeExtractMapper.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.contains(".pdf")) {
			String newRemarkYY = remark.substring(remark.indexOf("-切") + 2);
			countStr = newRemarkYY.substring(newRemarkYY.indexOf("-") + 1, newRemarkYY.indexOf("Z-"));
			return countStr;
		}
		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("多拍返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+)";
		// 没有mm && 有cm
		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;
			if ("按比例".equals(split[1])) {
				width = Double.valueOf(split[0]) * 10;
			} else {
				width = Double.valueOf(split[1]) * 10;
			}
			size = length + "+" + width;
		} else {
			// 印艺,没有毫米
			if (remark.contains(".pdf")) {
				String newRemarkYY = remark.substring(remark.indexOf("-切") + 2);
				System.out.println(newRemarkYY);
				size = newRemarkYY.substring(0, newRemarkYY.indexOf("-"));
			} 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) {
					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]);
			if ("按比例".equals(split[1])) {
				width = Double.valueOf(split[0]);
			} else {
				width = Double.valueOf(split[1]);
			}
			size = length + "+" + width;
		}
		return size;
	}

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

		// 创建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("导入日期");
		// 遍历将数据放到excel列中
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		for (FinanceExtract financeExtracts : financeExtractsList) {
			filename = financeExtract.getFilename();
			HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
			dataRow.createCell(0).setCellValue(financeExtracts.getOrderNumber());
			dataRow.createCell(1).setCellValue(financeExtracts.getRemark());
			dataRow.createCell(2).setCellValue(financeExtracts.getLength());
			dataRow.createCell(3).setCellValue(financeExtracts.getWidth());
			dataRow.createCell(4).setCellValue(financeExtracts.getHeight());
			dataRow.createCell(5).setCellValue(financeExtracts.getCount());
			dataRow.createCell(6).setCellValue(financeExtracts.getCreator());
			dataRow.createCell(7).setCellValue(formatter.format(financeExtracts.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();
	}

}
