package com.kingdee.shr.ats.web.handler.util;


 
import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.ICommonBOSType;
import com.kingdee.bos.metadata.MetaDataLoaderFactory;
import com.kingdee.bos.metadata.MetaDataPK;
import com.kingdee.bos.metadata.entity.EntityObjectInfo;
import com.kingdee.eas.base.codingrule.CodingRuleManagerFactory;
import com.kingdee.eas.base.codingrule.ICodingRuleManager;
import com.kingdee.eas.basedata.org.*;
import com.kingdee.eas.basedata.person.IPerson;
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.common.EASBizException;
import com.kingdee.eas.framework.*;
import com.kingdee.eas.hr.base.HRBillStateEnum;
import com.kingdee.eas.hr.emp.PersonPositionCollection;
import com.kingdee.eas.hr.emp.PersonPositionFactory;
import com.kingdee.eas.hr.emp.PersonPositionInfo;
import com.kingdee.shr.base.syssetting.app.io.fileImport.BaseImportService;
import com.kingdee.shr.base.syssetting.app.io.fileImport.BaseResultInfo;
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.util.MetaDataUtil;
import com.kingdee.shr.shrimport.SHRFileTemplateInfo;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.util.*;

import static com.kingdee.shr.ats.web.util.file.Constants.hrOrg;

/**
 * 年假计划批量导入
 * @author kkuan
 *
 */
public class YearPlanFileService extends BaseImportService {
    private static Logger logger = Logger.getLogger(YearPlanFileService.class);

	private static final String  PERSONNUM = "Person.number";
	private static final String  HRORG =  "hrOrg";

    	@Override
    	public boolean isBatch(SHRFileTemplateInfo templateInfo) {
    		return true;
    	}

    	@Override
    	public boolean startBatchImport(Iterator<BaseRowInfo> rowIterator) {
			Context ctx = getContext();
			List<BaseRowInfo> list = new ArrayList<BaseRowInfo>(); //保存通过标准校验的数据

    		while (rowIterator.hasNext()) {
    			BaseRowInfo rowInfo = rowIterator.next();
    			try {
    				// 标准模板校验
    				super.verifyRow(rowInfo);
    			} catch (ImportException e) { 
    				// 有异常说明校验不通过
    				BaseResultInfo resultInfo = new BaseResultInfo(rowInfo);
    				resultInfo.setSuccess(false);
    				resultInfo.setMessage(e.getMessage());
    				resultInfo.setE(e);
    				super.getMonitor().completeRow(resultInfo);
    				continue;
    			}
    			list.add(rowInfo);
    		}

			//根据业务组织分组; 同一业务组织的放在一张单上;
			LinkedHashMap<String, List<BaseRowInfo>> rowMap = new LinkedHashMap ();
			try {
				IPerson perIns  = PersonFactory.getLocalInstance(ctx);
				for (int i = 0; i < list.size(); i++) {
					BaseRowInfo row = list.get(i);
					String personNum = row.getValueOfString(PERSONNUM);
					PersonCollection personCollection = null;
					try {
						personCollection = perIns.getPersonCollection("where  number = '" + personNum + "' or name = '" + personNum + "'");
					} catch (BOSException e) {
						throw new RuntimeException(e);
					}
					PersonInfo personInfo = personCollection.get(0);
					PersonPositionInfo positionInfo = this.getAdminOrgUnit(ctx, personInfo.getId().toString());
					HROrgUnitInfo hrOrgUnit = positionInfo.getHrOrgUnit();
					if(null == hrOrgUnit){
						throw new RuntimeException("人员业务组织信息为空,请检查!");
					}
					String  hrOrg  = hrOrgUnit.getNumber().toString();
					 
					if(rowMap.containsKey(hrOrg)){
						List<BaseRowInfo>  dataList =    rowMap.get(hrOrg);
						dataList.add(row);
					}else{
						List<BaseRowInfo>  dataList =  new ArrayList();
						dataList.add(row);
						rowMap.put(hrOrg,dataList);
					}
				}

			} catch (BOSException e) {
				throw new RuntimeException(e);
			}

			int sucessCount = 0; //成功数量，通过业务校验即认为是成功。
			int count = super.getMonitor().getProgress().getCount(); // 导入的总数量
			CoreBaseCollection billCol = new CoreBaseCollection(); //分录
			String entityName =  "com.kingdee.eas.jiaotou.app.NJJH";
			for (Map.Entry<String, List<BaseRowInfo>> entry : rowMap.entrySet()) {
				List<BaseRowInfo> rowList = entry.getValue();
				String hrOrg = entry.getKey();
				CoreBaseInfo billInfo = null; 
				 try {
					 billInfo = createInfo(entityName);
				} catch (Exception e1) {
					e1.printStackTrace();
				}

				CoreBaseCollection coll = new CoreBaseCollection(); //分录
				try {
					IHROrgUnit orgIns = HROrgUnitFactory.getLocalInstance(ctx);
					HROrgUnitCollection hrOrgCol = orgIns.getHROrgUnitCollection("where  number = '" + hrOrg + "' or name = '" + hrOrg + "'");
					HROrgUnitInfo hrOrgUnitInfo = hrOrgCol.get(0);
					billInfo.put("hrOrgUnit",hrOrgUnitInfo);
					String newNumber = getNewNumber(ctx, billInfo);
					billInfo.put("number",newNumber);
					billInfo.put("billState", HRBillStateEnum.SAVED_VALUE);
				} catch (BOSException e) {
					throw new RuntimeException(e);
				}
				for (int i = 0; i < rowList.size(); i++) {
					BaseRowInfo row = rowList.get(i);
					try {
						String personNum = row.getValueOfString(PERSONNUM);
						 IPerson perIns = PersonFactory.getLocalInstance(ctx);
						PersonCollection personCollection = perIns.getPersonCollection("where  number = '" + personNum + "' or name = '" + personNum + "'");
						PersonInfo personInfo = personCollection.get(0);


						CoreBaseInfo  transRowToObejct = super.transRowToObejct(row);
						doCustomVerifyRow(transRowToObejct); //业务校验
						PersonPositionInfo positionInfo = this.getAdminOrgUnit(ctx, personInfo.getId().toString());
					 
						AdminOrgUnitInfo personDep = positionInfo.getPersonDep();
						PositionInfo primaryPosition = positionInfo.getPrimaryPosition();
						transRowToObejct.put("person",personInfo);
						transRowToObejct.put("position",primaryPosition);
						transRowToObejct.put("adminOrg",personDep);
						
						coll.add(transRowToObejct); // 将每一行数据存入coll中，可以最后做批量保存
						sucessCount++;
					} catch (ImportException e) {
						BaseResultInfo resultInfo = new BaseResultInfo(row);
						resultInfo.setSuccess(false);
						resultInfo.setMessage(e.getMessage());
						resultInfo.setE(e);
						super.getMonitor().completeRow(resultInfo);
					} catch (BOSException e) {
						throw new RuntimeException(e);
					}
				}
				billInfo.put("entrys", coll);
				billCol.add(billInfo);

			}
    		if (billCol.size() > 0) {
    			try {
					ICoreBase iCoreBase = MetaDataUtil.getBizInterface(entityName);
					iCoreBase.save(billCol);
//					iCoreBase.submit(billCol);
    			} catch (Exception e) {
    				//批量操作异常后，直接将成功数量设置为0
    				super.getMonitor().getProgress().setFinish(count); // 完成数
    				super.getMonitor().getProgress().setSuccess(0); // 设置成功数为0
    				e.printStackTrace(); //打出日志，无法在导入报告中看到，只能查看apusic日志
    				return true;
    			}
    		}
    		// 最后设置成功的数量和完成数量 
    		super.getMonitor().getProgress().setFinish(count); // 完成数
    		super.getMonitor().getProgress().setSuccess(sucessCount); // 成功数量 ，最终保证：失败的数量+成功的数量 = 导入的总数量
    		return true;
    	}

    	/**
    	 * 业务校验，自行实现，如果校验不通过请抛出ImportException
    	 * @return
    	 */
    	private void doCustomVerifyRow(CoreBaseInfo transRowToObejct) throws ImportException {

    	}

	protected void verifyRowBiz(BaseRowInfo row) throws ImportException {
		Context ctx = getContext();
		try {
			IHROrgUnit orgIns = null;
//			String hrOrg = row.getValueOfString(HRORG);
//			orgIns = HROrgUnitFactory.getLocalInstance(ctx);
//			boolean  exists= orgIns.exists("where  number = '" + hrOrg + "' or name = '" + hrOrg + "'");
//			if (!exists  ) {
//				throw new ImportException("业务组织填写错误,"+hrOrg+"未找到对应数据");
//			}
			String personNum = row.getValueOfString(PERSONNUM);
			IPerson perIns = PersonFactory.getLocalInstance(ctx);
			boolean  exists2=  perIns.exists("where  number = '" + personNum + "' or name = '" + personNum + "'");
			if (!exists2  ) {
				throw new ImportException("人员填写错误,"+personNum+"未找到对应数据");
			}
		} catch (BOSException e) {
			throw new RuntimeException(e);
		} catch (EASBizException e) {
			throw new RuntimeException(e);
		}

	}
	
	
	
	private CoreBaseInfo createInfo(String entityName) throws Exception {
		String clazz = MetaDataLoaderFactory.getRemoteMetaDataLoader().getEntity(new MetaDataPK(entityName))
				.getObjectValueClass();
		Class modelClass = Class.forName(clazz);
		CoreBaseInfo model = (CoreBaseInfo) modelClass.newInstance();
		if (!StringUtils.isEmpty(entityName)) {
			MetaDataPK metaDataPK = new MetaDataPK(entityName);
			EntityObjectInfo entityInfo = MetaDataLoaderFactory.getRemoteMetaDataLoader().getEntity(metaDataPK);
			if (entityInfo.isDynamic() && model instanceof ICommonBOSType) {
				ICommonBOSType commonObject = (ICommonBOSType) model;
				commonObject.setBOSType(entityInfo.getType());
				commonObject.setPK(metaDataPK);
			}
		}

		return model;
	}


	/**
	 * 根据编码规则获取单据编码
	 *
	 * @param ctx
	 * @param info
	 * @return
	 */
	public static String getNewNumber(Context ctx, CoreBaseInfo info) {
		String number = "";
		ICodingRuleManager iCodingRuleManager = null;
		OrgUnitInfo orgUnit = (OrgUnitInfo) info.get("hrOrgUnit");
		if (orgUnit == null) {
			return null;
		}
		try {
			iCodingRuleManager = CodingRuleManagerFactory.getLocalInstance(ctx);
			if (iCodingRuleManager.isExist(info, orgUnit.getId().toString())) {
				number = iCodingRuleManager.getNumber(info, orgUnit.getId().toString());
			} else {
				return null;
			}
		} catch (EASBizException e) {
			e.printStackTrace();
		} catch (BOSException e) {
			e.printStackTrace();
		}

		return number;
	}



	public PersonPositionInfo getAdminOrgUnit(Context ctx, String personID) {
		if (personID == null) {
			return null;
		} else {
			PersonPositionInfo personPositionInfo = null;
			StringBuffer oqlb = new StringBuffer();
			oqlb.append("select ");
			oqlb.append("id,");
			oqlb.append("enterDate,");
			oqlb.append("jobGrade.id,");
			oqlb.append("tryoutMonth,");
			oqlb.append("jobGrade.name,");
			oqlb.append("jobLevel.id,");
			oqlb.append("jobLevel.name,");
			oqlb.append("hrOrgUnit.id,");
			oqlb.append("hrOrgUnit.number,");
			oqlb.append("person.number,");
			oqlb.append("person.name,");
			oqlb.append("person.employeeType.name,");
			oqlb.append("personDep.id,");
			oqlb.append("personDep.name,");
			oqlb.append("personDep.number,");
			oqlb.append("personDep.longnumber,");
			oqlb.append("personDep.displayName,");
			oqlb.append("primaryPosition.id,");
			oqlb.append("primaryPosition.name,");
			oqlb.append("primaryPosition.number,");
			oqlb.append("primaryPosition.job.id,");
			oqlb.append("primaryPosition.job.name");
			oqlb.append(" where person.id='");
			oqlb.append(personID);
			oqlb.append("'");
			PersonPositionCollection c = null;

			try {
				c = PersonPositionFactory.getLocalInstance(ctx).getPersonPositionCollection(oqlb.toString());
			} catch (BOSException var7) {
				var7.printStackTrace();
			}

			if (c != null && c.size() > 0) {
				personPositionInfo = c.get(0);
			}

			return personPositionInfo;
		}
	}
}
