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

@Service
public class FinanceDifferenceService {

	@Autowired
	private FinanceDifferenceMapper differenceMapper;

	public List<FinanceDifference> get(FinanceDifference difference) {
		return differenceMapper.get(difference);
	}

	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<FinanceDifference> list = new ArrayList<FinanceDifference>(1000);
		try {
			in = file.getInputStream();
			listob = new ExcelUtils().getBankListByExcel(in, file.getOriginalFilename());
		} catch (IOException e) {
			e.printStackTrace();
		}
		String openOrderNumber = "";
		String filename = file.getOriginalFilename();
		System.out.println(filename);
		for (int i = 0; i < listob.size(); i++) {
			synchronized (this) {
				FinanceDifference vo = new FinanceDifference();
				List<Object> lo = listob.get(i);
				if (lo.size() == 0 || lo.size() == 1 || lo.get(4) == "") {
					System.out.println("++++++++++++++");
					continue;
				}
				String orderNumber = String.valueOf(lo.get(0)).trim();
				String shopname = String.valueOf(lo.get(1)).trim();
				String wangwang = String.valueOf(lo.get(2)).trim();
				String payTime = String.valueOf(lo.get(3)).trim();
				String price = String.valueOf(lo.get(4)).trim();
				String remark = String.valueOf(lo.get(5)).trim();
				String taobaoStatus = String.valueOf(lo.get(6)).trim();
				SimpleDateFormat formatter = null;
				if (payTime.contains("-")) {
					formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				} else if (payTime.contains("/")) {
					formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
				}
				Date pay_time = formatter.parse(payTime);// 把字符串转为日期格式
				vo.setOrderNumber(orderNumber);
				vo.setShopname(shopname);
				vo.setWangwang(wangwang);
				vo.setPayTime(pay_time);
				vo.setPrice(price);
				vo.setRemark(remark);
				vo.setTaobaoStatus(taobaoStatus);
				try {
					openOrderNumber = cutOrderNumber(remark);
				} catch (Exception e) {
					System.out.println(remark);
				}
				// openOrderNumber = remark.replaceAll("[^(0-9)]", "");
				vo.setOpenOrderNumber(openOrderNumber);
				vo.setFilename(filename);
				vo.setCreator(user.getRealname());
				list.add(vo);
			}
		}
		if (list.size() > 0) {
			differenceMapper.insertForeach(list);
		}
		in.close();
		return Msg.success();
	}

	private String cutOrderNumber(String remark) {
		// 获取字符串中的数字
		// 这个15是指连续数字的最少个数
		Pattern p = Pattern.compile("\\d{15,}");
		Matcher m = p.matcher(remark);
		String openOrder = "";
		while (m.find()) {
			openOrder = m.group();
		}
		if (remark.contains("S_")) {
			if (remark.contains("C")) {
				return "S_C1_" + openOrder;
			} else {
				return "S_" + openOrder;
			}
		}
		return openOrder;
	}

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

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

		// 创建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("导入日期");
		// 遍历将数据放到excel列中
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		for (FinanceDifference differences : differencesList) {
			filename = difference.getFilename();
			HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
			dataRow.createCell(0).setCellValue(differences.getOrderNumber());
			dataRow.createCell(1).setCellValue(differences.getShopname());
			dataRow.createCell(3).setCellValue("");
			if (differences.getPayTime() != null) {
				dataRow.createCell(3).setCellValue(formatter.format(differences.getPayTime()));
			}
			dataRow.createCell(2).setCellValue(differences.getWangwang());
			dataRow.createCell(4).setCellValue(differences.getPrice());
			dataRow.createCell(5).setCellValue(differences.getRemark());
			dataRow.createCell(6).setCellValue(differences.getTaobaoStatus());
			dataRow.createCell(7).setCellValue(differences.getOpenOrderNumber());
			dataRow.createCell(8).setCellValue(differences.getCreator());
			dataRow.createCell(9).setCellValue(formatter.format(differences.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();
	}

}
