package com.kingdee.eas.custom.facade.employee;


import org.apache.commons.lang3.StringUtils;
import org.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.util.BOSUuid;
import com.kingdee.eas.base.permission.UserFactory;
import com.kingdee.eas.base.permission.UserInfo;
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.Genders;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.utils.SendUtils;
import com.kingdee.eas.framework.CoreBaseInfo;
import com.kingdee.eas.hr.affair.EmpEnrollBizBillEntryCollection;
import com.kingdee.eas.hr.affair.EmpEnrollBizBillEntryInfo;
import com.kingdee.eas.hr.affair.EmpEnrollBizBillFactory;
import com.kingdee.eas.hr.affair.EmpEnrollBizBillInfo;
import com.kingdee.eas.hr.affair.SourceBillTypeEnum;
import com.kingdee.eas.hr.base.AffairActionReasonCollection;
import com.kingdee.eas.hr.base.AffairActionReasonFactory;
import com.kingdee.eas.hr.base.ApproveTypeEnum;
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.HRBizDefineCollection;
import com.kingdee.eas.hr.base.HRBizDefineFactory;
import com.kingdee.eas.hr.base.VariationReasonCollection;
import com.kingdee.eas.hr.base.VariationReasonFactory;
import com.kingdee.eas.hr.emp.CountryRegionCollection;
import com.kingdee.eas.hr.emp.CountryRegionFactory;
import com.kingdee.eas.hr.emp.CredentialsTypeFactory;
import com.kingdee.eas.hr.org.JobGradeFactory;
import com.kingdee.eas.hr.org.JobGradeInfo;
import com.kingdee.eas.mobile.BOSMsgTypeEnum;
import com.kingdee.eas.mobile.PriorityEnum;
import com.kingdee.eas.util.app.ContextUtil;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import com.kingdee.shr.preentry.SubmitEffectSSCFacadeFactory;
import com.kingdee.util.LocaleUtils;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 预入职生成入职单后台事务
 *
 * @author xiaoxin
 */
public class EmpPreEntryFacadeControllerBean extends AbstractEmpPreEntryFacadeControllerBean {
    /**
     *
     */
    private static final long serialVersionUID = -4572246200432035893L;
    private static Logger logger =
            Logger.getLogger("com.kingdee.eas.custom.facade.employee.EmpPreEntryFacadeControllerBean");

    @Override
    protected void _createEmpEnrollBizBill(Context ctx, String baseDate,
                                           String empNumber, String orgNumber) throws BOSException {
        baseDate = this.getYesterday(baseDate);
        logger.error("基准日期" + baseDate);
        //查询预入职单据状态为已审核，是否自动生成入职单为是，预入职日期在当天之前的数据
        StringBuffer preEntrySql = new StringBuffer();
        preEntrySql.append(" select a.FCreatorID,a.Fid,a.FPositionID,CFLocalName_l2,CFSurname_l2,CFMiddleNames_l2,CFGivenName_l2,CFUserName_l2,a.FName_l2,a.FName_l1,a.FName_l3,CFEmpNumber,");
        preEntrySql.append(" FGender,FBirthday,FGlobalRoaming,FNCell,FEmail,CFWorkemail,FIDCardNO,CFDocumenttypeID,FPassportNO,");
        preEntrySql.append(" FPreEnterDate,CFTryMonth,CFTrialStartDate,CFTransferDate,CFEmpTypeID,CFPersontypeID,CFWcategoryID,");
        preEntrySql.append(" CFFtorptID,CFLmanagerID,CFAdmintitle,CFAcademictitleID,CFJobsID,CFWaitcontract,CFLegalemployer,");
        preEntrySql.append(" CFExpatriate,CFResident,CFPaycurrency,CFHwage,CFFsmentitlement,CFFsentitlement,CFFaentitlement,a.CFJobGradeID,a.CFRmethodID,a.CFCountryRegionID, ");
        preEntrySql.append(" a.cfjobendtime");
        preEntrySql.append(" from T_HR_PreEntry as a ");
        preEntrySql.append(" left join T_HR_PreEntryPerson as b on a.FTALENTID  = b.fid	");
        preEntrySql.append(" where fbillState = 3 and CFAutoConversion = 'Yes' and FIsGenerateEntryBill = 0 and FPREENTERDATE <= '" + baseDate + "'");
        if (StringUtils.isNotBlank(empNumber)) {
            preEntrySql.append(" a.CFEmpNumber = '" + empNumber + "' ");
        }
        if (StringUtils.isNotBlank(empNumber)) {
            preEntrySql.append(" a.orgNumber = (select fid from t_org_admin where fnumber = '" + empNumber + "') ");
        }
        logger.error("预入职sql：" + preEntrySql);
        IRowSet rs = DbUtil.executeQuery(ctx, preEntrySql.toString());
        try {
            if (rs.size() > 0) {
                createEmpEnrollBizBillInfo(ctx, rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取基准日期
     *
     * @return
     */
    private String getYesterday(String baseDate) {
        if (StringUtils.isEmpty(baseDate)) {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            baseDate = simpleDateFormat.format(calendar.getTime());
        }
        return baseDate;
    }


    private void createEmpEnrollBizBillInfo(Context ctx, IRowSet rs) throws SQLException {
        StringBuffer strBuffer = new StringBuffer();
        while (rs.next()) {
            try {
                logger.error("生成入职单：" + rs.getString("CFEmpNumber"));
                //单据主题
                EmpEnrollBizBillInfo empbizInfo = new EmpEnrollBizBillInfo();
                //分录
                EmpEnrollBizBillEntryInfo empbizEntryInfo = new EmpEnrollBizBillEntryInfo();
                UserInfo user = UserFactory.getLocalInstance(ctx).getUserInfo(new ObjectUuidPK(rs.getString("FCreatorID")));
                logger.error("创建用户：" + user.toString());
                //申请人
                empbizInfo.setApplier(user.getPerson());
                //申请日期
                empbizInfo.setApplyDate(new Date());
                //岗位
                PositionInfo positionInfo = PositionFactory.getLocalInstance(ctx).getPositionInfo(new ObjectUuidPK(rs.getString("FPositionID")));
                AdminOrgUnitInfo adminInfo = positionInfo.getAdminOrgUnit();
                //住址֯
                empbizInfo.setAdminOrg(adminInfo);
                empbizInfo.setHrOrgUnit(ContextUtil.getCurrentHRUnit(ctx));
                //审核状态
                empbizInfo.setBillState(HRBillStateEnum.AUDITED);
                empbizInfo.setApproveType(ApproveTypeEnum.DIRECT);
                empbizInfo.setBizDate(new Date());
                //创建者
                empbizInfo.setAuditor(user);
                empbizInfo.setIsMultiEntry(false);
                empbizInfo.setInnerState(0);
                empbizInfo.setIsMulti(false);
                empbizInfo.setUseDefault(true);
                //本地名称
                empbizEntryInfo.put("localname", rs.getString("CFLocalName_l2"));
                //姓
                empbizEntryInfo.put("surname", rs.getString("CFSurname_l2"));
                //中间名
                empbizEntryInfo.put("middleNames", rs.getString("CFMiddleNames_l2"));
                //名
                empbizEntryInfo.put("givenName", rs.getString("CFGivenName_l2"));
                //用户名
                empbizEntryInfo.put("userName", rs.getString("CFUserName_l2"));
                //展示名称
                empbizEntryInfo.setEmpName(rs.getString("FName_l2"));
                empbizEntryInfo.setEmpName(rs.getString("FName_l1"), LocaleUtils.locale_l1);
                empbizEntryInfo.setEmpName(rs.getString("FName_l2"), LocaleUtils.locale_l2);
                empbizEntryInfo.setEmpName(rs.getString("FName_l3"), LocaleUtils.locale_l3);
                logger.error("英文名：" + empbizEntryInfo.getEmpName(Locale.ENGLISH) + ",中文名：" + empbizEntryInfo.getEmpName(Locale.SIMPLIFIED_CHINESE) + ",名称：" + empbizEntryInfo.getEmpName());
                //员工编码
                empbizEntryInfo.setEmpNumber(rs.getString("CFEmpNumber"));
                //性别
                empbizEntryInfo.setGender(Genders.getEnum(rs.getInt("FGender")));
                //出生日期
                empbizEntryInfo.setBirthday(rs.getDate("FBirthday"));
                //区号
                empbizEntryInfo.setGlobalRoaming(rs.getString("FGlobalRoaming"));
                //新手机号
                empbizEntryInfo.setNCell(rs.getString("FNCell"));
                //工作邮箱
                empbizEntryInfo.setEmail(rs.getString("CFWorkemail"));
                //私人邮箱
                empbizEntryInfo.put("pemail", rs.getString("FEmail"));
                System.out.println("工作邮箱===" + empbizEntryInfo.getEmail());
                //֤身份证号
                empbizEntryInfo.put("IDCardNo", rs.getString("FIDCardNO"));
                //֤证件类型
                if (StringUtils.isNotBlank(rs.getString("CFDocumenttypeID"))) {
                    empbizEntryInfo.setCredentialsType(CredentialsTypeFactory.getLocalInstance(ctx).
                            getCredentialsTypeInfo(new ObjectUuidPK(rs.getString("CFDocumenttypeID"))));
                }
                empbizEntryInfo.put("passPortNo", rs.getString("FPassportNO"));
                empbizEntryInfo.setPosition(positionInfo);
                //职务
                if (positionInfo.getJob() != null && positionInfo.getJob().getId() != null) {
                    logger.error("岗位职务：" + positionInfo.getJob().getName());
                    empbizEntryInfo.setJob(positionInfo.getJob());
                }
                //行政组织
                empbizEntryInfo.setAdminOrg(positionInfo.getAdminOrgUnit());
                //预入职日期
                empbizEntryInfo.setBizDate(rs.getDate("FPreEnterDate"));
                //试用期（月）
                empbizEntryInfo.setProbation(rs.getInt("CFTryMonth"));
                //试用期开始日期
                empbizEntryInfo.put("trialStartDate", rs.getDate("CFTrialStartDate"));
                //预计转正日期
                empbizEntryInfo.setPlanFormalDate(rs.getDate("CFTransferDate"));
                //用工关系状态
                if (StringUtils.isNotBlank(rs.getString("CFEmpTypeID"))) {
                    empbizEntryInfo.setEmpType(EmployeeTypeFactory.getLocalInstance(ctx).
                            getEmployeeTypeInfo(new ObjectUuidPK(rs.getString("CFEmpTypeID"))));
                } else {
                    String paramStr = null;
                    if (empbizEntryInfo.getProbation() > 0) {
                        paramStr = "where number = '002'";
                    } else {
                        paramStr = "where number = '001'";
                    }
                    EmployeeTypeCollection employeeType = EmployeeTypeFactory.getLocalInstance(ctx).getEmployeeTypeCollection(paramStr);
                    empbizEntryInfo.setEmpType(employeeType.get(0));
                }

                //人员类型
                empbizEntryInfo.put("persontype", rs.getString("CFPersontypeID"));
                //员工类别
                empbizEntryInfo.put("wcategory", rs.getString("CFWcategoryID"));
                //全职或兼职
                empbizEntryInfo.put("ftorpt", rs.getString("CFFtorptID"));
                //直属上级
                empbizEntryInfo.put("lmanager", rs.getString("CFLmanagerID"));
                //admin title
                empbizEntryInfo.put("admintitle", rs.getString("CFAdmintitle"));
                //Academic Title
                empbizEntryInfo.put("academictitle", rs.getString("CFAcademictitleID"));
                //Job2
                empbizEntryInfo.put("jobs", rs.getString("CFJobsID"));
                //是否等待合同
                empbizEntryInfo.put("waitcontract", rs.getString("CFWaitcontract"));
                //法人
                empbizEntryInfo.put("legalemployer", rs.getString("CFLegalemployer"));
                //境外人士
                empbizEntryInfo.put("Expatriate", rs.getString("CFExpatriate"));
                //居民
                empbizEntryInfo.put("resident", rs.getString("CFResident"));
                //֧支付币种
                empbizEntryInfo.put("paycurrency", rs.getString("CFPaycurrency"));
                //时薪
                empbizEntryInfo.put("hwage", rs.getString("CFHwage"));
                //教师病假最高额度
                empbizEntryInfo.put("fsmentitlement", rs.getString("CFFsmentitlement"));
                //教师病假额度
                empbizEntryInfo.put("fsentitlement", rs.getString("CFFsentitlement"));
                //教师年假额度
                empbizEntryInfo.put("faentitlement", rs.getString("CFFaentitlement"));
                //职等
                if (StringUtils.isNotBlank(rs.getString("CFJobGradeID"))) {
                    JobGradeInfo jobGradeInfo = JobGradeFactory.getLocalInstance(ctx).getJobGradeInfo(new ObjectUuidPK(rs.getString("CFJobGradeID")));
                    empbizEntryInfo.put("jobGrade", jobGradeInfo);
                }
                //纳税方式
                empbizEntryInfo.put("rmethod", rs.getString("CFRmethodID"));
                empbizEntryInfo.setEnrollAgain(false);
                //变动操作
                HRBizDefineCollection hbdc = HRBizDefineFactory.getLocalInstance(ctx).getHRBizDefineCollection(" where number = 'SHR01'");
                empbizEntryInfo.setHrBizDefine(hbdc.get(0));
                //变动类型
                AffairActionReasonCollection affairActionReasonCollection = AffairActionReasonFactory.getLocalInstance(ctx).getAffairActionReasonCollection(" where number = '0101'");
                empbizEntryInfo.setAffairActionReason(affairActionReasonCollection.get(0));

                VariationReasonCollection vrcs = VariationReasonFactory.getLocalInstance(ctx).getVariationReasonCollection(" where number = 'RZ05'");
                empbizEntryInfo.setVariationReason(vrcs.get(0));
                empbizEntryInfo.put("PreEntryId", rs.getString("Fid"));
                empbizEntryInfo.setSourceBillType(SourceBillTypeEnum.PREENTRY);

                //国家地区
                if (StringUtils.isNotBlank(rs.getString("CFCountryRegionID"))) {
                    CountryRegionCollection countryRegionCollection = CountryRegionFactory.getLocalInstance(ctx).getCountryRegionCollection("where id = '" + rs.getString("CFCountryRegionID") + "'");
                    if (countryRegionCollection != null && countryRegionCollection.size() > 0) {
                        empbizEntryInfo.setCountryRegion(countryRegionCollection.get(0));
                    }
                }
                //兼职类人员任职结束时间
                empbizEntryInfo.put("jobEndTime", rs.getString("cfjobendtime"));


                empbizInfo.getEntrys().add(empbizEntryInfo);
                logger.error("单据信息：" + empbizInfo.toString());
                CoreBaseInfo model = empbizInfo;
                IObjectPK bosid = EmpEnrollBizBillFactory.getLocalInstance(ctx).submitEffect(model);

                EmpEnrollBizBillInfo empEnrollBizBillInfo = EmpEnrollBizBillFactory.getLocalInstance(ctx).getEmpEnrollBizBillInfo(bosid);
                EmpEnrollBizBillEntryCollection entrys = empEnrollBizBillInfo.getEntrys();
                String personBillId = "";
                if (entrys.size() > 0) {
                    personBillId = entrys.get(0).getId().toString();
                }
                logger.error("生成入职单成功：" + bosid);
                if (!StringUtils.isEmpty(bosid + "")) {
                    StringBuffer upsql = new StringBuffer();
                    upsql.append(" update T_HR_PreEntry set FCheckInState = '3',FIsGenerateEntryBill = '1',FPersonBillId = '" + personBillId + "' where FID = '" + rs.getString("Fid") + "'");
                    logger.error("更新预入职单状态：" + upsql);
                    DbUtil.execute(ctx, upsql.toString());
                }

            } catch (Exception e) {
                e.printStackTrace();
                logger.error(rs.getString("CFEmpNumber") + "生成入职单失败：" + e.getMessage());
                strBuffer.append("Automatic onboarding of employee " + rs.getString("FName_l2") + "(" + rs.getString("CFEmpNumber") + ") failed. " + e.getMessage() + "\r\n");
                continue;
            }
        }

        if (strBuffer.length() > 0) {
            try {
                strBuffer.append("Please check the data, or contact the system administrator with itsupport@gtiit.edu.cn.");
                Set<String> userIdSet = new HashSet<String>();
                String roleSql = "select c.fid from T_WFR_WFROLE a left join T_WFR_PERSONROLE b on a.fid=b.froleid left join T_PM_USER c on b.FPSERSONID = c.FPERSONID where a.FNUMBER in ('105') and c.fid is not null";
                logger.error("获取工作流角色对应用户SQL：" + roleSql);
                IRowSet roleRow = DbUtil.executeQuery(ctx, roleSql);
                try {
                    while (roleRow.next()) {
                        userIdSet.add(roleRow.getString("fid"));
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                logger.error("用户ID集合：" + userIdSet.toString());
                if (userIdSet.size() == 0) {
                    return;
                }
                List<String> list = userIdSet.stream().collect(Collectors.toList());
                SendUtils.msgGroupSend(ctx, "Notification of automatic onboarding failure", PriorityEnum.HIGHT_VALUE, false, strBuffer.toString(), list, BOSMsgTypeEnum.V_TYPE_EMAIL, null);
            } catch (EASBizException e) {
                e.printStackTrace();
            } catch (BOSException e) {
                e.printStackTrace();
            }
        }
    }

}
