package com.engine.organization.util.relation;

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.crm.CrmShareBase;
import weaver.file.Prop;
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.CusFormSetting;
import weaver.system.CusFormSettingComInfo;
import weaver.system.SysRemindWorkflow;
import weaver.systeminfo.SystemEnv;
import weaver.systeminfo.setting.HrmUserSettingComInfo;

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> retmap = new HashMap<>();
        RecordSet rs = new RecordSet();
        String sql;
        try {
            DepartmentComInfo departmentComInfo = new DepartmentComInfo();
            boolean canEdit = HrmUserVarify.checkUserRight("HrmResourceEdit:Edit", user);
            if (!canEdit) {
                retmap.put("status", "-1");
                retmap.put("message", SystemEnv.getHtmlLabelName(22620, user.getLanguage()));
                return retmap;
            }
            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) {
                retmap.put("status", "-1");
                retmap.put("message", SystemEnv.getHtmlLabelName(84760, user.getLanguage()));
                return retmap;
            }


            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) {
                        retmap.put("status", "-1");
                        retmap.put("message", SystemEnv.getHtmlLabelName(15094, user.getLanguage()));
                        return retmap;
                    }
                }
            }

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


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

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


            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)) {
                        retmap.put("status", "-1");
                        retmap.put("message", SystemEnv.getHtmlLabelName(515420, user.getLanguage()));
                        return retmap;
                    }
                }
            }

            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 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 (org.apache.commons.lang3.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);

                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();
                }
            }

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

    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());
            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;
    }

    public static Map<String, Object> editResourceBase(User user, Map<String, Object> params) {
        Map<String, Object> retMap = new HashMap<>();
        try {
            String id = Util.null2String(params.get("id"));
            // 判断是否为本人操作
            boolean canEdit = HrmUserVarify.checkUserRight("HrmResourceEdit:Edit", user);
            if (!canEdit && !Util.null2String(user.getUID()).equals(id)) {
                retMap.put("status", "-1");
                retMap.put("message", "" + weaver.systeminfo.SystemEnv.getHtmlLabelName(22620, weaver.general.ThreadVarLanguage.getLang()) + "");
                return retMap;
            }
            RecordSet rs = new RecordSet();
            DepartmentComInfo DepartmentComInfo = new DepartmentComInfo();
            ResourceComInfo ResourceComInfo = new ResourceComInfo();
            HrmServiceManager HrmServiceManager = new HrmServiceManager();
            CrmShareBase CrmShareBase = new CrmShareBase();

            StringBuilder para;

            if (id.length()==0) {
                retMap.put("status", "-1");
                retMap.put("message", ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(22620,weaver.general.ThreadVarLanguage.getLang())+"");
                return retMap;
            }
            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 resourceimageBase64 = Util.null2String(params.get("resourceimageBase64"));
            if(resourceimageBase64.length()>0){
                resourceimageid = ServiceUtil.saveResourceImage(resourceimageBase64);
            }
            String oldresourceimageid = Util.null2String(params.get("oldresourceimage"));
            if ("".equals(resourceimageid)) {
                resourceimageid = oldresourceimageid;
            }
            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());
            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 email = Util.fromScreen3(Util.null2String(params.get("email")), user.getLanguage());
            String dsporder = Util.fromScreen3(Util.null2String(params.get("dsporder")), user.getLanguage());
            String jobcall = Util.fromScreen3(Util.null2String(params.get("jobcall")), user.getLanguage());
            String systemlanguage = Util.fromScreen3(Util.null2String(params.get("systemlanguage")), user.getLanguage());
            if ("".equals(systemlanguage) || "0".equals(systemlanguage)) {
                systemlanguage = "7";
            }
            String accounttype = Util.fromScreen3(Util.null2String(params.get("accounttype")), user.getLanguage());
            String belongto = Util.fromScreen3(Util.null2String(params.get("belongto")), user.getLanguage());
            if (dsporder.length() == 0) {
                dsporder = id;
            }
            if ("0".equals(accounttype)) {
                belongto = "-1";
            }


            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;
            }


            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.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);//吸入操作前日志

            //Td9325,解决多账号次账号没有登陆Id在浏览框组织结构中无法显示的问题。
            String oldbelongto = "";
            boolean falg = false;
            String loginid = "";
            rs.execute("select * from HrmResource where id =" + id);
            if (rs.next()) {
                loginid = rs.getString("loginid");
                float idsporder = rs.getFloat("dsporder");
                if (idsporder <= 0) {
                    dsporder = rs.getString("id");
                } else {
                    dsporder = "" + idsporder;
                }

                String thisAccounttype = rs.getString("accounttype");
                if ("1".equals(thisAccounttype) && "0".equals(accounttype)) {
                    oldbelongto = rs.getString("belongto");
                }
            }

            if ("1".equals(accounttype) && "".equalsIgnoreCase(loginid)) {
                rs.execute("select loginid from HrmResource where id =" + belongto);
                if (rs.next()) {
                    loginid = rs.getString(1);
                }

                if (!"".equals(loginid)) {
                    loginid = loginid + (id + 1);
                    falg = true;
                }
            }
            String sql = "select * from HrmResource where id = " + Util.getIntValue(id);
            rs.execute(sql);
            String oldmanagerid = "";
            String oldmanagerstr = "";
            while (rs.next()) {
                oldmanagerid = rs.getString("managerid");
                oldmanagerstr = rs.getString("managerstr");
                // 处理managerstr 不以逗号开始或者结束的情况 形如 managerstr：8 begin
                if (!oldmanagerstr.startsWith(",")) {
                    oldmanagerstr = "," + oldmanagerstr;
                }
                if (!oldmanagerstr.endsWith(",")) {
                    oldmanagerstr = oldmanagerstr + ",";
                }
                // 处理managerstr 不以逗号开始或者结束的情况 形如 managerstr：8 end
            }
            //mysql报错问题java.sql.SQLException: Incorrect integer value: '' for column 'COSTCENTERID' at row 1
            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 (StringUtils.isNotEmpty(workcode)) {
                CodeRuleManager.getCodeRuleManager().checkReservedIfDel(RuleCodeType.USER.getValue(), 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 + systemlanguage
                    + SEPARATOR + accounttype + SEPARATOR + belongto + SEPARATOR + email + SEPARATOR + dsporder + SEPARATOR + mobileshowtype);
            RecordSetTrans rst = new RecordSetTrans();
            rst.setAutoCommit(false);
            try {
                rst.executeProc("HrmResourceBasicInfo_Update", para.toString());
                if(Util.null2String(locationid).length()>0) {
                    rst.executeSql("update hrmresource set countryid=(select countryid from HrmLocations where id=" + locationid + ") 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();
            }

            if(!"7".equals(systemlanguage) && StringUtils.isNotBlank(systemlanguage)){
                User.setUserLang(Util.getIntValue(id),Util.getIntValue(systemlanguage, 7));
            }

            //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();
            }

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

            rst = new RecordSetTrans();
            rst.setAutoCommit(false);
            try {
                para = new StringBuilder("" + id + SEPARATOR + managerstr);
                rst.executeProc("HrmResource_UpdateManagerStr", para.toString());
                rst.commit();
            } catch (Exception e) {
                rst.rollback();
                e.printStackTrace();
            }

            managerid = Util.null2String(managerid).trim();
            oldmanagerid = Util.null2String(oldmanagerid).trim();
            if(!managerid.equals(oldmanagerid) && !(("".equals(managerid) || "0".equals(managerid)) && ("".equals(oldmanagerid) || "0".equals(oldmanagerid)))){
                String temOldmanagerstr = "," + id + oldmanagerstr;
                temOldmanagerstr = temOldmanagerstr.endsWith(",") ? temOldmanagerstr : (temOldmanagerstr + ",");
                sql = "select id,departmentid,subcompanyid1,managerid,seclevel,managerstr from HrmResource where managerstr like '%" + temOldmanagerstr + "'";
                rs.execute(sql);
                while (rs.next()) {
                    String nowmanagerstr = Util.null2String(rs.getString("managerstr"));
                    // 处理managerstr 不以逗号开始或者结束的情况 形如 managerstr：8 begin
                    if (!nowmanagerstr.startsWith(",")) {
                        nowmanagerstr = "," + nowmanagerstr;
                    }
                    if (!nowmanagerstr.endsWith(",")) {
                        nowmanagerstr = nowmanagerstr + ",";
                    }
                    // 处理managerstr 不以逗号开始或者结束的情况 形如 managerstr：8 end
                    String resourceid = rs.getString("id");
                    //指定上级为自身的情况，不更新自身上级
                    if (id.equals(resourceid)) {
                        continue;
                    }
                    String nowmanagerstr2 = "";
                    int index = nowmanagerstr.lastIndexOf(oldmanagerstr);
                    if (index != -1) {
                        if (!"".equals(managerstr)) {
                            nowmanagerstr2 = nowmanagerstr.substring(0, index) + ("".equals(oldmanagerstr) ? managerstr.substring(1) : managerstr);
                        } else {
                            nowmanagerstr2 = nowmanagerstr.substring(0, index) + ("".equals(oldmanagerstr) ? "" : ",");
                        }
                    }
                    rst = new RecordSetTrans();
                    rst.setAutoCommit(false);
                    try {
                        para = new StringBuilder(resourceid + SEPARATOR + nowmanagerstr2);
                        rst.executeProc("HrmResource_UpdateManagerStr", para.toString());
                        rst.commit();
                        ResourceComInfo.updateResourceInfoCache(resourceid); //更新缓存
                    } catch (Exception e) {
                        rst.rollback();
                        e.printStackTrace();
                    }
                }
            }

            String subcmpanyid1 = DepartmentComInfo.getSubcompanyid1(departmentid);
            para = new StringBuilder("" + id + SEPARATOR + subcmpanyid1);
            rst = new RecordSetTrans();
            rst.setAutoCommit(false);
            try {
                rst.executeProc("HrmResource_UpdateSubCom", para.toString());
                rst.commit();
            } catch (Exception e) {
                rst.rollback();
                e.printStackTrace();
            }

            if(!managerid.equals(oldmanagerid) && !(("".equals(managerid) || "0".equals(managerid)) && ("".equals(oldmanagerid) || "0".equals(oldmanagerid)))){//修改人力资源经理，对客户和日程共享重新计算
                CrmShareBase.setShareForNewManager(id);
            }
            boolean formdefined = false;
            CusFormSettingComInfo CusFormSettingComInfo = new weaver.system.CusFormSettingComInfo();
            CusFormSetting CusFormSetting = CusFormSettingComInfo.getCusFormSetting("hrm", "HrmResourceBase");
            if (CusFormSetting != null) {
                if (CusFormSetting.getStatus() == 2) {
                    //自定义布局页面
                    formdefined = true;
                }
            }
            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());

            new Thread(new OrganisationComRunnable("user", "editbasicinfo", id + "-" + status)).start();
            // 改为自进行修正
            ResourceComInfo.updateResourceInfoCache(id);

            try {
                //OA与第三方接口单条数据同步方法开始
                HrmServiceManager.SynInstantHrmResource(id, "2");
                //OA与第三方接口单条数据同步方法结束
            } catch (Exception e) {
                new BaseBean().writeLog("OA与第三方接口单条数据同步失败" + e);
            }


            //处理次账号修改为主账号时，检查次账号所属 主账号的 其他设置是否需要修改 add by kzw QC159888
            try {
                if (!"".equals(oldbelongto)) {
                    HrmUserSettingComInfo userSetting = new HrmUserSettingComInfo();
                    String belongtoshow = userSetting.getBelongtoshowByUserId(oldbelongto);
                    if ("1".equals(belongtoshow)) {
                        rs.execute("select id from hrmresource where belongto = " + oldbelongto);
                        if (!rs.next()) {
                            String setId = userSetting.getId(oldbelongto);
                            rs.execute("update HrmUserSetting set belongtoshow=0  where id=" + setId);
                            userSetting.removeHrmUserSettingComInfoCache();
                        }
                    }
                }
            } catch (Exception e) {
                new BaseBean().writeLog(e.getMessage());
            }

            rs.execute("update HrmResource set " + DbFunctionUtil.getUpdateSetSql(rs.getDBType(), user.getUID()) + " where id=" + id);
            rs.execute("update HrmResourceManager set " + DbFunctionUtil.getUpdateSetSql(rs.getDBType(), user.getUID()) + " where id=" + id);

            //写入操作后日志
            LogUtil.writeBizLog(logger.getBizLogContexts());

            HrmFaceCheckManager.sync(id, HrmFaceCheckManager.getOptUpdate(), "hrm_e9_HrmResourceBaseService_editResourceBase", HrmFaceCheckManager.getOaResource());

            retMap.put("status", "1");
            retMap.put("id", id);
        } catch (Exception e) {
            new BaseBean().writeLog(e);
            retMap.put("status", "-1");
            retMap.put("message", ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(22620,weaver.general.ThreadVarLanguage.getLang())+"");
        }
        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);
        }
    }

    public static Map<String,Object> convertEcResourceParams(Map<String, Object> params){
        // 先查询原有EC人员信息，再封装传参
        Map<String, Object> convertParams = new HashMap<>();
        String jclResourceId  = Util.null2String(params.get("id"));
        // 更新人员时，初始化人员参数
        if (StringUtils.isNotBlank(jclResourceId)) {
            RecordSet rs = new RecordSet();
            rs.execute("select * from hrmresource where id = '" + jclResourceId + "'");
            int colcount = rs.getColCounts();
            if (rs.next()) {
                for (int i = 1; i <= colcount; i++) {
                    convertParams.put(rs.getColumnName(i).toLowerCase(), Util.null2String(rs.getString(i)));
                }
            }
        }


        // 部门ID
        convertParams.put("departmentid",params.get("ec_department"));
        // EC岗位
        String jclJobId = Util.null2String(params.get("job_title"));
        String ecJobId = "1";
        if (StringUtils.isNotBlank(jclJobId)) {
            ecJobId = EcHrmRelationUtil.getEcJobId(Long.parseLong(jclJobId));
        }
        convertParams.put("jobtitle",ecJobId);

        convertParams.put("workcode",params.get("work_code"));
        convertParams.put("lastname",params.get("last_name"));
        convertParams.put("sex",params.get("sex"));
        convertParams.put("status",params.get("status"));
        convertParams.put("accounttype",params.get("account_type"));
        convertParams.put("belongto",params.get("belong_to"));
        convertParams.put("locationid",params.get("location_id"));
        convertParams.put("dsporder",params.get("show_order"));
        convertParams.put("companystartdate",params.get("company_start_date"));
        convertParams.put("workstartdate",params.get("work_start_date"));
        convertParams.put("resourceimageid",params.get("resource_image_id"));
        convertParams.put("jobactivitydesc",params.get("job_activity_desc"));

        convertParams.put("mobile",params.get("mobile"));
        convertParams.put("telephone",params.get("telephone"));
        convertParams.put("email",params.get("email"));

        // 直接上级
        convertParams.put("managerid", params.get("manager_id"));


        return convertParams;
    }
}
