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

import java.sql.SQLException;
import java.text.MessageFormat;
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 com.cloudera.impala.jdbc4.internal.apache.log4j.Logger;
import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.orm.ORMCoreException;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.base.permission.UserInfo;
import com.kingdee.eas.basedata.org.AdminOrgUnitInfo;
import com.kingdee.eas.basedata.org.HROrgUnitInfo;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.framework.CoreBaseInfo;
import com.kingdee.eas.hr.affair.IResignBizBill;
import com.kingdee.eas.hr.affair.ResignBizBillEntryInfo;
import com.kingdee.eas.hr.affair.ResignBizBillFactory;
import com.kingdee.eas.hr.affair.ResignBizBillInfo;
import com.kingdee.eas.hr.base.AffairActionReasonFactory;
import com.kingdee.eas.hr.base.AffairActionReasonInfo;
import com.kingdee.eas.hr.base.BillEffectEnum;
import com.kingdee.eas.hr.base.EmpLaborRelationInfo;
import com.kingdee.eas.hr.base.EmployeeTypeFactory;
import com.kingdee.eas.hr.base.EmployeeTypeInfo;
import com.kingdee.eas.hr.base.HRBaseException;
import com.kingdee.eas.hr.base.HRBillStateEnum;
import com.kingdee.eas.hr.base.SHRCheckRuleInfo;
import com.kingdee.eas.hr.base.check.CheckResultInfo;
import com.kingdee.eas.hr.base.check.SHRAffairActionCheckTool;
import com.kingdee.eas.hr.base.util.HRParamUtil;
import com.kingdee.eas.hr.base.util.HRUtilExtend;
import com.kingdee.eas.hr.emp.EmpBatchAffairBizException;
import com.kingdee.eas.hr.emp.EmployeeBizException;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
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.ResignBizBillHrManImportService;
import com.kingdee.shr.base.syssetting.app.io.impl.util.FileServiceUtil;
import com.kingdee.shr.base.syssetting.app.io.impl.util.ResignImportCheck;
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.util.StringUtils;
import com.kingdee.util.UuidException;
import com.kingdee.shr.base.syssetting.app.io.fileImport.BaseColumnInfo;
import com.kingdee.eas.base.core.util.DateUtil;

/**
 * @author ISSUSER 离职单导入
 * 
 */
public class ResignBizBillImport extends ResignBizBillHrManImportService {
	private static Logger logger1 = Logger.getLogger("com.kingdee.shr.customer.gtiit.rpt.ResignBizBillImport");

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

	@Override
	protected void submitData(CoreBaseInfo baseInfo) throws ImportException {

		Context ctx = this.getContext();
		UserInfo uInfo = (UserInfo) ctx.get("UserInfo");
		PersonInfo pInfo = uInfo.getPerson();
		String effectOprate = baseInfo.get("effectOprate").toString();
		ResignBizBillInfo billInfo = new ResignBizBillInfo();
		ResignBizBillEntryInfo entryInfo = (ResignBizBillEntryInfo) baseInfo;
		String number = entryInfo.getString("empnumber");
		// 新增字段的导入
		// 通过工号查询员工信息
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT  a.fpersonid as peronid, a.CFHourlywage as hourlyage,a.CFLineManagerNameI as lineId,a.CFAdmintitle as admintitle,a.CFWorkercategoryID as workerId,a.CFJobsID as jobsId,a.CFAcademicTitleID as academicId,\r\n"
						+ "a.FAdminOrgID drementID,a.FHROrgUnitID as horgunitid,a.fpositionid as postitionid,a.fleffdt\r\n"
						+ " FROM T_HR_EmpOrgRelation a left join t_bd_person b  on b.fid=a.fpersonid inner  join (SELECT max(fleffdt)fleffdt, fpersonid FROM T_HR_EmpOrgRelation where FIsLatestInAday='1' group by fpersonid )c on a.fpersonid=c.fpersonid  \r\n"
						+ "  and  a.fleffdt=c.fleffdt where a.FIsLatestInAday ='1' and  b.FNumber = '"+number+"'");
		// 员工变动操作的id
		String bizdeId = entryInfo.getHrBizDefine().getId().toString();
		setEmpType(ctx, bizdeId, entryInfo);
		
		// 最后工作日=离职日期
		Date tobizDate = entryInfo.getBizDate();
		entryInfo.setLeftCompanyDate(tobizDate);
		
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(tobizDate);
		calendar.add(Calendar.DAY_OF_MONTH, 1);
		//禁用用户日期
		entryInfo.setForbidUserDate(calendar.getTime());
		
		try {
			/*//目标用工关系状态
			EmployeeTypeInfo employeeTypeInfo = EmployeeTypeFactory.getLocalInstance(ctx).getEmployeeTypeInfo("where name='"+bizeName+"'");
			entryInfo.setEmpType(employeeTypeInfo);
			//变动类型
			AffairActionReasonInfo affairActionReasonInfo = AffairActionReasonFactory.getLocalInstance(ctx).getAffairActionReasonInfo("where name='"+bizeName+"'");
			entryInfo.setAffairActionReason(affairActionReasonInfo);*/
			IRowSet rs = DbUtil.executeQuery(this.ctx, sql.toString());
			while (rs.next()) {

				// 直属上级id
				String lineId = rs.getString("lineId");
				entryInfo.put("lmanager", lineId);
				// 时薪
				String hourlyage = rs.getString("hourlyage");
				entryInfo.put("hwage", hourlyage);
				// 员工类别id
				String workerId = rs.getString("workerId");
				entryInfo.put("wcategory", workerId);
				// job2id
				String jobsId = rs.getString("jobsId");
				entryInfo.put("jobs", jobsId);
				// Admin Title
				String admintitle = rs.getString("admintitle");
				entryInfo.put("admintitle", admintitle);
				// Academic Title id
				String academicId = rs.getString("academicId");
				entryInfo.put("academictitle", academicId);
			}
		} catch (BOSException e) {
			e.printStackTrace();
		} catch (ORMCoreException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} 

		try {
			// 最后工作日期  最后工作日期就是离职日期
			this.checkConpanyLeftDate(entryInfo.getBizDate(), entryInfo.getBizDate(), SHRWebResource
					.getString("com.kingdee.eas.hr.emp.EmployeeBizResource", "label44", this.getContext()));
		} catch (SHRWebException var19) {
			EmployeeBizException e = new EmployeeBizException(EmployeeBizException.CONNOT_IMPORT_LINE, var19,
					new Object[] { var19.getMessage() });
			throw new ImportException(e.getMessage(), e);
		}

		FileServiceUtil fs = new FileServiceUtil();

		EmpBatchAffairBizException e1;
		try {
			EmpLaborRelationInfo labInfo = fs.getLaborRelation(ctx, entryInfo.getPerson());
			entryInfo.setEnterDate(labInfo.getEnterDate());
			billInfo.setApplier(pInfo);
			billInfo.setApplyDate(new Date());
			billInfo.setBillState(HRBillStateEnum.SUBMITED);
			billInfo.setExtendedProperty("isAddNew", "isAddNew");
			if (baseInfo.get("billNumber") != null) {
				billInfo.setNumber(baseInfo.get("billNumber").toString());
			}
			billInfo.setHrOrgUnit((HROrgUnitInfo) baseInfo.get("hrOrgUnit"));
			billInfo.setAdminOrg((AdminOrgUnitInfo) baseInfo.get("adminOrg"));
			FileServiceUtil.checkBillNumberExist(ctx, baseInfo, billInfo);
			entryInfo.setBill(billInfo);
			billInfo.getEntrys().clear();
			billInfo.getEntrys().add(entryInfo);
			this.checkCompulsoryRule(ctx, entryInfo);
			this.assignExist(ctx, entryInfo, billInfo);
			billInfo.setBizDate(entryInfo.getBizDate());
			// 需要目标用工关系状态的id
//			this.validEntryInfo(ctx, billInfo, entryInfo.getEmpType().getId().toString(),
//					entryInfo.getHrBizDefine().getId().toString());
			this.validEntryInfo(ctx, billInfo, entryInfo.getEmpType().getId().toString(),
					entryInfo.getHrBizDefine().getId().toString());
			this.setWorkFlow(billInfo);
			IObjectPK objectPK;
			IResignBizBill iHRAffairBizBill;
			if (BillEffectEnum.SUB.getAlias().equalsIgnoreCase(effectOprate)) {
				this.isHave = FileServiceUtil.checkWorkFlowInstance(ctx, billInfo,
						"com.kingdee.eas.hr.affair.app.ResignBizBillEditUIFunction");

				try {
					if (!this.isHave) {
						throw new ImportException(
								new EmpBatchAffairBizException(EmpBatchAffairBizException.EXCEPTION67));
					}

					iHRAffairBizBill = ResignBizBillFactory.getLocalInstance(ctx);
					objectPK = iHRAffairBizBill.submit(billInfo);
					entryInfo.setId(BOSUuid.read(objectPK.toString()));
					this.billForewarnRunTime(ctx, billInfo);
				} catch (EASBizException var14) {
					throw new BOSException(var14.getMessage());
				} catch (BOSException var15) {
					throw new BOSException(var15.getMessage());
				}
			} else {
				try {
					iHRAffairBizBill = ResignBizBillFactory.getLocalInstance(ctx);
					// 变动类型不能为空
					objectPK = iHRAffairBizBill.submitEffect(billInfo);
					entryInfo.setId(BOSUuid.read(objectPK.toString()));
					this.billForewarnRunTime(ctx, billInfo);
				} catch (EASBizException var12) {
					throw new BOSException(var12.getMessage());
				} catch (BOSException var13) {
					throw new BOSException(var13.getMessage());
				}
			}

		} catch (EASBizException var16) {
			e1 = new EmpBatchAffairBizException(EmpBatchAffairBizException.CANNOT_IMPORT_LINE, var16,
					new Object[] { var16.getMessage() });
			throw new ImportException(e1.getMessage(), e1);
		} catch (BOSException var17) {
			e1 = new EmpBatchAffairBizException(EmpBatchAffairBizException.CANNOT_IMPORT_LINE, var17,
					new Object[] { var17.getMessage() });
			throw new ImportException(e1.getMessage(), e1);
		} catch (UuidException var18) {
			e1 = new EmpBatchAffairBizException(EmpBatchAffairBizException.CANNOT_IMPORT_LINE, var18,
					new Object[] { var18.getMessage() });
			throw new ImportException(e1.getMessage(), e1);
		}
	}
	
	/**
	 * 根据变动操作给目标用工关系状态和变动类型赋值
	 */ 
	public void setEmpType(Context ctx, String hrBizDefineId, ResignBizBillEntryInfo entryInfo) {
		if(StringUtils.isEmpty(hrBizDefineId)) {
			return;
		}
		String sql = "select a.FEMPTYPEID ,b.FACTIONREASONID from T_HR_HRBizDefOutEmpType a left join T_HR_HRBizDefChangeReason b on a.FBIZDEFINEID = b.FHRBIZDEFINEID where a.fbizdefineid='"+hrBizDefineId+"'";
		//用工关系状态id
		String empTypeId = "";
		//变动类型id
		String affairReasonId = "";
		try {
			IRowSet rs = DbUtil.executeQuery(ctx, sql);
			while(rs.next()) {
				empTypeId = rs.getString("FEMPTYPEID");
				affairReasonId = rs.getString("FACTIONREASONID");
			}
			if(!StringUtils.isEmpty(empTypeId)) {
				EmployeeTypeInfo employeeTypeInfo = EmployeeTypeFactory.getLocalInstance(ctx).getEmployeeTypeInfo(new ObjectUuidPK(empTypeId));
				entryInfo.setEmpType(employeeTypeInfo);
			}
			if(!StringUtils.isEmpty(affairReasonId)) {
				AffairActionReasonInfo affairActionReasonInfo = AffairActionReasonFactory.getLocalInstance(ctx).getAffairActionReasonInfo(new ObjectUuidPK(affairReasonId));
				entryInfo.setAffairActionReason(affairActionReasonInfo);
			}
		} catch (BOSException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (EASBizException e) {
			e.printStackTrace();
		}
	}

	protected void assignExist(Context ctx, ResignBizBillEntryInfo entryInfo, CoreBaseInfo baseInfo)
			throws EASBizException, BOSException {
		if (entryInfo != null && entryInfo.getPerson() != null) {
			ResignBizBillInfo billInfo = (ResignBizBillInfo) baseInfo;
			String billId = billInfo.getId() == null ? null : billInfo.getId().toString();
			PersonInfo personInfo = entryInfo.getPerson();
			HROrgUnitInfo hrOrgUnitIfo = entryInfo.getHrOrgUnit();
			boolean isResignCheck = false;
			String paramNum = "IS_RESIGN_CHECK";
			if (hrOrgUnitIfo != null) {
				isResignCheck = HRParamUtil.getParamOfHR(ctx, paramNum, hrOrgUnitIfo.getId().toString());
			} else {
				isResignCheck = HRParamUtil.getParamOfHR(ctx, paramNum, (String) null);
			}

			String errorMsg = HRUtilExtend.resignAssignCheck(ctx, personInfo.getId().toString(), billId);
			if (errorMsg != null && !isResignCheck) {
				errorMsg = errorMsg.replaceAll("<br>", "");
				String[] msg = new String[] { errorMsg };
				throw new HRBaseException(HRBaseException.PERSONPLANISOVER, msg);
			}
		}
	}

	private void checkCompulsoryRule(Context ctx, ResignBizBillEntryInfo entryInfo)
			throws EASBizException, BOSException {
		if (entryInfo != null && entryInfo.getPerson() != null) {
			PersonInfo personInfo = entryInfo.getPerson();
			new CheckResultInfo();
			CheckResultInfo resultInfo = SHRAffairActionCheckTool.checkCompulsoryRule(ctx, personInfo, 4);
			List errorMsgRuleList = resultInfo.getErrorMsgRuleList();
			if (errorMsgRuleList != null && errorMsgRuleList.size() > 0) {
				StringBuffer errorInfo = new StringBuffer();
				int i = 0;

				for (int size = errorMsgRuleList.size(); i < size; ++i) {
					SHRCheckRuleInfo ruleInfo = (SHRCheckRuleInfo) errorMsgRuleList.get(i);
					String ruleDescription = ruleInfo.getRuleDescription();
					if (!StringUtils.isEmpty(ruleDescription)) {
						ruleDescription = ruleDescription.replaceAll("<br>", "");
					}

					if (i == 0) {
						errorInfo.append(ruleDescription);
					} else {
						errorInfo.append(";").append(ruleDescription);
					}
				}

				if (errorMsgRuleList.size() > 0) {
					String[] msg = new String[] { errorInfo.toString() };
					throw new HRBaseException(HRBaseException.PERSONPLANISOVER, msg);
				}
			}

		}
	}

	@Override
	public void verifyRow(BaseRowInfo row) throws ImportException {

		this.verifyRowSystem(row);

		Map<String, BaseColumnInfo> columnInfoMap = row.getMapColumnInfo();

		Iterator<Entry<String, BaseColumnInfo>> iterator = columnInfoMap.entrySet().iterator();
		Context ctx = this.getContext();
		HashMap validMap = new HashMap();

		try {
			String value;
			while (iterator.hasNext()) {
				BaseColumnInfo columnInfo = (BaseColumnInfo) ((Entry) iterator.next()).getValue();
				if (columnInfo != null) {

					value = row.getValueOfStringByIndex(columnInfo.getColumnIndex());

					validMap.put(columnInfo.getPropName(), value);
				}
			}
			validMap.put("UI", this.getImportUIPK());
			validMap.put("objNum", this.getImportNum());
			value = "/dynamic.do?method=submitEffect#uri=com.kingdee.eas.hr.affair.app.ResignBizBill.formAll";
			validMap.put("effectUrl", value);
			String errorMsg = "";
			ResignImportCheck ric = new ResignImportCheck();
			if (StringUtils.isEmpty(errorMsg)) {
				errorMsg = ric.checkNumber(ctx, validMap);
			}
			if (StringUtils.isEmpty(errorMsg)) {
				errorMsg = ric.checkPerson(ctx, validMap);
			}
			if (StringUtils.isEmpty(errorMsg)) {
				errorMsg = ric.checkHrBizDefineConfig(ctx, validMap);
			}
			// 变动类型不能为空
			/// if (StringUtils.isEmpty(errorMsg)) {
			// errorMsg = ric.checkActionReasonAndVariation(ctx, validMap);
			/// * */ }
			if (StringUtils.isEmpty(errorMsg)) {
				errorMsg = ric.checkOldEmployeeType(ctx, validMap);
			}
			// //目标用工状态不能为空
			// if (StringUtils.isEmpty(errorMsg)) {
			/// errorMsg = ric.checkNewEmployeeType(ctx, validMap);
			// }
			errorMsg = super.validCommonData(ctx, errorMsg, ric, validMap);

			if (!StringUtils.isEmpty(errorMsg)) {
				throw new ImportException(errorMsg);
			}
		} catch (ImportException var10) {
			throw var10;
		} catch (BOSException var11) {
			throw new ImportException(var11.getMessage(), var11);

		}

	}

	@Override
	public void checkConpanyLeftDate(Date bizDate, Date leftCompanyDate, String bizDateName) throws SHRWebException {
		if (bizDate == null) {
			throw new IllegalArgumentException(MessageFormat.format(
					SHRWebResource.getString("com.kingdee.eas.hr.emp.EmployeeBizResource", "label36", this.ctx),
					bizDateName));

		}
		// else if (leftCompanyDate == null) {
		// throw new
		// IllegalArgumentException(SHRWebResource.getString("com.kingdee.eas.hr.emp.EmployeeBizResource",
		// "label35", this.ctx));
		// /* */ }
		else {
			long between = DateUtil.dateDiff(leftCompanyDate, bizDate);
			long i = between / 86400000L;
			if (i < 0L || i > 1L) {

				EmployeeBizException e = new EmployeeBizException(EmployeeBizException.LAST_WORKDAY_MUST_CURRENT,
						new Object[] { bizDateName });
				throw new ImportException(e.getMessage(), e);
			}
		}
	}
}
