package com.kingdee.eas.custom.certification.utils;

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.function.WfEventListenerStateManager;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.base.permission.UserFactory;
import com.kingdee.eas.base.permission.UserInfo;
import com.kingdee.eas.basedata.org.AdminOrgUnitFactory;
import com.kingdee.eas.basedata.org.AdminOrgUnitInfo;
import com.kingdee.eas.basedata.org.PositionFactory;
import com.kingdee.eas.basedata.org.PositionInfo;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.sendmessage.utils.SendMessageUtils;
import com.kingdee.eas.framework.CoreBaseInfo;
import com.kingdee.eas.hr.affair.*;
import com.kingdee.eas.hr.base.ApproveTypeEnum;
import com.kingdee.eas.hr.base.EmpPosOrgRelationCollection;
import com.kingdee.eas.hr.base.EmpPosOrgRelationFactory;
import com.kingdee.eas.hr.base.HRBillStateEnum;
import com.kingdee.eas.hr.emp.LabContractFirstPartyInfo;
import com.kingdee.eas.hr.emp.PersonContactMethodInfo;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.base.syssetting.exception.ShrWebBizException;
import com.kingdee.shr.certificationservice.*;
import com.kingdee.shr.certificationservice.app.CertificateBillSource;
import com.kingdee.shr.certificationservice.app.CertificateStatusEnum;
import com.kingdee.shr.certificationservice.app.CertificationDrawUpMode;
import com.kingdee.util.StringUtils;
import com.kingdee.util.UuidException;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.*;

public class CreateCertification {


    private static Logger logger = LoggerFactory.getLogger(CreateCertification.class);


    /**
     * 根据离职单据id生成离职证明
     * @param ctx
     * @param billId
     * @throws BOSException
     * @throws EASBizException
     */
    public static void createCertificationById(Context ctx, String billId,int auditType) throws BOSException, EASBizException {
		IResignBizBill bizIns = ResignBizBillFactory.getLocalInstance(ctx);
		// 离职单
		ResignBizBillInfo resiInfo = bizIns.getResignBizBillInfo(new ObjectUuidPK(billId));
		ResignBizBillEntryCollection entrys = resiInfo.getEntrys();

		// List<String> billList = new ArrayList();
		for (int i = 0; i < entrys.size(); i++) {
			ResignBizBillEntryInfo resiEn = entrys.get(i);
			createCert(ctx, resiEn.getId().toString(),auditType);
		}
	}

	/**
	 * 
	 * @param ctx
	 * @param entryId
	 */
	public static void createCert(Context ctx, String entryId,int auditType) {
		List<String> certIds = new ArrayList();
		HRCertificationBillInfo quitElecInfo = new HRCertificationBillInfo();
        HRCertificationBillInfo   socialElecInfo = new HRCertificationBillInfo();

		try {
			IResignBizBillEntry entryIns = ResignBizBillEntryFactory.getLocalInstance(ctx);
			ResignBizBillEntryInfo resiEn = entryIns.getResignBizBillEntryInfo(new ObjectUuidPK(entryId));
			//
			IResignBizBill billIns = ResignBizBillFactory.getLocalInstance(ctx);
			ResignBizBillInfo resiInfo = billIns.getResignBizBillInfo(new ObjectUuidPK(resiEn.getBill().getId()));
			// 人员
			PersonInfo person = resiEn.getPerson();
			quitElecInfo.setPerson(person);
			socialElecInfo.setPerson(person);
			// 人事业务组织
			quitElecInfo.setHrOrgUnit(resiInfo.getHrOrgUnit());
			socialElecInfo.setHrOrgUnit(resiInfo.getHrOrgUnit());
			
			//直接审批
			if(auditType == 1){
				// 状态
				quitElecInfo.setBillState(HRBillStateEnum.SAVED);
				socialElecInfo.setBillState(HRBillStateEnum.SAVED);
				quitElecInfo.setApproveType(ApproveTypeEnum.DIRECT);
				socialElecInfo.setApproveType(ApproveTypeEnum.DIRECT);
			}else{
				quitElecInfo.setBillState(HRBillStateEnum.SUBMITED);
				socialElecInfo.setBillState(HRBillStateEnum.SUBMITED);
				quitElecInfo.setApproveType(ApproveTypeEnum.WORKFLOW);
				socialElecInfo.setApproveType(ApproveTypeEnum.WORKFLOW);
			}
			// 制单日期
			quitElecInfo.setApplyDate(new Date());
			socialElecInfo.setApplyDate(new Date());
			// 审批日期
//			quitElecInfo.setBizDate(new Date());
//			socialElecInfo.setBizDate(new Date());
			// 制单人
			quitElecInfo.setApplier(resiInfo.getApplier());
			socialElecInfo.setApplier(resiInfo.getApplier());
			// 单据来源人事
			quitElecInfo.setBillSource(CertificateBillSource.CertificateEmp);
			socialElecInfo.setBillSource(CertificateBillSource.CertificateEmp);
			//
//			 quitElecInfo.put("billType", CertificateBillType.Common);
//			socialElecInfo.put("billType", CertificateBillType.Common);
			// 源单id
			quitElecInfo.put("souBillId", resiInfo.getId());
			socialElecInfo.put("souBillId", resiInfo.getId());
			   //是否自动生成
	        quitElecInfo.put("isAutoGen", true);
	        socialElecInfo.put("isAutoGen", true);
	      //是否发送
	        quitElecInfo.put("isSend", false);
	        socialElecInfo.put("isSend", false);
			// 快递
			quitElecInfo.setNeedExpress(false);
			socialElecInfo.setNeedExpress(false);
			// 
			quitElecInfo.setFreeDate(resiEn.getBizDate());
			socialElecInfo.setFreeDate(resiEn.getBizDate());
			// 开具状态
			quitElecInfo.setCertificationStatus(CertificateStatusEnum.UnCertificated);
			socialElecInfo.setCertificationStatus(CertificateStatusEnum.UnCertificated);

			IHRCertificationBillType cerIns = HRCertificationBillTypeFactory.getLocalInstance(ctx);
			if (ObjectUtils.isNotEmpty(resiEn.get("quittemp"))) {
				CertificationTempletInfo tempInfo = (CertificationTempletInfo) resiEn.get("quittemp");
				setTempType(ctx, quitElecInfo, tempInfo);
			}
			if (ObjectUtils.isNotEmpty(resiEn.get("socialtemp"))) {
				CertificationTempletInfo tempInfo = (CertificationTempletInfo) resiEn.get("socialtemp");
				setTempType(ctx, socialElecInfo, tempInfo);
			}

			// reason 申请原因 实体
			ICertificationApplyReason reasonIns = CertificationApplyReasonFactory.getLocalInstance(ctx);
			CertificationApplyReasonInfo reasonInfo = reasonIns.getCertificationApplyReasonInfo(" where name = '离职'");
			quitElecInfo.setReason(reasonInfo);
			socialElecInfo.setReason(reasonInfo);
			// expectedTime 期望日期
			// freeDate 劳动关系解除日期
			// drawUpMode 开具形式 电子证明
			quitElecInfo.setDrawUpMode(CertificationDrawUpMode.electronic);
			socialElecInfo.setDrawUpMode(CertificationDrawUpMode.electronic);
			// labContractFirstParty 证明开具主体
			quitElecInfo.setLabContractFirstParty(resiEn.get("labContractFirstParty") == null ? null
					: (LabContractFirstPartyInfo) resiEn.get("labContractFirstParty"));
			socialElecInfo.setLabContractFirstParty(resiEn.get("labContractFirstParty") == null ? null
					: (LabContractFirstPartyInfo) resiEn.get("labContractFirstParty"));
			// certificationStatus 证明状态
			quitElecInfo.put("genFromResign", true);
			socialElecInfo.put("genFromResign", true);

			Map<String, Object> pData = new HashMap<String, Object>();
			ResignBillUtil.assemblePersonInfoDataMap(ctx, pData, person.getId().toString());
			if (ObjectUtils.isNotEmpty(pData)) {
				// 联系方式
				setContact(quitElecInfo, pData.get("personContact"));
				setContact(socialElecInfo, pData.get("personContact"));
				// adminOrg 所属行政组织
				quitElecInfo
						.setAdminOrg(pData.get("adminOrg") == null ? null : (AdminOrgUnitInfo) pData.get("adminOrg"));
				socialElecInfo
						.setAdminOrg(pData.get("adminOrg") == null ? null : (AdminOrgUnitInfo) pData.get("adminOrg"));
				// position 职位
				quitElecInfo.setPosition(pData.get("position") == null ? null : (PositionInfo) pData.get("position"));
				socialElecInfo.setPosition(pData.get("position") == null ? null : (PositionInfo) pData.get("position"));
				// enterDate 入职日期
				quitElecInfo.put("enterDate", pData.get("enterDate"));
				socialElecInfo.put("enterDate", pData.get("enterDate"));
			}

			IHRCertificationBill certIns;

			certIns = HRCertificationBillFactory.getLocalInstance(ctx);
			// 离职单如果选择了是否需要电子证明;用于判断;
			if (resiEn.getBoolean("quitElec")) {
				updateOtherInfo(ctx,quitElecInfo);
				IObjectPK addnew = certIns.addnew(quitElecInfo);
				String keyValue = StringUtils.cnulls(addnew.getKeyValue("id"));
				certIds.add(keyValue);
			}
			// 社保结算证明
			if (resiEn.getBoolean("socialElec")) {
				updateOtherInfo(ctx,quitElecInfo);
				IObjectPK addnew = certIns.addnew(socialElecInfo);
				String keyValue = StringUtils.cnulls(addnew.getKeyValue("id"));
				certIds.add(keyValue);
			}

			if (certIds.size() > 0) {
				if(auditType == 1 ){
					auditCertiBill(ctx, certIds);
				}else{
					submitCertific(ctx, certIds);
				}
			}
		} catch (BOSException e) {
			e.printStackTrace();
		} catch (EASBizException e) {
			e.printStackTrace();
		}
    }



	/**
	 * 通过模板字段设置模板类型
	 * @throws EASBizException
	 * @throws BOSException
	 */
	private static void setTempType(Context ctx, HRCertificationBillInfo certInfo, CertificationTempletInfo tempInfo)
			throws EASBizException, BOSException {
		ICertificationTemplet tempIns = CertificationTempletFactory.getLocalInstance(ctx);
		tempInfo = tempIns.getCertificationTempletInfo(new ObjectUuidPK(tempInfo.getId()));
		certInfo.setCertificationTemplet(tempInfo);
		IHRCertificationBillType cerIns = HRCertificationBillTypeFactory.getLocalInstance(ctx);
		if (ObjectUtils.isNotEmpty(tempInfo.getCertificationBillType())) {
			HRCertificationBillTypeInfo typeInfo = cerIns
					.getHRCertificationBillTypeInfo(new ObjectUuidPK(tempInfo.getCertificationBillType().getId()));
			if (null != typeInfo) {
				certInfo.setCertificationBillType(typeInfo);
			}
		}
    }

    /**
     * 联系方式
     */
    private static void setContact(HRCertificationBillInfo elecProofInfo ,Object cmInfoObj) {
        if( ObjectUtils.isNotEmpty(cmInfoObj) ) {
            PersonContactMethodInfo cmInfo = (PersonContactMethodInfo)cmInfoObj;
            //email 联系邮箱
            elecProofInfo.setEmail(cmInfo.getEmail());
            //手机号码  nCell
            elecProofInfo.setNCell( cmInfo.getNCell());
            elecProofInfo.setCallPhone(cmInfo.getNCell());
            //国际区号  globalRoaming
            elecProofInfo.setGlobalRoaming(cmInfo.getGlobalRoaming());
        }
    }

    /**
     * 审批证明单据
     */
    private static void  auditCertiBill(Context ctx, List<String> bills) {
        try {
            IHRCertificationBill certiIns = HRCertificationBillFactory.getLocalInstance(ctx);
            for(int i = 0;i<bills.size();i++) {
                certiIns.auditEntryEffect(BOSUuid.read(bills.get(i)));
            }
//			Thread.sleep(3000L);
//          batchCompanySign (ctx,billList);
        } catch (BOSException e ) {
            e.printStackTrace();
        } catch (EASBizException e) {
            e.printStackTrace();
        }
    }



	private static void  submitCertific(Context ctx, List<String> bills) {
		try {
			for(int i = 0;i<bills.size();i++) {
				exeSubmit(ctx,bills.get(i));
				Thread.sleep(2000);
			}
		} catch (BOSException e ) {
			e.printStackTrace();
		} catch (EASBizException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

    /**
     * 签署
     * @param ctx
     */
    public static void batchCompanySign (Context ctx , List<String> billList)
            throws SHRWebException, InterruptedException, BOSException, EASBizException, IOException {
        try {
            IECertificationOptFacade eCertificationOptFacade = ECertificationOptFacadeFactory.getLocalInstance(ctx);
            for (int i = 0; i < billList.size(); i++) {
            	eCertificationOptFacade.createECertification(BOSUuid.read(billList.get(i)), true);
            	Thread.sleep(2000L);
            }
        } catch (EASBizException var15) {
            logger.error(var15.getMessage(), var15);
        } catch (BOSException var16) {
            logger.error(var16.getMessage(), var16);
        } catch (Exception var17) {
            logger.error(var17.getMessage(), var17);
        }
		


    }



    /**
     * 发送消息
     * @param ctx
     * @param billList
     * @throws BOSException
     * @throws EASBizException
     * @throws IOException
     */
    public static void sendMsg(Context ctx, List<String> billList) throws BOSException, EASBizException, IOException, ShrWebBizException {
        for(int i = 0;i<billList.size();i++) {
			SendMessageUtils.sendMessage(ctx, billList.get(i));
        }
    }


	/**
	 * 更新其他信息
	 * 提交前执行
	 * @param ctx
	 * @param certificationBillinfo
	 */
	private  static  void updateOtherInfo(Context ctx, HRCertificationBillInfo certificationBillinfo) {
		try {
			if (certificationBillinfo.getAdminOrg() != null) {
				AdminOrgUnitInfo adminorg = AdminOrgUnitFactory.getLocalInstance(ctx).getAdminOrgUnitInfo(
						new ObjectUuidPK(BOSUuid.read(certificationBillinfo.getAdminOrg().getId().toString())));
				certificationBillinfo.setAdminOrgStr(adminorg.getName());
			}

			if (certificationBillinfo.getPosition() != null) {
				PositionInfo position = PositionFactory.getLocalInstance(ctx).getPositionInfo(
						new ObjectUuidPK(BOSUuid.read(certificationBillinfo.getPosition().getId().toString())));
				certificationBillinfo.setPositionStr(position.getName());
			}

			CertificationApplyReasonInfo certificationApplyReasonInfo = CertificationApplyReasonFactory
					.getLocalInstance(ctx).getCertificationApplyReasonInfo(
							new ObjectUuidPK(BOSUuid.read(certificationBillinfo.getReason().getId().toString())));
			certificationBillinfo.setApplyreasonStr(certificationApplyReasonInfo.getName());
			String personId = certificationBillinfo.getPerson().getId().toString();
			EmpPosOrgRelationCollection empPosOrgRelationCollection = EmpPosOrgRelationFactory.getLocalInstance(ctx)
					.getEmpPosOrgRelationCollection("where person='" + personId
							+ "' and assignType=1 and isSystem=1 order by endDateTime desc");
			if (empPosOrgRelationCollection.size() > 0) {
				certificationBillinfo.setEmpOrgRelation(empPosOrgRelationCollection.get(0));
			}

			HRCertificationBillTypeInfo billTypeInfo = (HRCertificationBillTypeInfo) certificationBillinfo.get("certificationBillType");
			if (billTypeInfo != null) {
				String certificationBillTypeId = billTypeInfo.getId().toString();
				CertificationTempletCollection coll = CertificationTempletFactory.getLocalInstance(ctx)
						.getCertificationTempletCollection(
								"where certificationBillType = '" + certificationBillTypeId + "' and state=1");
				if (coll != null && coll.size() == 1) {
					CertificationTempletInfo tempinfo = coll.get(0);
					certificationBillinfo.setCertificationTemplet(tempinfo);
				}
			}
		} catch (EASBizException var11) {
			logger.error(var11.getMessage(), var11);
		} catch (BOSException var12) {
			logger.error(var12.getMessage(), var12);
		} catch (UuidException var13) {
			logger.error(var13.getMessage(), var13);
		}

	}


	/**
	 * 调用submit方法
	 */
	public static void exeSubmit(Context ctx, String billId ) throws BOSException, EASBizException {

		//提交
		try {
			IHRCertificationBill localInstance = HRCertificationBillFactory.getLocalInstance(ctx);
			HRCertificationBillInfo billInfo = localInstance.getHRCertificationBillInfo(new ObjectUuidPK(billId));
//		IObjectPK userId = ctx.getCaller();
//		UserInfo  user = UserFactory.getLocalInstance(ctx).getUserByID(userId);
//		billInfo.setAuditor(user);
			
			boolean isOpen = WfEventListenerStateManager.getInstance().isEnable();           
			//开启工作流事务  
			if(!isOpen) {
				WfEventListenerStateManager.getInstance().enableEventListener(); 
			}
			localInstance.submit(billInfo);
			   //如果本来工作流服务状态不是关的，将它关掉   
			if(!isOpen) {
				WfEventListenerStateManager.getInstance().disableEventListener();    
			}
		} catch (Exception var4) {
			var4.printStackTrace();
		}
	}


}
