package com.engine.recruit.system;

import com.api.doc.detail.util.DocDownloadCheckUtil;
import com.api.hrm.service.HrmResourceBaseService;
import com.api.hrm.util.ServiceUtil;
import com.engine.common.biz.SimpleBizLogger;
import com.engine.common.constant.BizLogOperateAuditType;
import com.engine.common.constant.BizLogOperateType;
import com.engine.common.constant.BizLogSmallType4Hrm;
import com.engine.common.constant.BizLogType;
import com.engine.common.entity.BizLogContext;
import com.engine.common.service.impl.HrmCommonServiceImpl;
import com.engine.common.util.LogUtil;
import com.engine.hrm.entity.RuleCodeType;
import com.engine.hrm.util.CodeRuleManager;
import com.engine.hrm.util.HrmWeakPasswordUtil;
import com.engine.hrm.util.face.HrmFaceCheckManager;
import com.engine.hrm.util.face.ValidateFieldManager;
import com.engine.hrm.util.face.bean.CheckItemBean;
import com.weaver.general.BaseBean;
import ln.LN;
import org.apache.commons.lang3.StringUtils;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.file.Prop;
import weaver.formmode.recruit.modeexpand.util.RecruitModeUtil;
import weaver.general.GCONST;
import weaver.general.PasswordUtil;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.common.DbFunctionUtil;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.companyvirtual.DepartmentVirtualComInfo;
import weaver.hrm.finance.SalaryManager;
import weaver.hrm.passwordprotection.manager.HrmResourceManager;
import weaver.hrm.privacy.PrivacyComInfo;
import weaver.hrm.privacy.UserPrivacyComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.hrm.settings.ChgPasswdReminder;
import weaver.hrm.settings.RemindSettings;
import weaver.hrm.tools.HrmDateCheck;
import weaver.interfaces.hrm.HrmServiceManager;
import weaver.license.PluginUserCheck;
import weaver.rsa.security.RSA;
import weaver.rtx.OrganisationCom;
import weaver.rtx.OrganisationComRunnable;
import weaver.system.SysRemindWorkflow;
import weaver.systeminfo.SystemEnv;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author:dxfeng
 * @createTime: 2022/10/11
 * @version: 1.0
 */
public class ResourceSyncUtil {
    private static final char SEPARATOR = Util.getSeparator();
    private static final String TODAY = DateUtil.getCurrentDate();

    public static Map<String, Object> addResource(User user, Map<String, Object> params) {

        Map<String, Object> returnMap = new HashMap<>();
        RecordSet rs = new RecordSet();
        String sql;
        try {
            DepartmentComInfo departmentComInfo = new DepartmentComInfo();
            boolean canEdit = HrmUserVarify.checkUserRight("HrmResourceEdit:Edit", user);
            if (!canEdit) {
                returnMap.put("status", "-1");
                returnMap.put("message", SystemEnv.getHtmlLabelName(22620, user.getLanguage()));
                return returnMap;
            }
            String loginId = Util.null2String(params.get("loginid"));
            String accountType = Util.null2s(Util.fromScreen3(Util.null2String(params.get(("accounttype"))), user.getLanguage()), "0");
            if ("1".equals(accountType)) {
                //次账号没有loginId
                loginId = "";
            }
            boolean canSave = false;
            LN LN = new LN();
            int ckHrmnum = LN.CkHrmnum();
            if (loginId.length() > 0) {
                if (ckHrmnum < 0) {
                    //只有License检查人数小于规定人数，才能修改。防止客户直接修改数据库数据
                    canSave = true;
                }
            } else {
                canSave = true;
            }
            if (!canSave) {
                returnMap.put("status", "-1");
                returnMap.put("message", SystemEnv.getHtmlLabelName(84760, user.getLanguage()));
                return returnMap;
            }


            if (!"".equals(loginId) && "0".equals(accountType)) {
                sql = "select count(1) from hrmresourceallview where loginid='" + loginId + "' ";
                rs.execute(sql);
                if (rs.next()) {
                    if (rs.getInt(1) > 0) {
                        returnMap.put("status", "-1");
                        returnMap.put("message", SystemEnv.getHtmlLabelName(15094, user.getLanguage()));
                        return returnMap;
                    }
                }
            }

            String departmentid = Util.null2String(params.get("departmentid"));
            String subcompanyid = departmentComInfo.getSubcompanyid1(departmentid);
            if (!"".equals(loginId) && !"0".equals(subcompanyid) && new HrmResourceManager().noMore(subcompanyid)) {
                returnMap.put("status", "-1");
                returnMap.put("message", SystemEnv.getHtmlLabelName(81926, user.getLanguage()));
                return returnMap;
            }


            ResourceComInfo ResourceComInfo = new ResourceComInfo();
            Map<String, String> result = addResourceBase(user, params);

            String addResourceBaseCode = result.get("status");
            if ("-1".equals(addResourceBaseCode)) {
                returnMap.put("status", "-1");
                returnMap.put("message", result.get("message"));
                return returnMap;
            }


            int id = Util.getIntValue(result.get("id"));
            String password = Util.null2String(params.get("password"));
            //是否开启了RSA加密
            String openRSA = Util.null2String(Prop.getPropValue("openRSA", "isrsaopen"));
            if ("1".equals(openRSA)) {
                password = new RSA().decrypt(password);
            }
            ChgPasswdReminder reminder = new ChgPasswdReminder();
            RemindSettings settings = reminder.getRemindSettings();

            //判断是否开启了【启用初始密码】
            String defaultPasswordEnable = Util.null2String(settings.getDefaultPasswordEnable());
            //【初始密码】
            String defaultPassword = Util.null2String(settings.getDefaultPassword());
            //如果管理员设置的密码为空。并且开启了【启用初始密码】，且初始密码不为空，则默认取初始密码作为密码
            if ("".equals(password) && "1".equals(defaultPasswordEnable) && !"".equals(defaultPassword)) {
                password = defaultPassword;
            }

            //判断是否开启了【禁止弱密码保存】
            String weakPasswordDisable = Util.null2s(settings.getWeakPasswordDisable(), "0");
            if ("1".equals(weakPasswordDisable)) {
                if (!"".equals(password)) {//密码为空的情况
                    //判断是否为弱密码
                    HrmWeakPasswordUtil hrmWeakPasswordUtil = new HrmWeakPasswordUtil();
                    if (hrmWeakPasswordUtil.isWeakPsd(password)) {
                        returnMap.put("status", "-1");
                        returnMap.put("message", SystemEnv.getHtmlLabelName(515420, user.getLanguage()));
                        return returnMap;
                    }
                }
            }

            int secLevel = Util.getIntValue(Util.null2String(params.get("seclevel")), 0);
            if (id > 0) {
                //保存系统信息
                SimpleBizLogger logger = new SimpleBizLogger();
                BizLogContext bizLogContext = new BizLogContext();
                bizLogContext.setLogType(BizLogType.HRM);//模块类型
                bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_RSOURCE_CARD);//所属大类型
                bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_RSOURCE_CARD_SYSTEM);//当前小类型
                bizLogContext.setOperateType(BizLogOperateType.ADD);
                bizLogContext.setOperateAuditType(BizLogOperateAuditType.WARNING);
                bizLogContext.setParams(params);//当前request请求参数
                logger.setUser(user);//当前操作人
                String mainSql = "select * from hrmresource where id=" + id;
                logger.setMainSql(mainSql, "id");//主表sql
                logger.setMainPrimarykey("id");//主日志表唯一key
                logger.setMainTargetNameColumn("lastname");//当前targetName对应的列（对应日志中的对象名）
                logger.before(bizLogContext);//写入操作前日志

                String workStartDate = Util.null2String(params.get("workstartdate"));//参加工作日期
                String companyStartDate = Util.null2String(params.get("companystartdate"));//入职日期
                String certificateNum = Util.null2String(params.get("certificatenum"));//身份证号
                String probationEndDate = Util.null2String(params.get("probationenddate"));//试用期结束日期

                String dspOrder = Util.fromScreen3(Util.null2String(params.get("dsporder")), user.getLanguage());
                if (dspOrder.length() == 0) {
                    dspOrder = "" + id;
                }
                if ("0".equals(accountType)) {

                    String encrptPassword = "";
                    String salt = "";
                    if (StringUtils.isNotBlank(password)) {
                        String[] encrypts = PasswordUtil.encrypt(password);
                        encrptPassword = encrypts[0];
                        salt = encrypts[1];
                    }

                    sql = " update hrmresource set loginid='" + loginId + "', password='" + encrptPassword + "'," +
                            "seclevel=" + secLevel + ",dsporder=" + dspOrder +
                            ",salt='" + salt + "',workstartdate='" + workStartDate + "',companystartdate='" + companyStartDate + "' where id = " + id;
                } else {
                    sql = " update hrmresource set seclevel=" + secLevel + ",dsporder=" + dspOrder +
                            " ,workstartdate='" + workStartDate + "',companystartdate='" + companyStartDate + "' where id = " + id;
                }
                // 计算工龄、司龄
                updateWorkInfo(String.valueOf(id), user, params);

                rs.execute(sql);

                // 更新身份证、试用期结束日期
                sql = " update hrmresource set certificatenum='" + certificateNum + "',probationenddate ='" + probationEndDate + "' where id = " + id;
                rs.executeUpdate(sql);

                HrmFaceCheckManager.setUserPassowrd(id + "", password);
                HrmFaceCheckManager.sync(id + "", HrmFaceCheckManager.getOptUpdate(), "HrmResourceAddService_saveSimple_update", HrmFaceCheckManager.getOaResource());

                LogUtil.writeBizLog(logger.getBizLogContexts());
            }

            //同步RTX端的用户信息.
            new OrganisationCom().checkUser(id);
            new Thread(new OrganisationComRunnable("user", "add", "" + id)).start();
            ResourceComInfo.updateResourceInfoCache("" + id);
            new PluginUserCheck().clearPluginUserCache("messager");
            //OA与第三方接口单条数据同步方法开始
            new HrmServiceManager().SynInstantHrmResource("" + id, "1");
            //OA与第三方接口单条数据同步方法结束
            //BBS集成相关
            String bbsLingUrl = new weaver.general.BaseBean().getPropValue(GCONST.getConfigFile(), "ecologybbs.linkUrl");
            if (!"0".equals(password)) {
                if (!"".equals(bbsLingUrl)) {
                    new Thread(new weaver.bbs.BBSRunnable(loginId, password)).start();
                }
            }

            returnMap.put("id", id);
            returnMap.put("status", "1");
        } catch (Exception e) {
            new BaseBean().writeLog("保存新建人员simple错误：" + e);
            returnMap.put("status", "-1");
            returnMap.put("message", "" + weaver.systeminfo.SystemEnv.getHtmlLabelName(22620, weaver.general.ThreadVarLanguage.getLang()) + "");
        }
        return returnMap;
    }

    private static Map<String, String> addResourceBase(User user, Map<String, Object> params) {
        Map<String, String> retmap = new HashMap<>();
        try {
            retmap.put("id", "0");
            RecordSet rs = new RecordSet();
            DepartmentComInfo DepartmentComInfo = new DepartmentComInfo();
            ResourceComInfo ResourceComInfo = new ResourceComInfo();
            SalaryManager SalaryManager = new SalaryManager();
            ChgPasswdReminder reminder = new ChgPasswdReminder();
            RemindSettings settings = reminder.getRemindSettings();
            SysRemindWorkflow SysRemindWorkflow = new SysRemindWorkflow();
            DepartmentVirtualComInfo DepartmentVirtualComInfo = new DepartmentVirtualComInfo();

            StringBuilder para;
            String cmd = Util.null2String(params.get("cmd"));
            String id = Util.null2String(params.get("id"));
            String workcode = Util.fromScreen3(Util.null2String(params.get("workcode")), user.getLanguage());
            String lastname = Util.fromScreen3(Util.null2String(params.get("lastname")), user.getLanguage()).trim();
            String sex = Util.fromScreen3(Util.null2String(params.get("sex")), user.getLanguage());
            String resourceimageid = Util.null2String(params.get("resourceimageid"));
            if (resourceimageid.length() > 0) {
                resourceimageid = "" + DocDownloadCheckUtil.getDownloadfileidstr(resourceimageid);
            }
            String departmentid = Util.fromScreen3(Util.null2String(params.get("departmentid")), user.getLanguage());
            String costcenterid = Util.fromScreen3(Util.null2String(params.get("costcenterid")), user.getLanguage());
            String jobtitle = Util.fromScreen3(Util.null2String(params.get("jobtitle")), user.getLanguage());
            String joblevel = Util.fromScreen3(Util.null2String(params.get("joblevel")), user.getLanguage());
            String jobactivitydesc = Util.fromScreen3(Util.null2String(params.get("jobactivitydesc")), user.getLanguage());
            String managerid = Util.fromScreen3(Util.null2String(params.get("managerid")), user.getLanguage());
            String assistantid = Util.fromScreen3(Util.null2String(params.get("assistantid")), user.getLanguage());
            String status = Util.fromScreen3(Util.null2String(params.get("status")), user.getLanguage());
            if (StringUtils.isBlank(status)) {
                status = "0";
            }
            String locationid = Util.fromScreen3(Util.null2String(params.get("locationid")), user.getLanguage());
            String workroom = Util.fromScreen3(Util.null2String(params.get("workroom")), user.getLanguage());
            String telephone = Util.fromScreen3(Util.null2String(params.get("telephone")), user.getLanguage());
            String mobile = Util.fromScreen3(Util.null2String(params.get("mobile")), user.getLanguage());
            String mobileshowtype = Util.fromScreen3(Util.null2String(params.get("mobileshowtype")), user.getLanguage());
            String mobilecall = Util.fromScreen3(Util.null2String(params.get("mobilecall")), user.getLanguage());
            String fax = Util.fromScreen3(Util.null2String(params.get("fax")), user.getLanguage());
            String jobcall = Util.fromScreen3(Util.null2String(params.get("jobcall")), user.getLanguage());
            String email = Util.fromScreen3(Util.null2String(params.get("email")), user.getLanguage());
            String dsporder = Util.fromScreen3(Util.null2String(params.get("dsporder")), user.getLanguage());
            String accounttype = Util.fromScreen3(Util.null2String(params.get("accounttype")), user.getLanguage());
            String systemlanguage = Util.null2String(params.get("systemlanguage"));
            if ("".equals(systemlanguage) || "0".equals(systemlanguage)) {
                systemlanguage = "7";
            }
            String belongto = Util.fromScreen3(Util.null2String(params.get("belongto")), user.getLanguage());
            //应聘人员id
            String rcid = Util.null2String(params.get("rcId"));

            CheckItemBean mobileBean = new CheckItemBean("mobile", mobile, id);
            ValidateFieldManager.validate(mobileBean);
            if (!mobileBean.isPass()) {
                retmap.put("status", "-1");
                retmap.put("message", mobileBean.getCheckMsg());
                return retmap;
            }

            CheckItemBean telephoneBean = new CheckItemBean("telephone", telephone, id);
            ValidateFieldManager.validate(telephoneBean);
            if (!telephoneBean.isPass()) {
                retmap.put("status", "-1");
                retmap.put("message", telephoneBean.getCheckMsg());
                return retmap;
            }


            if (dsporder.length() == 0) {
                dsporder = id;
            }
            if ("0".equals(accounttype)) {
                belongto = "-1";
            }
            String departmentvirtualids = Util.null2String(params.get("departmentvirtualids"));//虚拟部门id;

            //Td9325,解决多账号次账号没有登陆Id在浏览框组织结构中无法显示的问题。
            boolean falg = false;
            String loginid = "";
            if ("1".equals(accounttype)) {
                rs.execute("select loginid from HrmResource where id =" + belongto);
                if (rs.next()) {
                    loginid = rs.getString("loginid");
                }
                if (!"".equals(loginid)) {
                    String maxidsql = "select max(id) as id from HrmResource where loginid like '" + loginid + "%'";
                    rs.execute(maxidsql);
                    if (rs.next()) {
                        loginid = loginid + (rs.getInt("id") + 1);
                        falg = true;
                    }
                }
            }
            rs.executeProc("HrmResourceMaxId_Get", "");
            rs.next();
            id = "" + rs.getInt(1);
            if (!"".equals(rcid)) {
                id = rcid;
            }
            SimpleBizLogger logger = new SimpleBizLogger();
            BizLogContext bizLogContext = new BizLogContext();
            bizLogContext.setLogType(BizLogType.HRM);//模块类型
            bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_RSOURCE_CARD);//所属大类型
            bizLogContext.setBelongTypeTargetName(SystemEnv.getHtmlLabelName(1361, user.getLanguage()));
            bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_RSOURCE_CARD_BASE);//当前小类型
            bizLogContext.setOperateType(BizLogOperateType.ADD);
            bizLogContext.setParams(params);//当前request请求参数
            logger.setUser(user);//当前操作人
            String cusFieldNames = ServiceUtil.getCusFieldNames("HrmCustomFieldByInfoType", -1, "b");
            String mainSql = "select a.*" + (cusFieldNames.length() > 0 ? "," + cusFieldNames : "") + " from hrmresource a left join cus_fielddata b on a.id=b.id and b.scope='HrmCustomFieldByInfoType' and b.scopeid=-1 where a.id=" + id;
            logger.setMainSql(mainSql, "id");//主表sql
            logger.setMainPrimarykey("id");//主日志表唯一key
            logger.setMainTargetNameColumn("lastname");//当前targetName对应的列（对应日志中的对象名）
            logger.before(bizLogContext);//写入操作前日志

            String sql = "select managerstr, seclevel from HrmResource where id = " + Util.getIntValue(managerid);
            rs.execute(sql);
            String managerstr = "";
            while (rs.next()) {
                String tmp_managerstr = rs.getString("managerstr");
                //处理managerstr 不以逗号开始或者结束的情况 形如 managerstr：8 begin
                if (!tmp_managerstr.startsWith(",")) {
                    tmp_managerstr = "," + tmp_managerstr;
                }
                if (!tmp_managerstr.endsWith(",")) {
                    tmp_managerstr = tmp_managerstr + ",";
                }
                //处理managerstr 不以逗号开始或者结束的情况 形如 managerstr：8 end
                managerstr += tmp_managerstr;
                managerstr = "," + managerid + managerstr;
                managerstr = managerstr.endsWith(",") ? managerstr : (managerstr + ",");
            }

            String subcmpanyid1 = DepartmentComInfo.getSubcompanyid1(departmentid);
            RecordSetTrans rst = new RecordSetTrans();
            rst.setAutoCommit(false);
            try {
                if (resourceimageid.length() == 0) {
                    resourceimageid = "null";
                }
                if (costcenterid.length() == 0) {
                    costcenterid = "null";
                }
                if (managerid.length() == 0) {
                    managerid = "null";
                }
                if (assistantid.length() == 0) {
                    assistantid = "null";
                }
                if (accounttype.length() == 0) {
                    accounttype = "null";
                }
                if (belongto.length() == 0) {
                    belongto = "null";
                }
                if (jobcall.length() == 0) {
                    jobcall = "null";
                }
                if (mobileshowtype.length() == 0) {
                    mobileshowtype = "null";
                }
                if ("postgresql".equalsIgnoreCase(rst.getDBType())) {
                    if (joblevel.length() == 0) {
                        joblevel = null;
                    }
                    if (dsporder.length() == 0) {
                        dsporder = null;
                    }
                }
                workcode = CodeRuleManager.getCodeRuleManager().generateRuleCode(RuleCodeType.USER, subcmpanyid1, departmentid, jobtitle, workcode);
                para = new StringBuilder("" + id + SEPARATOR + workcode + SEPARATOR + lastname + SEPARATOR + sex + SEPARATOR + resourceimageid + SEPARATOR +
                        departmentid + SEPARATOR + costcenterid + SEPARATOR + jobtitle + SEPARATOR + joblevel + SEPARATOR + jobactivitydesc + SEPARATOR +
                        managerid + SEPARATOR + assistantid + SEPARATOR + status + SEPARATOR + locationid + SEPARATOR + workroom + SEPARATOR + telephone +
                        SEPARATOR + mobile + SEPARATOR + mobilecall + SEPARATOR + fax + SEPARATOR + jobcall + SEPARATOR + subcmpanyid1 + SEPARATOR + managerstr +
                        SEPARATOR + accounttype + SEPARATOR + belongto + SEPARATOR + systemlanguage + SEPARATOR + email + SEPARATOR + dsporder + SEPARATOR + mobileshowtype);

                rst.executeProc("HrmResourceBasicInfo_Insert", para.toString());
                if (Util.null2String(locationid).length() > 0) {
                    rst.executeSql("update hrmresource set countryid=(select countryid from HrmLocations where id=" + locationid + "),"
                            + DbFunctionUtil.getInsertUpdateSetSql(rst.getDBType(), user.getUID()) + " where id=" + id);
                }
                String logidsql, quickSearchStr = new HrmCommonServiceImpl().generateQuickSearchStr(lastname);
                if (falg) {
                    logidsql = "update HrmResource set loginid = ?, pinyinlastname = ?, ecology_pinyin_search = ? where id = ?";
                    rst.executeUpdate(logidsql, loginid, quickSearchStr, quickSearchStr, id);
                } else {
                    logidsql = "update HrmResource set pinyinlastname = ?, ecology_pinyin_search = ? where id = ?";
                    rst.executeUpdate(logidsql, quickSearchStr, quickSearchStr, id);
                }
                rst.commit();
            } catch (Exception e) {
                rst.rollback();
                e.printStackTrace();
            }

            boolean formdefined = false;
            weaver.system.CusFormSettingComInfo CusFormSettingComInfo = new weaver.system.CusFormSettingComInfo();
            weaver.system.CusFormSetting CusFormSetting = CusFormSettingComInfo.getCusFormSetting("hrm", "HrmResourceBase");
            if (CusFormSetting != null) {
                if (CusFormSetting.getStatus() == 2) {
                    //自定义布局页面
                    formdefined = true;
                }
            }
            int userid = user.getUID();
            String userpara = "" + userid + SEPARATOR + TODAY;
            para = new StringBuilder("" + id);
            for (int i = 0; i < 5; i++) {
                int idx = i;
                if (formdefined) {
                    idx++;
                }
                String datefield = Util.null2String(params.get("datefield" + idx));
                String numberfield = "" + Util.getDoubleValue(Util.null2String(params.get("numberfield" + idx)), 0);
                String textfield = Util.null2String(params.get("textfield" + idx));
                String tinyintfield = "" + Util.getIntValue(Util.null2String(params.get("tinyintfield" + idx)), 0);
                para.append(SEPARATOR).append(datefield).append(SEPARATOR).append(numberfield).append(SEPARATOR).append(textfield).append(SEPARATOR).append(tinyintfield);
            }
            rs.executeProc("HrmResourceDefine_Update", para.toString());
            rs.executeProc("HrmResource_CreateInfo", "" + id + SEPARATOR + userpara + SEPARATOR + userpara);

            //421944 用户自定义隐私设置

            UserPrivacyComInfo upc = new UserPrivacyComInfo();
            PrivacyComInfo pc = new PrivacyComInfo();
            Map<String, String> mapShowSets = pc.getMapShowSets();
            String insertSql;
            rs = new RecordSet();
            try {
                String deletePriSql = " delete from userprivacysetting where userid= '" + id + "'";
                rs.execute(deletePriSql);
                for (Map.Entry<String, String> me : mapShowSets.entrySet()) {
                    String fieldName = me.getKey();
                    String fieldVal = Util.null2String(mapShowSets.get(fieldName));
                    if ("1".equals(fieldVal)) {
                        String tmpPK = id + "__" + fieldName;
                        String tmpPvalue = Util.null2String(params.get(fieldName + "showtype"));
                        insertSql = "insert into userprivacysetting (combinedid,userid,ptype,pvalue) values('" + tmpPK + "','" + id + "','" + fieldName + "','" + tmpPvalue + "')";
                        rs.execute(insertSql);
                    }
                }
                upc.removeUserPrivacyCache();
            } catch (Exception e) {
                e.printStackTrace();
            }


            // 改为只进行该人缓存信息的添加
            ResourceComInfo.addResourceInfoCache(id);
            SalaryManager.initResourceSalary(id);

            para = new StringBuilder("" + id + SEPARATOR + managerid + SEPARATOR + departmentid + SEPARATOR + subcmpanyid1 + SEPARATOR + "0" + SEPARATOR + managerstr);
            rs.executeProc("HrmResource_Trigger_Insert", para.toString());

            String sql_1 = ("insert into HrmInfoStatus (itemid,hrmid) values(1," + id + ")");
            rs.execute(sql_1);
            String sql_2 = ("insert into HrmInfoStatus (itemid,hrmid) values(2," + id + ")");
            rs.execute(sql_2);
            String sql_3 = ("insert into HrmInfoStatus (itemid,hrmid) values(3," + id + ")");
            rs.execute(sql_3);
            String sql_10 = ("insert into HrmInfoStatus (itemid,hrmid) values(10," + id + ")");
            rs.execute(sql_10);

            String CurrentUser = "" + user.getUID();
            String CurrentUserName = "" + user.getUsername();
            String SWFAccepter;
            String SWFTitle;
            String SWFRemark;
            String SWFSubmiter;
            String Subject;
            Subject = SystemEnv.getHtmlLabelName(15670, user.getLanguage());
            Subject += ":" + lastname;

            //modifier by lvyi 2013-12-31
            if ("1".equals(settings.getEntervalid())) {//入职提醒
                String thesql = "select  hrmids from HrmInfoMaintenance where id<4 or id = 10";
                rs.execute(thesql);
                StringBuilder members = new StringBuilder();
                while (rs.next()) {
                    String hrmid_tmp = Util.null2String(rs.getString("hrmids"));//TD9392
                    if (hrmid_tmp.length() != 0) {
                        members.append(",").append(rs.getString("hrmids"));
                    }
                }
                if (!"".equals(members.toString())) {
                    members = new StringBuilder(members.substring(1));
                    members = new StringBuilder(new HrmResourceBaseService().duplicateRemoval(members.toString(), user.getUID() + ""));
                    SWFAccepter = members.toString();
                    SWFTitle = SystemEnv.getHtmlLabelName(15670, user.getLanguage());
                    SWFTitle += ":" + lastname;
                    SWFTitle += "-" + CurrentUserName;
                    SWFTitle += "-" + TODAY;
                    SWFRemark = "<a class='wea-hrm-new-employee-set'  onClick=\"openHrmNewEmployeeSetDialog(" + id + ")\"  style=\"cursor:pointer;\"  id = '" + id + "'>" + Util.fromScreen2(Subject, user.getLanguage()) + "</a>";
                    SWFSubmiter = CurrentUser;
                    SysRemindWorkflow.setPrjSysRemind(SWFTitle, 0, Util.getIntValue(SWFSubmiter), SWFAccepter, SWFRemark);
                }
            }

            //CustomFieldTreeManager.editCustomDataE9Add("HrmCustomFieldByInfoType", -1, fu, Util.getIntValue(id, 0));
            //应聘人员的个人信息18条
            if (!"".equals(rcid)) {
                sql = "select * from HrmCareerApply where id = ?";
                rs.executeQuery(sql, id);
                if (rs.next()) {
                    String birthday = Util.null2String(rs.getString("birthday"));
                    String folk = Util.null2String(rs.getString("folk"));
                    String nativeplace = Util.null2String(rs.getString("nativeplace"));
                    String regresidentplace = Util.null2String(rs.getString("regresidentplace"));

                    String certificatenum = Util.null2String(rs.getString("certificatenum"));
                    String maritalstatus = Util.null2String(rs.getString("maritalstatus"));
                    String policy = Util.null2String(rs.getString("policy"));
                    String bememberdate = Util.null2String(rs.getString("bememberdate"));

                    String bepartydate = Util.null2String(rs.getString("bepartydate"));
                    String islabouunion = Util.null2String(rs.getString("islabouunion"));
                    String educationlevel = Util.null2String(rs.getString("educationlevel"));
                    String degree = Util.null2String(rs.getString("degree"));

                    String healthinfo = Util.null2String(rs.getString("healthinfo"));

                    String height = Util.null2String(rs.getString("height"));
                    if (height.contains(".")) {
                        height = height.substring(0, height.indexOf("."));
                    }
                    String weight = Util.null2String(rs.getString("weight"));
                    if (weight.contains(".")) {
                        weight = weight.substring(0, weight.indexOf("."));
                    }

                    String residentplace = Util.null2String(rs.getString("residentplace"));
                    String homeaddress = Util.null2String(rs.getString("homeaddress"));
                    String tempresidentnumber = Util.null2String(rs.getString("tempresidentnumber"));

                    para = new StringBuilder("" + id + SEPARATOR + birthday + SEPARATOR + folk + SEPARATOR + nativeplace + SEPARATOR + regresidentplace + SEPARATOR + maritalstatus + SEPARATOR + policy + SEPARATOR + bememberdate + SEPARATOR + bepartydate + SEPARATOR + islabouunion + SEPARATOR + educationlevel + SEPARATOR + degree + SEPARATOR + healthinfo + SEPARATOR + height + SEPARATOR + weight + SEPARATOR + residentplace + SEPARATOR + homeaddress + SEPARATOR + tempresidentnumber + SEPARATOR + certificatenum);
                    RecordSet rs1 = new RecordSet();
                    rs1.executeProc("HrmResourcePersonalInfo_Insert", para.toString());
                }
            }
            //更新虚拟组织部门id
            if (departmentvirtualids.length() > 0) {
                //保存前先删除需要删除的数据，因为有managerid 所以不能全部删除再保存
                sql = "delete from hrmresourcevirtual where resourceid=" + id + " and departmentid not in (" + departmentvirtualids + ")";
                rs.execute(sql);

                String[] departmentvirtualid = departmentvirtualids.split(",");
                for (String s : departmentvirtualid) {
                    rs.execute(" select count(*) from HrmResourceVirtual where departmentid ='" + s + "' and resourceid = " + id);
                    if (rs.next()) {
                        //如果已存在 无需处理
                        if (rs.getInt(1) > 0) {
                            continue;
                        }
                    }

                    //写入
                    int tmpid = 0;
                    rs.execute("select max(id) from HrmResourceVirtual ");
                    if (rs.next()) {
                        tmpid = rs.getInt(1) + 1;
                    }
                    String subcompanyid = DepartmentVirtualComInfo.getSubcompanyid1(s);
                    sql = " insert into HrmResourceVirtual (id,resourceid,subcompanyid,departmentid ) " +
                            " values (" + tmpid + "," + id + "," + subcompanyid + "," + s + ")";
                    rs.execute(sql);
                }
            }

            LogUtil.writeBizLog(logger.getBizLogContexts());

            HrmFaceCheckManager.sync(id, HrmFaceCheckManager.getOptInsert(), "hrm_e9_HrmResourceBaseService_addResourceBase", HrmFaceCheckManager.getOaResource());
            //同步RTX端的用户信息.
            new OrganisationCom().checkUser(Util.getIntValue(id));
            new Thread(new OrganisationComRunnable("user", "add", "" + id)).start();
            ResourceComInfo.updateResourceInfoCache("" + id);
            new PluginUserCheck().clearPluginUserCache("messager");
            //OA与第三方接口单条数据同步方法开始
            new HrmServiceManager().SynInstantHrmResource("" + id, "1");
            //OA与第三方接口单条数据同步方法结束

            //新增人员实时同步到CoreMail邮件系统
            //CoreMailAPI.synUser(id);
            retmap.put("status", "1");
            retmap.put("id", id);
        } catch (Exception e) {
            new BaseBean().writeLog("新建人员基本信息错误：" + e);
            retmap.put("status", "-1");
        }
        return retmap;
    }

    private static void updateWorkInfo(String id, User user, Map<String, Object> params) {
        try {
            RecordSet rs = new RecordSet();
            String sql;
            String companystartdate = Util.fromScreen3(Util.null2String(params.get("companystartdate")), user.getLanguage());
            String workstartdate = Util.fromScreen3(Util.null2String(params.get("workstartdate")), user.getLanguage());

            List<String> lsParams = new ArrayList<>();
            lsParams.add(companystartdate.length() == 0 ? null : companystartdate);
            lsParams.add(workstartdate.length() == 0 ? null : workstartdate);
            lsParams.add(id);
            sql = " update hrmresource set companystartdate=?,workstartdate=? where id=?";
            rs.executeUpdate(sql, lsParams);
            HrmDateCheck hrmDateCheck = new HrmDateCheck();
            hrmDateCheck.calWorkInfo(id);
        } catch (Exception e) {
            new BaseBean().writeLog(e);
        }
    }


    /**
     * 建模表转换为人员表集合
     *
     * @param params 建模表数据集合
     * @return
     */
    public static Map<String, Object> convertEcResourceParams(Map<String, Object> params) {
        Map<String, Object> convertParams = new HashMap<>();
        convertParams.put("lastname", RecruitModeUtil.parseBlankToNull(params.get("xm")));
        convertParams.put("sex", RecruitModeUtil.parseBlankToNull(params.get("xb")));
        convertParams.put("mobile", RecruitModeUtil.parseBlankToNull(params.get("sjhm")));
        convertParams.put("email", RecruitModeUtil.parseBlankToNull(params.get("dzyx")));
        convertParams.put("departmentid", RecruitModeUtil.parseBlankToNull(params.get("rzbm")));
        convertParams.put("managerid", RecruitModeUtil.parseBlankToNull(params.get("zjsj")));
        convertParams.put("jobtitle", RecruitModeUtil.parseBlankToNull(params.get("gw")));
        convertParams.put("password", RecruitModeUtil.parseBlankToNull(params.get("xtmm")));
        convertParams.put("loginid", RecruitModeUtil.parseBlankToNull(params.get("xtzh")));
        convertParams.put("status", RecruitModeUtil.parseBlankToNull(params.get("ygzt")));

        // 个人信息
        convertParams.put("certificatenum", RecruitModeUtil.parseBlankToNull(params.get("sfzh")));

        // 工作信息
        convertParams.put("companystartdate", RecruitModeUtil.parseBlankToNull(params.get("rzrq")));
        convertParams.put("probationenddate", RecruitModeUtil.parseBlankToNull(params.get("jhzzrq")));
        return convertParams;
    }

}
