package com.sifang.modules.order.service.excel;

import com.google.common.collect.Maps;
import com.sifang.modules.order.utils.excelExt.handler.ExcelAbstractHandler;
import com.sifang.modules.sys.common.utils.DateUtils;
import org.apache.commons.lang.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;


public class OrderExcelImportHandler extends ExcelAbstractHandler {

	public static final String REGEX_MOBILE = "^((1[0-9]))\\d{9}$";
	public Date now = new Date();
	/**
	 * 如果返回false，则表示终止继续遍历Excel,截至到当前的行数
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Boolean handler(Map<String, Object> rowData, int rowIndex) {
		List<Object[]> executeSqlParams = getExecuteParams();
		if(StringUtils.isBlank(getExecuteSql())){
			String sql = generateSql();
			setExecuteSql(sql);//如果不存在SQL的话需要生成SQL 
			setSqlParamsCount(countSqlParamsNum(sql));
		}
//		Map<String, String> params = (Map<String, String>) getParams();
		//此处的map主要用来处理结束后进行数据库去重操作
		Map<String, Object[]> map = (Map<String, Object[]>) getHandlerResult();
		if(map == null || map.isEmpty()){
			map = Maps.newHashMap();
			setHandlerResult(map);
		}
	//	String customerNum = String.valueOf(rowData.get("4"));//手机号重复
		boolean isValid = checkRowData(rowData);
		if(isValid){//验证成功，可以插入数据库
			increaseSuccessCount(1);
			Object[] param = wrapSqlParams(rowData, getSqlParamsCount());
			executeSqlParams.add(param);
		}
		return true;
	}

	/**
	 * 如果返回false，则表示终止继续遍历Excel,截至到当前的行数
	 */
	//验证Excel模板
	@SuppressWarnings("unchecked")
	@Override
	public Boolean checkExcel(Map<String, Object> rowData, int rowIndex) {
		Map<String, Object> result = (Map<String, Object>) this.getHandlerResult();
		if(result == null){
			result = Maps.newHashMap();
			this.setHandlerResult(result);
		}
		
		Map<String, String> existsOrderMap = (Map<String, String>) result.get("existsOrderMap");
		if(existsOrderMap == null){
			existsOrderMap = Maps.newHashMap();
			result.put("existsOrderMap", existsOrderMap);
		}

		if(rowIndex == (getStartRow() -1)){//如果是title列，则直接检查是否同一个Excel模板,包括顺序和列名匹配
			StringBuilder sb = new StringBuilder("");
			sb.append("服务类型").append(",").append("用户姓名").append(",");
			sb.append("性别").append(",").append("联系方式1").append(",");
			sb.append("联系方式2").append(",").append("省").append(",");
			sb.append("市").append(",").append("区").append(",");
			sb.append("详细地址").append(",").append("产品品牌").append(",");
			sb.append("产品品类").append(",").append("产品型号").append(",");
			sb.append("产品数量").append(",").append("机身条码").append(",");
			sb.append("购买时间").append(",").append("购买渠道").append(",");
			sb.append("保修类型").append(",").append("工单加急（小时）").append(",").append("故障描述");
			String[] titles = sb.toString().split(",");
			boolean ret = true;
			for(int i = 0; i < titles.length; i++){
				String tt = String.valueOf(rowData.get(String.valueOf(i + 1)));
				if(!titles[i].equals(tt.trim())){
					//模板不匹配
					result.put("TemplateError", "TemplateError");
					ret = false;
					break;
				}
			}
			return ret;
		}else if(checkOrderData(rowData) && rowIndex > (getStartRow() -1)){
			

				Object mobile = checkMobile(rowData.get("4").toString());
			// 判断是否为科学计数法（包含E、e、+等符号）

				if(rowData.get("1") == null || StringUtils.isBlank(rowData.get("1").toString())){
					appendErrorDetail("<p>第"+(rowIndex+1)+"行数据：服务类型为空"+"</p>");
					return true;
				}else if(rowData.get("2") == null || StringUtils.isBlank(rowData.get("2").toString())){
					appendErrorDetail("<p>第"+(rowIndex+1)+"行数据：用户姓名为空"+"</p>");
					return true;
				}else if(rowData.get("4") == null || StringUtils.isBlank(rowData.get("4").toString())){
					appendErrorDetail("<p>第"+(rowIndex+1)+"行数据：联系方式1为空"+"</p>");
					return true;
				}else  if(!Pattern.matches(REGEX_MOBILE, mobile.toString())){
					appendErrorDetail("<p>第" + (rowIndex + 1) + "行数据：联系方式1格式有误" + "</p>");

				}else if(rowData.get("6") == null || StringUtils.isBlank(rowData.get("6").toString())){
					appendErrorDetail("<p>第"+(rowIndex+1)+"行数据：省为空"+"</p>");
					return true;
				}else if(rowData.get("7") == null || StringUtils.isBlank(rowData.get("7").toString())){
					appendErrorDetail("<p>第"+(rowIndex+1)+"行数据：市为空"+"</p>");
					return true;
				}else if(rowData.get("8") == null || StringUtils.isBlank(rowData.get("8").toString())){
					appendErrorDetail("<p>第"+(rowIndex+1)+"行数据：区为空"+"</p>");
					return true;
				}else if(rowData.get("9") == null || StringUtils.isBlank(rowData.get("9").toString())){
					appendErrorDetail("<p>第"+(rowIndex+1)+"行数据：详细地址为空"+"</p>");
					return true;
				}else if(rowData.get("10") == null || StringUtils.isBlank(rowData.get("10").toString())){
					appendErrorDetail("<p>第"+(rowIndex+1)+"行数据：产品品牌为空"+"</p>");
					return true;
				}else if(rowData.get("11") == null || StringUtils.isBlank(rowData.get("11").toString())){
					appendErrorDetail("<p>第"+(rowIndex+1)+"行数据：产品品类为空"+"</p>");
					return true;
				}else if(rowData.get("13") == null || StringUtils.isBlank(rowData.get("13").toString())){
					appendErrorDetail("<p>第"+(rowIndex+1)+"行数据：产品数量为空"+"</p>");
					return true;
				}else if(rowData.get("17") == null || StringUtils.isBlank(rowData.get("17").toString())){
					appendErrorDetail("<p>第"+(rowIndex+1)+"行数据：保修类型为空"+"</p>");
					return true;
				}else if(rowData.get("19") == null || StringUtils.isBlank(rowData.get("19").toString())){
					appendErrorDetail("<p>第"+(rowIndex+1)+"行数据：故障描述为空"+"</p>");
					return true;
				}
			if(rowIndex > (getMaxRows())){
				result.put("overLimit", "overLimit");
				return false;
			}
		}
		return true;
	}

	public String checkMobile(String mobile){
		String mobiles = mobile;
		if (("" + mobile).indexOf("E") != -1 || ("" + mobile).indexOf("e") != -1 || ("" + mobile).indexOf("+") != -1) {
			BigDecimal bd = new BigDecimal("" + mobile);
			if (("" + mobile).indexOf("E") != -1 || ("" + mobile).indexOf("e") != -1 || ("" + mobile).indexOf("+") != -1) {
				bd = new BigDecimal(Double.parseDouble(bd.toString()));
				mobiles = bd.toString();
			} else {
				mobiles = "" + mobile;
			}
		}
		return mobiles;
	}
	
	/**
	 * 生成批量插入的SQL语句
	 * @return
	 */
	public String generateSql(){
		StringBuilder sb = new StringBuilder();
		sb.append(" INSERT INTO crm_order ");
		sb.append(" (service_type, customer_name, customer_sex, customer_mobile, customer_telephone, province, city, AREA, customer_address, appliance_brand, appliance_category, appliance_model, appliance_num, appliance_barcode, appliance_buy_time, please_refer_mall,warranty_type, complete_limit_length, complete_extend_cost)	 ");
		sb.append(" VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ");
		return sb.toString();
	}
	
	/**
	 * 根据具体业务验证excel数据的正确有效性
	 * @param rowData:excel的每一行数据
	 * @return 
	 * 			true:表示可以插入数据库的，
	 * 			false:表示校验失败的，需要错误提示的
	 */
	public boolean checkRowData(Map<String, Object> rowData){
		if((rowData.get("1") == null || StringUtils.isBlank(rowData.get("1").toString()))
				&& (rowData.get("2") == null || StringUtils.isBlank(rowData.get("2").toString()))
				&& (rowData.get("4") == null || StringUtils.isBlank(rowData.get("4").toString()))
				&& (rowData.get("6") == null || StringUtils.isBlank(rowData.get("6").toString()))
				&& (rowData.get("7") == null || StringUtils.isBlank(rowData.get("7").toString()))
				&& (rowData.get("8") == null || StringUtils.isBlank(rowData.get("8").toString()))
				&& (rowData.get("9") == null || StringUtils.isBlank(rowData.get("9").toString()))
				&& (rowData.get("10") == null || StringUtils.isBlank(rowData.get("10").toString()))
				&& (rowData.get("11") == null || StringUtils.isBlank(rowData.get("11").toString()))
				&& (rowData.get("13") == null || StringUtils.isBlank(rowData.get("13").toString()))
				&& (rowData.get("17") == null || StringUtils.isBlank(rowData.get("17").toString()))
				&& (rowData.get("19") == null || StringUtils.isBlank(rowData.get("19").toString()))
				){
			return false;
		}
		return true;
	}
	
	public boolean checkOrderData(Map<String, Object> rowData){
		if((rowData.get("1") == null || StringUtils.isBlank(rowData.get("1").toString()))
				&& (rowData.get("2") == null || StringUtils.isBlank(rowData.get("2").toString()))
				&& (rowData.get("4") == null || StringUtils.isBlank(rowData.get("4").toString()))
				&& (rowData.get("6") == null || StringUtils.isBlank(rowData.get("6").toString()))
				&& (rowData.get("7") == null || StringUtils.isBlank(rowData.get("7").toString()))
				&& (rowData.get("8") == null || StringUtils.isBlank(rowData.get("8").toString()))
				&& (rowData.get("9") == null || StringUtils.isBlank(rowData.get("9").toString()))
				&& (rowData.get("10") == null || StringUtils.isBlank(rowData.get("10").toString()))
				&& (rowData.get("11") == null || StringUtils.isBlank(rowData.get("11").toString()))
				&& (rowData.get("13") == null || StringUtils.isBlank(rowData.get("13").toString()))
				&& (rowData.get("17") == null || StringUtils.isBlank(rowData.get("17").toString()))
				&& (rowData.get("19") == null || StringUtils.isBlank(rowData.get("19").toString()))
				){
			return false;
		}
		return true;
	}

	/**
	 * 根据业务封装可执行的SQL语句对应的参数数组
	 * @param rowData
	 * @param count
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Object[] wrapSqlParams(Map<String, Object> rowData, int count){
		Object[] param = new Object[count];
		Map<String, String> params = (Map<String, String>) getParams();
		for(int i = 1; i <= rowData.size(); i++){
			String idx = i + "";
			Object val = rowData.get(idx);
			if(i== 3){
				if(val != null && StringUtils.isNotBlank(val.toString())){
					String sex =  val.toString();
					if("先生".equals(sex)){
						val = "1";
					}else{
						val = "2";
					}

				}
			}else if(i==4){
				val = checkMobile(rowData.get("4").toString());
			}else if(i==13){
			int sjd= new Double(String.valueOf(val)).intValue();
				val =sjd;
			}
			else if( i == 15){//完工时间|报修时间|购买日期
				if(val != null && StringUtils.isNotBlank(val.toString())){
					try{
						String time = val.toString();
						if(ExcelWrite.regex(time)){//可能的数字excel时间
							int leng = time.indexOf(".");
							if(leng >0){
								time = time.substring(0,leng);
							}
							Date tmpDate = DateUtils.converExcelDate(time);
							val = tmpDate;
						}else{
							val = DateUtils.parseDate(val.toString(), datePattern);
						}
					}catch (Exception e) {
						val= null;
					}
				}else{
					val = null;
				}
			}else if(i== 17){
				if(val != null && StringUtils.isNotBlank(val.toString())){
					String sex =  val.toString();
					if("保内".equals(sex)){
						val = "1";
					}else{
						val = "2";
					}

				}
			}else if(i==18){
				if(val!= null && StringUtils.isNotBlank(val.toString())){
					int sjd= new Double(String.valueOf(val)).intValue();
					val =sjd;
				}else{
					val="0";
				}
			}
			param[i-1] = val;
		}
		return param;
	}
	

}
