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

import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;

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.metadata.entity.EntityViewInfo;
import com.kingdee.bos.metadata.entity.FilterInfo;
import com.kingdee.bos.metadata.entity.FilterItemInfo;
import com.kingdee.bos.metadata.entity.SelectorItemCollection;
import com.kingdee.bos.metadata.entity.SelectorItemInfo;
import com.kingdee.bos.orm.ORMCoreException;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.basedata.org.AdminOrgUnitInfo;
import com.kingdee.eas.basedata.org.HROrgUnitInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.framework.CoreBaseInfo;
import com.kingdee.eas.hr.affair.FluctuationBizBillEntryInfo;
import com.kingdee.eas.hr.affair.FluctuationBizBillFactory;
import com.kingdee.eas.hr.affair.FluctuationBizBillInfo;
import com.kingdee.eas.hr.affair.IFluctuationBizBill;
import com.kingdee.eas.hr.base.AffairActionReasonCollection;
import com.kingdee.eas.hr.base.AffairActionReasonFactory;
import com.kingdee.eas.hr.base.BillEffectEnum;
import com.kingdee.eas.hr.base.EmpTypeEnum;
import com.kingdee.eas.hr.base.EmployeeTypeInfo;
import com.kingdee.eas.hr.base.HRBillStateEnum;
import com.kingdee.eas.hr.base.HRBizDefEmpTypeCollection;
import com.kingdee.eas.hr.base.HRBizDefineCollection;
import com.kingdee.eas.hr.base.HRBizDefineFactory;
import com.kingdee.eas.hr.base.HRBizDefineInfo;
import com.kingdee.eas.hr.base.app.EmpPostExperienceHisHelper;
import com.kingdee.eas.hr.emp.EmpBatchAffairBizException;
import com.kingdee.shr.base.syssetting.app.io.fileImport.BaseColumnInfo;
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.fileImport.ValueCovertUtils;
import com.kingdee.shr.base.syssetting.app.io.impl.FluctuationBizBillHrManImportService;
import com.kingdee.shr.base.syssetting.app.io.impl.util.FileServiceUtil;
import com.kingdee.shr.base.syssetting.app.io.impl.util.FluctuationImportCheck;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.ml.SHRWebResource;
import com.kingdee.eas.hr.org.JobGradeInfo;
import com.kingdee.eas.hr.org.JobLevelInfo;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import com.kingdee.eas.base.permission.UserInfo;
import com.kingdee.eas.basedata.person.PersonCollection;
import com.kingdee.eas.basedata.person.PersonFactory;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.basedata.org.PositionInfo;

/**
 * @author ISSUSER 调动单导入
 * FluctuationBizBillHrManImportService
 */
public class FluctImport extends FluctuationBizBillHrManImportService {
	String errorMsg;
	Context ctx = SHRContext.getInstance().getContext();

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

		String effectOprate = baseInfo.get("effectOprate").toString();
		Context ctx = this.getContext();
		UserInfo uInfo = (UserInfo) ctx.get("UserInfo");
		PersonInfo pInfo = uInfo.getPerson();
		Date now = new Date();
		FluctuationBizBillInfo billInfo = new FluctuationBizBillInfo();
		FluctuationBizBillEntryInfo entryInfo = (FluctuationBizBillEntryInfo) baseInfo;
		entryInfo.setOldAdminOrg((AdminOrgUnitInfo) null);
		entryInfo.setOldPosition((PositionInfo) null);
		entryInfo.setOldEmpType((EmployeeTypeInfo) null);
		
		String number = entryInfo.getString("empnumber");
		// 新增字段的导入   通过工号查询员工信息
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT top 1 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' and fassignType = '1' group by fpersonid ) c on a.fpersonid=c.fpersonid  \r\n"
						+ "  and  a.fleffdt=c.fleffdt where a.FIsLatestInAday ='1' and a.fassignType = '1' and  b.FNumber = '"+number+"'");
		try {
			//默认变动操作为公司内调动
			HRBizDefineCollection hrBizDefineColl = HRBizDefineFactory.getLocalInstance(ctx).getHRBizDefineCollection("where number = 'SHR22'");
			if(hrBizDefineColl != null && hrBizDefineColl.size()>0) {
				entryInfo.setHrBizDefine(hrBizDefineColl.get(0));
			}
			//默认变动类型为调动调出
			AffairActionReasonCollection affairActionReasonColl = AffairActionReasonFactory.getLocalInstance(ctx).getAffairActionReasonCollection("where number = '0207'");
			if(affairActionReasonColl != null && affairActionReasonColl.size()>0) {
				entryInfo.setAffairActionReason(affairActionReasonColl.get(0));
			}
			
			IRowSet rs = DbUtil.executeQuery(this.ctx, sql.toString());
			while (rs.next()) {
				// 直属上级id
				String lineId=rs.getString("lineId");
				entryInfo.put("Clmanager", lineId);
				//时薪
				String hourlyage=rs.getString("hourlyage");
				entryInfo.put("Chrate", hourlyage);
				//员工类别id
				String workerId=rs.getString("workerId");
				entryInfo.put("Workercategory", workerId);
				
				//job2id
				String jobsId=rs.getString("jobsId");
				String jobsStr = entryInfo.getString("jobs");
				if(StringUtils.isBlank(jobsStr)) {
					entryInfo.put("jobs", jobsId);
				}
				
				//Admin Title
				String adminTitle =rs.getString("admintitle");
				String adminTitleStr = entryInfo.getString("Admintitle");
				if(StringUtils.isBlank(adminTitleStr)) {
					entryInfo.put("Admintitle", adminTitle);
				}
				
				//Academic Title id
				String academicId=rs.getString("academicId");		
				String academicTitleStr=entryInfo.getString("academictitle");
				if(StringUtils.isBlank(academicTitleStr)) {
					entryInfo.put("academictitle", academicId);
				}
			}
		} catch (BOSException e) {
			e.printStackTrace();
		} catch (ORMCoreException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} 

		EmpBatchAffairBizException e1;
		try {
			HRBizDefineInfo hrBizDefineInfo = HRBizDefineFactory.getLocalInstance(ctx)
					.getHRBizDefineInfo(new ObjectUuidPK(entryInfo.getHrBizDefine().getId()));
			EmpTypeEnum empTypeEnum = hrBizDefineInfo.getEmpTypeField();
			if (empTypeEnum.getValue() == 10) {
				entryInfo.setEmpType((EmployeeTypeInfo) null);
			}

			JobLevelInfo jobLevel = entryInfo.getJobLevel();
			JobGradeInfo jobGrade = entryInfo.getJobGrade();
			EmpPostExperienceHisHelper.fillHistory(ctx, entryInfo.getPerson().getId().toString(),
					entryInfo.getBizDate(), entryInfo);
			entryInfo.setJobLevel(jobLevel);
			entryInfo.setJobGrade(jobGrade);
			billInfo.setApplier(pInfo);
			billInfo.setApplyDate(now);
			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.validEntryInfo(ctx, billInfo, entryInfo.getEmpType().getId().toString(),
					entryInfo.getHrBizDefine().getId().toString());
		} catch (BOSException var17) {
			e1 = new EmpBatchAffairBizException(EmpBatchAffairBizException.CANNOT_IMPORT_LINE, var17,
					new Object[] { var17.getMessage() });
			throw new ImportException(e1.getMessage(), e1);
		} catch (EASBizException var18) {
			e1 = new EmpBatchAffairBizException(EmpBatchAffairBizException.CANNOT_IMPORT_LINE, var18,
					new Object[] { var18.getMessage() });
			throw new ImportException(e1.getMessage(), e1);
		}

		this.setWorkFlow(billInfo);
		IFluctuationBizBill iHRAffairBizBill;
		IObjectPK objectPK;
		if (BillEffectEnum.SUB.getAlias().equalsIgnoreCase(effectOprate)) {
			this.isHave = FileServiceUtil.checkWorkFlowInstance(ctx, billInfo,
					"com.kingdee.eas.hr.affair.app.FluctuationBizBillEditUIFunction");

			try {
				if (!this.isHave) {
					throw new ImportException(SHRWebResource.getString("com.kingdee.eas.hr.emp.EmployeeResource",
							"CUR_USER_NOT_MATCH_PROCESS", ctx));
				}

				iHRAffairBizBill = FluctuationBizBillFactory.getLocalInstance(ctx);
				objectPK = iHRAffairBizBill.submit(billInfo);
				entryInfo.setId(BOSUuid.read(objectPK.toString()));
			} catch (EASBizException var15) {
				e1 = new EmpBatchAffairBizException(EmpBatchAffairBizException.CANNOT_IMPORT_LINE, var15,
						new Object[] { var15.getMessage() });
				throw new ImportException(e1.getMessage(), e1);
			} catch (BOSException var16) {
				e1 = new EmpBatchAffairBizException(EmpBatchAffairBizException.CANNOT_IMPORT_LINE, var16,
						new Object[] { var16.getMessage() });
				throw new ImportException(e1.getMessage(), e1);
			}
		} else {
			try {
				iHRAffairBizBill = FluctuationBizBillFactory.getLocalInstance(ctx);
				objectPK = iHRAffairBizBill.submitEffect(billInfo);
				entryInfo.setId(BOSUuid.read(objectPK.toString()));
			} catch (EASBizException var13) {
				e1 = new EmpBatchAffairBizException(EmpBatchAffairBizException.CANNOT_IMPORT_LINE, var13,
						new Object[] { var13.getMessage() });
				throw new ImportException(e1.getMessage(), e1);
			} catch (BOSException var14) {
				e1 = new EmpBatchAffairBizException(EmpBatchAffairBizException.CANNOT_IMPORT_LINE, var14,
						new Object[] { var14.getMessage() });
				throw new ImportException(e1.getMessage(), e1);
			}
		}
	}

	@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("hrBizDefine", "公司内调动");
			validMap.put("affairActionReason", "0207##调动调出");

			validMap.put("UI", this.getImportUIPK());
			validMap.put("objNum", this.getImportNum());
			value = "/dynamic.do?method=submitEffect#uri=com.kingdee.eas.hr.affair.app.FluctuationBizBill.formAll";
			validMap.put("effectUrl", value);
			String errorMsg = "";
			FluctuationImportCheck fic = new FluctuationImportCheck();
			FluctuationBizBillInfo checkInfo = new FluctuationBizBillInfo();
			if (StringUtils.isEmpty(errorMsg)) {
				errorMsg = fic.checkNumber(ctx, validMap, checkInfo);
			}

			if (StringUtils.isEmpty(errorMsg)) {
				errorMsg = fic.checkPerson(ctx, validMap);
			}

			if (StringUtils.isEmpty(errorMsg)) {
				errorMsg = fic.checkHrBizDefineConfig(ctx, validMap);
			}

			if (StringUtils.isEmpty(errorMsg)) {
				errorMsg = fic.checkActionReasonAndVariation(ctx, validMap);
			}

			if (StringUtils.isEmpty(errorMsg)) {
				errorMsg = fic.checkPositionAndOrgAndCompany(ctx, validMap);
			}

			if (StringUtils.isEmpty(errorMsg)) {
				errorMsg = fic.checkOldEmployeeType(ctx, validMap);
			}

			errorMsg = super.validCommonData(ctx, errorMsg, fic, validMap);
			if (!StringUtils.isEmpty(errorMsg)) {
				throw new ImportException(errorMsg);
			}
		} catch (ImportException var11) {
			throw var11;
		} catch (BOSException var12) {
			throw new ImportException(var12.getMessage(), var12);
		}
	}
	
}
