/**
 * 
 */
package com.kingdee.shr.customer.gtiit.imports;

import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.kingdee.shr.base.syssetting.app.io.fileImport.BaseColumnInfo;
import com.kingdee.shr.base.syssetting.app.io.fileImport.BaseImportService;
import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.base.codingrule.CodingRuleManagerFactory;
import com.kingdee.eas.base.codingrule.ICodingRuleManager;
import com.kingdee.eas.base.core.hr.util.HRParamUtil;
import com.kingdee.eas.basedata.org.HROrgUnitInfo;
import com.kingdee.eas.basedata.org.OrgType;
import com.kingdee.eas.basedata.org.OrgUnitInfo;
import com.kingdee.eas.basedata.org.PositionCollection;
import com.kingdee.eas.basedata.org.PositionFactory;
import com.kingdee.eas.basedata.org.PositionInfo;
import com.kingdee.eas.basedata.person.Genders;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.hr.base.ConstellationInfo;
import com.kingdee.eas.hr.base.EmployeeTypeCollection;
import com.kingdee.eas.hr.base.EmployeeTypeFactory;
import com.kingdee.eas.hr.base.HRBillStateEnum;
import com.kingdee.eas.hr.base.ZodiacInfo;
import com.kingdee.eas.hr.base.util.HRUtilExtend;
import com.kingdee.eas.hr.base.util.IDCardCommonUtil;
import com.kingdee.eas.hr.emp.EmployeeBizException;
import com.kingdee.eas.hr.emp.app.util.EMPhelper;
import com.kingdee.eas.hr.emp.app.util.SHREmpImportTool;
import com.kingdee.eas.hr.emp.app.util.SHREmpOptBizManageTool;
import com.kingdee.eas.hr.emp.app.util.SHREmpPreEntryCheckTool;
import com.kingdee.eas.hr.org.JobGradeCollection;
import com.kingdee.eas.hr.org.JobGradeFactory;
import com.kingdee.eas.hr.org.JobGradeInfo;
import com.kingdee.eas.hr.org.OrgnizationImportBizException;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import com.kingdee.shr.affair.web.handler.util.EmployeeUtil;
import com.kingdee.shr.base.permission.api.auth.SHRUserOrgPermissionApi;
import com.kingdee.shr.base.syssetting.BaseItemStateEnum;
import com.kingdee.shr.base.syssetting.SHRBaseItemInfo;
import com.kingdee.shr.base.syssetting.app.filter.HRFilterUtils;
import com.kingdee.shr.base.syssetting.app.io.fileImport.BaseRowInfo;
import com.kingdee.shr.base.syssetting.app.io.fileImport.ImportException;
import com.kingdee.shr.base.syssetting.app.io.impl.PreEntryPersonImportService;
import com.kingdee.shr.base.syssetting.app.io.impl.util.EmpEnrollImportCheck;
import com.kingdee.shr.base.syssetting.app.io.impl.util.FileServiceUtil;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.base.syssetting.ml.SHRWebResource;
import com.kingdee.shr.base.syssetting.util.LocaleUtils;
import com.kingdee.shr.ml.util.BOSConfigUtil;
import com.kingdee.shr.preentry.PreEntryCollection;
import com.kingdee.shr.preentry.PreEntryFactory;
import com.kingdee.shr.preentry.PreEntryInfo;
import com.kingdee.shr.preentry.PreEntryPersonInfo;
import com.kingdee.util.StringUtils;
import com.kingdee.util.DateTimeUtils;
import com.kingdee.eas.hr.base.BaseException;

/**
 * @author ISSUSER 预入职导入
 */
public class PreEntryPersonImport extends PreEntryPersonImportService {
	private static Pattern pattern = Pattern.compile("[一-龥]");

	Context ctx = SHRContext.getInstance().getContext();

	@Override
	protected void importNew(BaseRowInfo row) throws ImportException {

		try {
			Context ctx = this.getContext();
			HashMap<String, Object> modelMap = this.beforeImport(row);
			PreEntryInfo preEntryInfo = (PreEntryInfo) modelMap.get("PreEntryInfo");
			PreEntryPersonInfo preEntryPersonInfo = (PreEntryPersonInfo) modelMap.get("PreEntryPersonInfo");
			String userId = HRFilterUtils.getCurrentUserId(ctx);
			String hrOrgIdsString = SHRUserOrgPermissionApi.getUserHROrgRangeInSQL(ctx, userId, this.getPermItemId());
			// 本地姓名
			String localName = preEntryInfo.getString("localname");
			// 姓 只包含英文和空格
			String surname = preEntryInfo.getString("surname");
			boolean allUpperCase = isEnglishAndSpaceOnly(surname);
			if (!allUpperCase) {
				throw new ImportException("The first name must be in English");
			}
			preEntryInfo.put("surname", surname.toUpperCase());
			// 名
			String givenName = preEntryInfo.getString("givenname");
			// 中间名
			String middleNames = preEntryInfo.getString("middlenames");
			preEntryInfo.put("middlenames", middleNames);
			// 预入职日期
			Date preEnterDate = preEntryInfo.getDate("preenterdate");
			// 试用期（月）
			int tryMonth = preEntryInfo.getInt("trymonth");
			// 逻辑
			// 用户名 名】.【姓】 超过20字节保留首字母
			String userName = givenName + "." + surname;
			if (userName.length() > 20) {
				userName = givenName + "." + surname.substring(0, 1);
				if(userName.length() > 20) {
					int startLength = userName.length() - 20;
					userName = userName.substring(startLength,userName.length());
				}
			}
			userName = userName.toLowerCase();
			preEntryInfo.put("userName", userName);
			// 姓名= 名+姓+本地名称
			String name = givenName + " " + surname.toUpperCase() + " " + localName;
			// 工作邮箱=用户名】+"@gtiit.edu.cn"
			String workemail = userName + "@gtiit.edu.cn";
			preEntryInfo.put("workemail", workemail);
			// 私人邮箱
			// 试用期开始日期 默认为预入职日期
			preEntryInfo.put("trialStartDate", preEnterDate);
			// 预计转正日期 =【预入职日期】 + 【试用期（月）】
			Calendar instance = Calendar.getInstance();
			instance.setTime(preEnterDate);
			instance.add(Calendar.MONTH, tryMonth);
			Date time = instance.getTime();
			preEntryInfo.put("transferDate", time);
			String employeeTypeNumber = "";
			if(tryMonth > 0) {
				employeeTypeNumber = "002";
			}else {
				employeeTypeNumber = "001";
			}
			EmployeeTypeCollection employeeTypeColl = EmployeeTypeFactory.getLocalInstance(ctx).getEmployeeTypeCollection("where number = '"+employeeTypeNumber+"'");
			if(employeeTypeColl!=null && employeeTypeColl.size()>0) {
				preEntryInfo.put("empType", employeeTypeColl.get(0).getId().toString());
			}
			
			// 编码
			EmployeeUtil employee = new EmployeeUtil();
			int number = employee.getFnumber();
			preEntryInfo.put("empNumber", number);
			// 判断是否大于18岁
			Date birthday = preEntryPersonInfo.getBirthday();
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			String dateBirthday = formatter.format(birthday);
			LocalDate now = LocalDate.now();

			Calendar calendar = Calendar.getInstance();

			calendar.setTime(birthday);

			calendar.setTimeZone(TimeZone.getTimeZone("UTC")); // 设置时区为UTC，可以根据需要修改时区
			java.time.ZonedDateTime zonedDateTime = java.time.ZonedDateTime.ofInstant(calendar.toInstant(),
					calendar.getTimeZone().toZoneId());
			// 将ZonedDateTime转换为LocalDate

			LocalDate lobirthday = zonedDateTime.toLocalDate();
			long daysBetween = ChronoUnit.DAYS.between(lobirthday, now);
			if (daysBetween / 365.25 < 18) {
				throw new ImportException("Onboarding is not allowed for persons under 18 years old");
			}
			// 身份证不为空用身份证
			// 不为空就用 姓名+出生日期判断用户的唯一
			String cardno = preEntryPersonInfo.getIdCardNO();
			String checkSql = "select FIDCardNO,FPASSPORTNO from t_bd_person where to_char(FBirthday,'yyyy-MM-dd') = '"
					+ dateBirthday + "' and UPPER(FName_L1) = UPPER('" + name + "') or FIDCardNO = '"+cardno+"'";
			IRowSet rs = DbUtil.executeQuery(ctx, checkSql);
			if (rs.next()) {
				if(!StringUtils.isEmpty(rs.getString("FIDCardNO"))){
					throw new ImportException("Employee is re-entry employee, ID number：" + rs.getString("FIDCardNO"));
				}
				if(!StringUtils.isEmpty(rs.getString("FPASSPORTNO"))){
					throw new ImportException("Employee is re-entry employee, passport number：" + rs.getString("FPASSPORTNO"));
				}
			}
			
			JobGradeInfo jobGrade = (JobGradeInfo)preEntryInfo.get("jobGrade");
			if(jobGrade != null) {
				jobGrade = JobGradeFactory.getLocalInstance(ctx).getJobGradeInfo(new ObjectUuidPK(jobGrade.getId().toString()));
//				checkGrade(ctx, preEntryInfo.getPosition().getId().toString(), jobGrade);
				String errorMsg = checkJobGrade(ctx, preEntryInfo.getPosition().getId().toString(), jobGrade);
				if(org.apache.commons.lang3.StringUtils.isNotBlank(errorMsg)) {
					throw new ImportException(errorMsg);
				}
			}
			
			String nameOrEmailSql = "select fid from t_bd_person where Upper(CFUserName) = Upper('"+userName+"') or Upper(FEMail) = Upper('"+workemail+"')  union  select fid from T_HR_PreEntry where Upper(CFUserName_l1) = Upper('"+userName+"') or Upper(CFWorkemail) = Upper('"+workemail+"')";
			IRowSet emailRow = DbUtil.executeQuery(ctx, nameOrEmailSql);
			if(emailRow.next()) {
				throw new ImportException("The username: "+userName+" or email: "+workemail+" already exists");
			}

			if (!hrOrgIdsString.contains(preEntryInfo.getHrOrgUnit().getId().toString())) {
				EmployeeBizException e = new EmployeeBizException(EmployeeBizException.ENTRY_POSI_ORG_NOT_IN);
				throw new ImportException(e.getMessage(), e);
			}

			this.checkBlackList(ctx, preEntryPersonInfo);
			String empName = "";
			String l = LocaleUtils.getShortCode(ctx);
			boolean isNecessary = HRParamUtil.getParamOfHR(ctx, "IS_FULLNAME_SUBFIELD", (String) null);
			List<Map<String, String>> languageMapping = this.getLanguageMappingList();
			Matcher m1 = null;
			Matcher m2 = null;
			String firstNameLocal = null;
			String lastNameLocal = null;
			String curLang = null;
			Map<String, String> curLangs = new HashMap();
			curLangs.put("l1", "l1");
			curLangs.put("l2", "l2");
			curLangs.put("l3", "l3");
			Iterator var18;
			Map map;
			String orgId;
			if (isNecessary) {
				var18 = languageMapping.iterator();

				label145: while (true) {
					if (!var18.hasNext()) {
						if (curLangs.size() <= 0) {
							break;
						}

						var18 = curLangs.keySet().iterator();

						while (true) {
							if (!var18.hasNext()) {
								break label145;
							}

							orgId = (String) var18.next();
							curLang = (String) curLangs.get(orgId);
							preEntryInfo.setFirstName(
									preEntryInfo.getFirstName(com.kingdee.util.LocaleUtils.getLocale(l)),
									com.kingdee.util.LocaleUtils.getLocale(curLang));
							preEntryInfo.setLastName(
									preEntryInfo.getLastName(com.kingdee.util.LocaleUtils.getLocale(l)),
									com.kingdee.util.LocaleUtils.getLocale(curLang));
							preEntryPersonInfo.setFirstName(
									preEntryPersonInfo.getFirstName(com.kingdee.util.LocaleUtils.getLocale(l)),
									com.kingdee.util.LocaleUtils.getLocale(curLang));
							preEntryPersonInfo.setLastName(
									preEntryPersonInfo.getLastName(com.kingdee.util.LocaleUtils.getLocale(l)),
									com.kingdee.util.LocaleUtils.getLocale(curLang));
							// preEntryInfo.setName(preEntryInfo.getName(com.kingdee.util.LocaleUtils.getLocale(l)),
							// com.kingdee.util.LocaleUtils.getLocale(curLang));
							// preEntryPersonInfo.setName(
							// preEntryPersonInfo.getName(com.kingdee.util.LocaleUtils.getLocale(l)),
							// com.kingdee.util.LocaleUtils.getLocale(curLang));
						}
					}

					map = (Map) var18.next();
					firstNameLocal = row
							.getValueOfString(MessageFormat.format("{0}.{1}", "firstName", map.get("locale")));
					lastNameLocal = row
							.getValueOfString(MessageFormat.format("{0}.{1}", "lastName", map.get("locale")));
					curLang = (String) map.get("lang");
					preEntryInfo.setFirstName(firstNameLocal, com.kingdee.util.LocaleUtils.getLocale(curLang));
					preEntryInfo.setLastName(lastNameLocal, com.kingdee.util.LocaleUtils.getLocale(curLang));
					preEntryPersonInfo.setFirstName(firstNameLocal, com.kingdee.util.LocaleUtils.getLocale(curLang));
					preEntryPersonInfo.setLastName(lastNameLocal, com.kingdee.util.LocaleUtils.getLocale(curLang));
					m1 = pattern.matcher(firstNameLocal);
					m2 = pattern.matcher(lastNameLocal);
					empName = !m1.find() && !m2.find() ? firstNameLocal + " " + lastNameLocal
							: lastNameLocal + firstNameLocal;
					// preEntryInfo.setName(empName,
					// com.kingdee.util.LocaleUtils.getLocale(curLang));
					// preEntryPersonInfo.setName(empName,
					// com.kingdee.util.LocaleUtils.getLocale(curLang));

				}
			} else {
				var18 = languageMapping.iterator();

				while (var18.hasNext()) {
					map = (Map) var18.next();
					curLang = (String) map.get("lang");
					empName = row.getValueOfString(MessageFormat.format("{0}.{1}", "name", map.get("locale")));
					// preEntryInfo.setName(empName,
					// com.kingdee.util.LocaleUtils.getLocale(curLang));
					// preEntryPersonInfo.setName(empName,
					// com.kingdee.util.LocaleUtils.getLocale(curLang));
					preEntryInfo.setName(name, com.kingdee.util.LocaleUtils.getLocale(curLang));
					preEntryPersonInfo.setName(name, com.kingdee.util.LocaleUtils.getLocale(curLang));
					curLangs.remove(curLang);
					curLangs.remove(curLang);
				}

				if (curLangs.size() > 0) {
					var18 = curLangs.keySet().iterator();

					while (var18.hasNext()) {
						orgId = (String) var18.next();
						curLang = (String) curLangs.get(orgId);
						// preEntryInfo.setName(preEntryInfo.getName(com.kingdee.util.LocaleUtils.getLocale(l)),
						// com.kingdee.util.LocaleUtils.getLocale(curLang));
						// preEntryPersonInfo.setName(
						// preEntryPersonInfo.getName(com.kingdee.util.LocaleUtils.getLocale(l)),
						// com.kingdee.util.LocaleUtils.getLocale(curLang));
					}
				}
			}

			if (SHREmpImportTool.SPECIAL_AREA_CODE.equals(preEntryInfo.getGlobalRoaming())) {
				preEntryInfo.setCellPhone(preEntryInfo.getNCell());
			} else {
				preEntryInfo.setCellPhone(preEntryInfo.getGlobalRoaming() + "-" + preEntryInfo.getNCell());
			}

			preEntryInfo.setIsSSC(false);
			preEntryInfo.setBillState(HRBillStateEnum.SAVED);
			// 单据编号
//			if (!row.getValueOfString("PreEntry.number").equals("")) {
//				String preNumber = row.getValueOfString("PreEntry.number");
//				PreEntryCollection coll = PreEntryFactory.getLocalInstance(ctx)
//						.getPreEntryCollection("where number = '" + preNumber + "'");
//				if (coll.size() > 0) {
//					EmployeeBizException e = new EmployeeBizException(EmployeeBizException.HAS_EXIST_BILL_COD_OBJ,
//							new Object[] { preNumber });
//					throw new ImportException(e.getMessage(), e);
//				}
//
//				preEntryInfo.setNumber(preNumber);
//			}

			EmployeeBizException e;
			if (StringUtils.isEmpty(preEntryInfo.getNumber())) {
				OrgUnitInfo mainOrg = (OrgUnitInfo) ctx.get(OrgType.ControlUnit);
				orgId = mainOrg == null ? "" : mainOrg.getString("id");
				if (orgId == null || orgId.trim().length() == 0) {
					orgId = "00000000-0000-0000-0000-000000000000CCE7AED4";
				}

				ICodingRuleManager iCodingRuleManager = CodingRuleManagerFactory.getLocalInstance(ctx);
				if (!iCodingRuleManager.isExist(preEntryInfo, orgId)) {
					e = new EmployeeBizException(EmployeeBizException.BILL_NUM_NULL_NO_COD_RULE);
					throw new ImportException(e.getMessage(), e);
				}
			} else {
				preEntryInfo.put("isNeedCoding", "true");
			}
			PositionCollection coll = PositionFactory.getLocalInstance(ctx)
					.getPositionCollection("where id = '" + preEntryInfo.getPosition().getId().toString() + "'");
			HROrgUnitInfo hrOrgUnitInfo = SHREmpOptBizManageTool.getManageHROByAdminOrg(ctx,
					coll.get(0).getAdminOrgUnit().getId().toString());
			String importCheckEffectPermission = this.importCheckEffectPermission(ctx,
					"/dynamic.do?method=submitEffect#uri=emp.PreEntry.form", hrOrgUnitInfo);
			if (!StringUtils.isEmpty(importCheckEffectPermission)) {
				throw new ImportException(importCheckEffectPermission);
			}

			if (hrOrgUnitInfo == null) {
				e = new EmployeeBizException(EmployeeBizException.CANNOT_GET_TARGET,
						new Object[] { preEntryInfo.getPosition().getName() });
				throw new ImportException(e.getMessage(), e);
			}

			String IDCardNo = row.getValueOfString("IDCardNO");
			String constellationName = row.getValueOfString("constellation");
			String zodiacName = row.getValueOfString("zodiac");
			Map<String, String> resultMap = null;
			ConstellationInfo cInfo = new ConstellationInfo();
			ZodiacInfo zInfo = new ZodiacInfo();
			IDCardCommonUtil iDCardCommonUti = null;
			if (StringUtils.isEmpty(constellationName)) {
				if (!StringUtils.isEmpty(row.getValueOfString("birthday"))) {
					resultMap = EMPhelper.getConZocByBirthDay(ctx, preEntryPersonInfo.getBirthday());
				} else if (!StringUtils.isEmpty(IDCardNo)) {
					iDCardCommonUti = new IDCardCommonUtil(IDCardNo,
							HRParamUtil.getParamOfHR(ctx, "IS_IDCARD_VERIFY", hrOrgUnitInfo.getId().toString()));
					resultMap = EMPhelper.getConZocByBirthDay(ctx, iDCardCommonUti.getBirthday());
				}

				if (resultMap != null && resultMap.containsKey("constellationId")) {
					cInfo.setId(BOSUuid.read((String) resultMap.get("constellationId")));
					cInfo.setName((String) resultMap.get("constellation"));
				}
			} else {
				cInfo = EMPhelper.getConstellationByName(ctx, constellationName);
			}

			preEntryPersonInfo.setConstellation(cInfo);
			if (StringUtils.isEmpty(zodiacName)) {
				if (!StringUtils.isEmpty(row.getValueOfString("birthday"))) {
					resultMap = EMPhelper.getConZocByBirthDay(ctx, preEntryPersonInfo.getBirthday());
				} else if (!StringUtils.isEmpty(IDCardNo)) {
					iDCardCommonUti = new IDCardCommonUtil(IDCardNo,
							HRParamUtil.getParamOfHR(ctx, "IS_IDCARD_VERIFY", hrOrgUnitInfo.getId().toString()));
					resultMap = EMPhelper.getConZocByBirthDay(ctx, iDCardCommonUti.getBirthday());
				}

				if (resultMap != null && resultMap.containsKey("zodiacId")) {
					zInfo.setId(BOSUuid.read((String) resultMap.get("zodiacId")));
					zInfo.setName((String) resultMap.get("zodiac"));
				}
			} else {
				zInfo = EMPhelper.getZodiacByName(ctx, zodiacName);
			}

			preEntryPersonInfo.setZodiac(zInfo);
			// // 员工姓名不能为空
			// if (StringUtils.isEmpty(preEntryInfo.getName())) {
			//// EmployeeBizException e1 = new
			// EmployeeBizException(EmployeeBizException.EMP_NAME_NOT_NULL);
			//// throw new ImportException(e1.getMessage(), e1);
			// throw new ImportException("年龄不能大于18岁");
			// }

			SHRBaseItemInfo baseItemInfo = preEntryInfo.getEnrollSource();
			if (baseItemInfo != null && !this.isAvailableBaseItem(hrOrgUnitInfo.getId().toString(),
					baseItemInfo.getId().toString(), "com.kingdee.eas.hr.base.app.EnrollSource")) {
				EmployeeBizException e1 = new EmployeeBizException(EmployeeBizException.INVITE_SOURCE_BASE,
						new Object[] { baseItemInfo.getName(), hrOrgUnitInfo.getName() });
				throw new ImportException(e1.getMessage(), e1);
			}
			//法人
			preEntryInfo.put("legalemployer", preEntryInfo.getString("legalemployer"));

			this.setWorkFlow(preEntryInfo);
			super.addnewModel(preEntryInfo, preEntryPersonInfo);
		} catch (EASBizException var30) {
			throw new ImportException(var30.getMessage(), var30);
		} catch (BOSException var31) {
			throw new ImportException(var31.getMessage(), var31);
		} catch (SHRWebException var32) {
			var32.printStackTrace();
		} catch (ParseException var33) {
			var33.printStackTrace();
		}  catch (SQLException e2) {
			e2.printStackTrace();
		}

	}
	
	/**
	 * 校验职等是否在职位范围内
	 * @param ctx
	 * @param positionId
	 * @param jobGradeInfo
	 * @return
	 * @throws BOSException
	 * @throws SQLException
	 */
	public static boolean checkGrade(Context ctx,String positionId, JobGradeInfo jobGradeInfo) throws BOSException, SQLException {
		String sql = "SELECT a.FHIGHJOBGRADEID,a.FLOWJOBGRADEID,b.FINDEX highIndex,c.FINDEX lowIndex,c.FJOBGRADEMODULEID FROM T_ORG_Position a left join T_HR_JobGrade b on a.FHIGHJOBGRADEID = b.FID left join T_HR_JobGrade c on a.FLOWJOBGRADEID = c.fid where a.FID = '"+positionId+"'";
		IRowSet rs = DbUtil.executeQuery(ctx, sql);
		String highJobGradeId = "";
		String lowJobGradeId = "";
		String highIndex = "";
		String lowIndex = "";
		String jobGradeModuleId = "";
		if (rs.next()) {
			highJobGradeId = rs.getString("FHIGHJOBGRADEID")==null?"":rs.getString("FHIGHJOBGRADEID");
			lowJobGradeId = rs.getString("FLOWJOBGRADEID")==null?"":rs.getString("FLOWJOBGRADEID");
			highIndex = rs.getString("highIndex")==null?"":rs.getString("highIndex");
			lowIndex = rs.getString("lowIndex")==null?"":rs.getString("lowIndex");
			jobGradeModuleId = rs.getString("FJOBGRADEMODULEID")==null?"":rs.getString("FJOBGRADEMODULEID");
		}
		if(highJobGradeId != "" && lowJobGradeId != "") {
			String gradeIndex = String.valueOf(jobGradeInfo.getIndex());
			String gradeJobModuleId = jobGradeInfo.getJobGradeModule().getId().toString();
			if(gradeIndex.compareTo(lowIndex)>=0 && gradeIndex.compareTo(highIndex)<=0 && jobGradeModuleId.equals(gradeJobModuleId)) {
				return false;
			}
		}
		return true;
	}
	
	/**
	 * 校验职等是否在职位范围内（标准方法）
	 * @param ctx
	 * @param positionId
	 * @param jobGradeInfo
	 * @return
	 * @throws BOSException
	 * @throws SQLException
	 */
	public String checkJobGrade(Context ctx,String positionId, JobGradeInfo jobGradeInfo) throws BOSException {
		String errorMsg = "";
		String jobGradeId = jobGradeInfo.getId().toString();
		if (StringUtils.isEmpty(jobGradeId)) {
			return errorMsg;
		} else {
			StringBuffer sql = (new StringBuffer())
					.append("select id,name,number,index,jobGradeModule.state,jobGradeModule.name,jobGradeModule.id")
					.append(" where id = '").append(jobGradeId).append("')").append(" and state = 1");
			JobGradeCollection jgColl = JobGradeFactory.getLocalInstance(ctx).getJobGradeCollection(sql.toString());
			if (jgColl.size() > 0) {
				JobGradeInfo jgInfo = jgColl.get(0);
				if (jgInfo.getJobGradeModule() == null
						|| jgInfo.getJobGradeModule().getState() != BaseItemStateEnum.ENABLE) {
					errorMsg = MessageFormat.format(
							SHRWebResource.getString("com.kingdee.eas.hr.emp.EmployeeBizResource", "label153", ctx),
							jgInfo.getJobGradeModule().getName());
					return errorMsg;
				} else {
					int index = jgInfo.getIndex();
					String oql = "select id,lowJobGrade.name,lowJobGrade.number,lowJobGrade.index,highJobGrade.name,highJobGrade.number,highJobGrade.index,lowJobGrade.jobGradeModule.id where id ='"
							+ positionId + "'";
					PositionInfo pInfo = PositionFactory.getLocalInstance(ctx).getPositionCollection(oql).get(0);
					if (pInfo.getLowJobGrade() != null && pInfo.getHighJobGrade() != null) {
						if (pInfo.getLowJobGrade().getJobGradeModule() == null) {
							errorMsg = SHRWebResource.getString("com.kingdee.eas.hr.emp.EmployeeBizResource",
									"label160", ctx);
							return errorMsg;
						} else if (!jgInfo.getJobGradeModule().getId().toString()
								.equals(pInfo.getLowJobGrade().getJobGradeModule().getId().toString())) {
							errorMsg = SHRWebResource.getString("com.kingdee.eas.hr.emp.EmployeeBizResource",
									"label162", ctx);
							return errorMsg;
						} else if (index >= pInfo.getLowJobGrade().getIndex()
								&& index <= pInfo.getHighJobGrade().getIndex()) {
							return errorMsg;
						} else {
							errorMsg = SHRWebResource.getString("com.kingdee.eas.hr.emp.EmployeeBizResource",
									"label151", ctx);
							return errorMsg;
						}
					} else {
						errorMsg = SHRWebResource.getString("com.kingdee.eas.hr.emp.EmployeeBizResource",
								"label158", ctx);
						return errorMsg;
					}
				}
			} else {
				return errorMsg;
			}
		}
	}
	

	@Override
	protected void verifyRow(BaseRowInfo row) throws ImportException {
		Map<String, BaseColumnInfo> columnInfoMap = row.getMapColumnInfo();
		Iterator<Entry<String, BaseColumnInfo>> iterator = columnInfoMap.entrySet().iterator();
		Context ctx = this.getContext();
		Map<String, String> validMap = new HashMap();
		EmpEnrollImportCheck eeic = new EmpEnrollImportCheck();

		String value;
		while (iterator.hasNext()) {
			BaseColumnInfo columnInfo = (BaseColumnInfo) ((Entry) iterator.next()).getValue();
			if (columnInfo != null) {
				value = row.getValueOfStringByIndex(columnInfo.getColumnIndex());
				if (columnInfo.getPropName().equals("PreEntry.adminOrg")) {
					validMap.put("adminOrg", value);
				} else if (columnInfo.getPropName().equals("PreEntry.position")) {
					validMap.put("position", value);
				} else {
					validMap.put(columnInfo.getPropName(), value);
				}
			}
		}

		try {
			value = eeic.checkPositionAndOrgAndCompany(ctx, validMap);
			if (!StringUtils.isEmpty(value)) {
				throw new ImportException(value);
			}
		} catch (BOSException var9) {
			var9.printStackTrace();
		}
		super.verifyRow(row);
	}

	@Override
	public boolean verifyModelData(HashMap<String, Object> map) throws BOSException, EASBizException {
		boolean verifyType = true;
		PreEntryInfo preEntryInfo = (PreEntryInfo) map.get("PreEntryInfo");
		PreEntryPersonInfo preEntryPersonInfo = (PreEntryPersonInfo) map.get("PreEntryPersonInfo");
		String errorInfo;
		if (!StringUtils.isEmpty(preEntryPersonInfo.getIdCardNO()) && preEntryInfo.getHrOrgUnit() != null
				&& preEntryInfo.getHrOrgUnit().getId() != null) {
			IDCardCommonUtil iDCardCommonUtil = null;
			boolean isIDCardVerify = false;

			try {
				isIDCardVerify = HRParamUtil.getParamOfHR(this.getContext(), "IS_IDCARD_VERIFY",
						preEntryInfo.getHrOrgUnit().getId().toString());
				iDCardCommonUtil = new IDCardCommonUtil(preEntryPersonInfo.getIdCardNO(), isIDCardVerify);
				errorInfo = iDCardCommonUtil.getBirthday();
				Genders gender = iDCardCommonUtil.getGenders();
				Date birthday = DateTimeUtils.parseDate(errorInfo);
				if (preEntryPersonInfo.getGender() == null) {
					preEntryPersonInfo.setGender(gender);
				}

				if (preEntryPersonInfo.getBirthday() == null) {
					preEntryPersonInfo.setBirthday(birthday);
				}
			} catch (BaseException var12) {
				throw new ImportException(var12.getMessage(), var12);
			} catch (ParseException var13) {
				if (isIDCardVerify) {
					BaseException e1 = new BaseException(BaseException.IDCARD_NUMERROR);
					throw new ImportException(e1.getMessage(), e1);
				}
			}
		}

		if (!StringUtils.isEmpty(preEntryInfo.getNCell()) && !StringUtils.isEmpty(preEntryInfo.getGlobalRoaming())) {
			if (SHREmpImportTool.SPECIAL_AREA_CODE.equals(preEntryInfo.getGlobalRoaming())) {
				preEntryInfo.setCellPhone(preEntryInfo.getNCell());
			} else {
				preEntryInfo.setCellPhone(preEntryInfo.getGlobalRoaming() + "-" + preEntryInfo.getNCell());
			}

			Context ctx = this.getContext();

			try {
				String preEntryID = preEntryInfo.getId() != null ? preEntryInfo.getId().toString() : "";
				errorInfo = "";
				String email;
				if (preEntryInfo.getCellPhone() != null) {
					email = preEntryInfo.getCellPhone();
					HRUtilExtend.verifyCellPhoneNumber(ctx, email);
					errorInfo = SHREmpPreEntryCheckTool.checkPreEntryCellPhone(ctx, email, preEntryID);
					if (!errorInfo.equals("")) {
						throw new ImportException(errorInfo);
					}
				}

				if (preEntryInfo.getEmail() != null) {
					email = preEntryInfo.getEmail();
					HRUtilExtend.verifyMail(ctx, email);
					errorInfo = SHREmpPreEntryCheckTool.checkPreEntryEmail(ctx, email, preEntryID);
					if (!errorInfo.equals("")) {
						throw new ImportException(errorInfo);
					}
				}
			} catch (BOSException var10) {
				var10.printStackTrace();
			} catch (SQLException var11) {
				var11.printStackTrace();
			}

			return verifyType;
		} else {
			EmployeeBizException e = new EmployeeBizException(EmployeeBizException.TEL_IS_NULL);
			throw new ImportException(e.getMessage(), e);
		}
	}

	// 判断字符串是否是英文和空格
	public static boolean isEnglishAndSpaceOnly(String str) {
	    // 定义正则表达式，表示只包含英文和空格
	    String pattern = "^[a-zA-Z\\s]*$";
	    // 判断字符串是否匹配正则表达式
	    return str.matches(pattern);
	}


//	 模板动态添加列
	@Override
	public List<BaseColumnInfo> getDynamicColumn() {

	      Context ctx = this.getContext();
	      List<BaseColumnInfo> list = new ArrayList();
	      boolean isNecessary = false;
	      OrgnizationImportBizException e1;
	      try {
	         isNecessary = HRParamUtil.getParamOfHR(ctx, "IS_FULLNAME_SUBFIELD", (String)null);
	      } catch (EASBizException var9) {
	         e1 = new OrgnizationImportBizException(OrgnizationImportBizException.EXCEPTION116, var9, new Object[]{var9.getMessage()});
	         throw new ImportException(e1.getMessage(), e1);
	      } catch (BOSException var10) {
	         e1 = new OrgnizationImportBizException(OrgnizationImportBizException.EXCEPTION116, var10, new Object[]{var10.getMessage()});
	         throw new ImportException(e1.getMessage(), e1);
	      }
	 
	      List<Map<String, String>> languageMapping = this.getLanguageMappingList();
	 
	      int i = 1;
	      BaseColumnInfo columnInfo = null;
	      String columnName = null;     int j;
	      if (isNecessary) {
	         for(j = 0; j < languageMapping.size(); ++j) {
	            columnName = MessageFormat.format("{0}.{1}", "lastName", ((Map)languageMapping.get(j)).get("locale"));
	            columnInfo = BaseColumnInfo.createDynamicColumn(columnName, "", isNecessary);
	            columnInfo.setName(MessageFormat.format("{0}.{1}", SHRWebResource.getString("com.kingdee.eas.hr.emp.EmployeeResource", "EMP_LASTNAME", ctx), ((Map)languageMapping.get(j)).get("text")));
	            columnInfo.setColumnIndex(i);
	            columnInfo.setDataType(1);
	            columnInfo.setMultiLanFieldSupport(true);
	            list.add(columnInfo);
	            ++i;
	         }
	         for(j = 0; j < languageMapping.size(); ++j) {
	            columnName = MessageFormat.format("{0}.{1}", "firstName", ((Map)languageMapping.get(j)).get("locale"));
	            columnInfo = BaseColumnInfo.createDynamicColumn(columnName, "", isNecessary);
	            columnInfo.setName(MessageFormat.format("{0}.{1}", SHRWebResource.getString("com.kingdee.eas.hr.emp.EmployeeResource", "EMP_FIRSTNAME", ctx), ((Map)languageMapping.get(j)).get("text")));
	            columnInfo.setColumnIndex(i);
	            columnInfo.setDataType(1);
	            columnInfo.setMultiLanFieldSupport(true);
	            list.add(columnInfo);
	            ++i;
	         }
	      } else {
	         for(j = 0; j < languageMapping.size(); ++j) {
	        	 //去除name.chas这个字段
	            columnName = MessageFormat.format("{0}.{1}", "name", ((Map)languageMapping.get(j)).get("locale"));
	            columnInfo = BaseColumnInfo.createDynamicColumn(columnName, "", false);
	            columnInfo.setName(MessageFormat.format("{0}.{1}", SHRWebResource.getString("com.kingdee.eas.hr.emp.EmployeeResource", "EMP_NAME", ctx), ((Map)languageMapping.get(j)).get("text")));
	            columnInfo.setColumnIndex(i);
	            columnInfo.setDataType(1);
	            columnInfo.setMultiLanFieldSupport(true);
	            list.add(columnInfo);
	            ++i;
	         }
	      }
	 
	      return list;
	   
	}
	

	
	


}
