package com.engine.organization.util.saveimport.hrmimport;

import com.engine.common.entity.EncryptFieldEntity;
import com.engine.common.service.impl.HrmCommonServiceImpl;
import com.engine.common.util.ParamUtil;
import com.engine.encrypt.biz.EncryptFieldConfigComInfo;
import com.engine.hrm.entity.RuleCodeType;
import com.engine.hrm.util.CodeRuleManager;
import com.engine.hrm.util.HrmTriggerUtil;
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.engine.organization.entity.jclimport.po.JclImportHistoryDetailPO;
import com.engine.organization.mapper.jclimport.JclImportHistoryDetailMapper;
import com.engine.organization.mapper.jclimport.JclImportHistoryMapper;
import com.engine.organization.util.db.MapperProxyFactory;
import com.weaver.integration.ldap.sync.oa.OaSync;
import com.weaver.integration.ldap.util.AuthenticUtil;
import ln.LN;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import weaver.common.StringUtil;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.encrypt.EncryptUtil;
import weaver.general.BaseBean;
import weaver.general.PasswordUtil;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.common.DbFunctionUtil;
import weaver.hrm.common.database.dialect.DbDialectFactory;
import weaver.hrm.common.database.dialect.DialectUtil;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.definedfield.HrmFieldManager;
import weaver.hrm.job.JobActivitiesComInfo;
import weaver.hrm.job.JobGroupsComInfo;
import weaver.hrm.job.JobTitlesComInfo;
import weaver.hrm.job.UseKindComInfo;
import weaver.hrm.location.LocationComInfo;
import weaver.hrm.passwordprotection.manager.HrmResourceManager;
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.join.hrm.in.HrmResource;
import weaver.join.hrm.in.HrmResourceVo;
import weaver.join.hrm.in.ImportLog;
import weaver.join.hrm.in.processImpl.HrmTlevelManager;
import weaver.rtx.OrganisationCom;
import weaver.systeminfo.SystemEnv;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HrmImportProcessE9 extends BaseBean {


    private final Map<String, Integer> keyMap = new HashMap<>();           //看数据库是否有重复，将数据库现有的数据查出<id,workcode_lastname>

    private final Map<String, String> isADAccountMap = new HashMap<>();

    private final Map<String, Integer> certificateNums = new HashMap<>();//已存在的身份证

    Map<String, Map<String, String>> checkInfos = new HashMap<>();

    private final String[] checkKeys = new String[]{"loginid", "workcode"};

    private Map<String, JSONObject> baseTypeMap;                    //基础信息自定义字段数据库类型与字段名称映射<fieldName,dbtype>

    private Map<String, JSONObject> personTypeMap;                  //个人信息自定义字段数据库类型与字段名称映射<fieldName,dbtype>

    private Map<String, JSONObject> workTypeMap;                    //工作信息自定义字段数据库类型与字段名称映射

    private final String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

    private OrganisationCom rtxService = null;   //添加到rtx

    private int userlanguage = 7;   //登录语言

    char separator = Util.getSeparator();

    LN license = new LN();           //license

    String keyField = "";
    String operateType = "";

    private HrmResourceVo vo = null;

    private String multilanguage;

    private Map<String, Integer> sysLanguage = null;

    private Map<String, Integer> jobcallMap = null;
    private Map<String, Integer> locationMap = null;
    private Map<String, Integer> usekindMap = null;
    private Map<String, Integer> educationlevelMap = null;

    private int cnLanguageId = 7;

    private User user;
    private int pId = 0;
    private int rowNum = 0;

    //判断弱密码
    private HrmWeakPasswordUtil hrmWeakPasswordUtil;

    public void setUser(User user) {
        this.user = user;
    }

    public Map<String, Object> init(HttpServletRequest request, Long importHistoryId) {
        Map<String, Object> retmap = new HashMap<>();
        try {
            this.user = (User) request.getSession(true).getAttribute("weaver_user@bean");
            this.keyField = Util.null2String(request.getParameter("keyField"));
            this.operateType = Util.null2String(request.getParameter("operateType"));

            Map<String, Object> params = ParamUtil.request2Map(request);
            params.put("operateType", this.operateType);
            this.pId = importHistoryId.intValue();


            LN license = new LN();
            license.InLicense();
            RecordSet recordSet = new RecordSet();


            String sql = "select multilanguage,(select id from syslanguage where language='简体中文' or language='中文') as cnLanguageId from license ";
            recordSet.execute(sql);
            recordSet.next();
            multilanguage = recordSet.getString("multilanguage");
            cnLanguageId = recordSet.getInt(2);

            sysLanguage = new HashMap<>();
            recordSet.execute("select id,language from syslanguage where activable=1");
            while (recordSet.next()) {
                sysLanguage.put(recordSet.getString(2), recordSet.getInt(1));
            }

            educationlevelMap = new HashMap<>();

            String educationName = "convToMultiLang(name,7)";
            if ("sqlserver".equalsIgnoreCase(recordSet.getDBType())) {
                educationName = "dbo.convToMultiLang(name,7)";
            }


            recordSet.execute(String.format("select id,%s from HrmEducationLevel", educationName));

            while (recordSet.next()) {
                educationlevelMap.put(recordSet.getString(2), recordSet.getInt(1));
            }


            jobcallMap = new HashMap<>();
            if ("sqlserver".equalsIgnoreCase(recordSet.getDBType())) {
                recordSet.execute("select id,dbo.convToMultiLang(name,7) from HrmJobCall");
            } else {
                recordSet.execute("select id,convToMultiLang(name,7) from HrmJobCall");
            }
            while (recordSet.next()) {
                jobcallMap.put(recordSet.getString(2), recordSet.getInt(1));
            }

            locationMap = new HashMap<>();
            if ("sqlserver".equalsIgnoreCase(recordSet.getDBType())) {
                recordSet.execute("select id,dbo.convToMultiLang(locationname,7) from HrmLocations where countryid=1");
            } else {
                recordSet.execute("select id,convToMultiLang(locationname,7) from HrmLocations where countryid=1");
            }
            while (recordSet.next()) {
                locationMap.put(recordSet.getString(2), recordSet.getInt(1));
            }

            usekindMap = new HashMap<>();
            if ("sqlserver".equalsIgnoreCase(recordSet.getDBType())) {
                recordSet.execute("select id,dbo.convToMultiLang(name,7) from HrmUseKind");
            } else {
                recordSet.execute("select id,convToMultiLang(name,7) from HrmUseKind");
            }
            while (recordSet.next()) {
                usekindMap.put(recordSet.getString(2), recordSet.getInt(1));
            }

        } catch (Exception e) {
            writeLog(e);
        }
        return retmap;
    }

    /**
     * 对人员数据进行解析，并添加到数据库
     *
     * @param hrMap 人员数据Map集合
     * @return List
     */
    public void processMap(Map<String, HrmResourceVo> hrMap) {//增加同步锁，防止同时多次调用
        List<ImportLog> resultList = new ArrayList<>();          //导入结果
        RecordSet recordSet = new RecordSet();
        try {
            String subCompanyName = "";      //分部名称
            String departmentName = "";      //部门名称
            int subcompanyid1 = 0;           // 分部Id
            int departmentid = 0;            // 部门id
            String key;                   // workcode_lastname 组合
            getKeyMap(keyField);             //获取重复性验证字段Map
            int id;
            rtxService = new OrganisationCom();

            final ResourceComInfo resourcecominfo = new ResourceComInfo();
            DepartmentComInfo departmentComInfo = new DepartmentComInfo();
            SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo();
            JobActivitiesComInfo jobActivitiesComInfo = new JobActivitiesComInfo();
            JobTitlesComInfo jobTitlesComInfo = new JobTitlesComInfo();
            JobGroupsComInfo jobGroupsComInfo = new JobGroupsComInfo();
            LocationComInfo locationComInfo = new LocationComInfo();
            UseKindComInfo useKindComInfo = new UseKindComInfo();

            Set<String> keySet = hrMap.keySet();
            Object[] keyArray = keySet.toArray();

            Class<HrmResource> hrmClass = HrmResource.class;
            Class<HrmResourceVo> voClass = HrmResourceVo.class;

            String field = "id,subcompanyid1,departmentid,workcode,lastname,"
                    + "loginid,password,seclevel,sex,jobtitle,jobcall,joblevel,"
                    + "jobactivitydesc,managerid,assistantid,status,locationid,workroom,"
                    + "telephone,mobile,mobilecall,fax,email,"
                    + "systemlanguage,birthday,folk,nativeplace,regresidentplace,"
                    + "certificatenum,maritalstatus,policy,bememberdate,bepartydate,"
                    + "islabouunion,educationlevel,degree,healthinfo,height,weight,"
                    + "usekind,startdate,enddate,probationenddate,"//add by lvyi
                    + "residentplace,homeaddress,tempresidentnumber,"
                    + "datefield1,datefield2,datefield3,datefield4,datefield5,"
                    + "textfield1,textfield2,textfield3,textfield4,textfield5,"
                    + "numberfield1,numberfield2,numberfield3,numberfield4,numberfield5,"
                    + "tinyintfield1,tinyintfield2,tinyintfield3,tinyintfield4,tinyintfield5,"
                    + "companystartdate,workstartdate,"
                    + "accumfundaccount,accounttype,belongto,accountname,bankid1,accountid1,dsporder,classification";

            String[] fields = field.split(",");

            int createrid = 1; // 创建者id
            int lastmodid = 1; // 最后修改者id
            if (user != null) {
                createrid = user.getUID();
                lastmodid = user.getUID();
            }

            String lastmoddate = date; // 最后修改时间

            ChgPasswdReminder reminder = new ChgPasswdReminder();
            RemindSettings settings = reminder.getRemindSettings();
            //判断是否启用【启用初始密码】
            //是否启用初始密码：false-不启用初始密码、true-启用初始密码
            boolean defaultPasswordEnable = "1".equals(Util.null2String(settings.getDefaultPasswordEnable()));
            //初始密码
            //初始密码
            String defaultPassword = Util.null2String(settings.getDefaultPassword());
            //判断是否启用【弱密码禁止保存】
            //弱密码禁止保存：false-允许保存弱密码、true-不允许保存弱密码
            boolean weakPasswordDisable = "1".equals(Util.null2String(settings.getWeakPasswordDisable()));
            try {
                //判断是否为弱密码
                hrmWeakPasswordUtil = new HrmWeakPasswordUtil();
            } catch (Exception e) {
                writeLog(e);
            }

            Object obj;
            HrmResource hrm;
            for (Object o : keyArray) {
                obj = o;
                vo = hrMap.get((String) obj);
                key = (String) obj;
                hrm = new HrmResource();
                this.rowNum++;
                //TimeUnit.SECONDS.sleep(1);
                try {  // 异常处理

                    if ("add".equals(operateType)) {

                        if (keyMap.get(key) != null) {
                            resultList.add(createLog(vo, "创建", "失败", SystemEnv.getHtmlLabelName(83520, userlanguage)));
                            continue;
                        }

                        if (this.checkInfo(vo, resultList)) {
                            continue;
                        }
                        if (vo.getAccounttype() == null || "".equalsIgnoreCase(Util.null2String(vo.getAccounttype()))) {
                            if (StringUtil.isNotNull(vo.getCertificatenum()) && certificateNums.get(StringUtil.vString(vo.getCertificatenum())) != null) {
                                resultList.add(createLog(vo, "创建", "失败", SystemEnv.getHtmlLabelName(83521, userlanguage)));
                                continue;
                            }
                        } else {
                            if (vo.getAccounttype() != null && !"".equals(vo.getAccounttype())) {
                                if ("主账号".equals(vo.getAccounttype())) {
                                    if (StringUtil.isNotNull(vo.getCertificatenum()) && certificateNums.get(StringUtil.vString(vo.getCertificatenum())) != null) {
                                        resultList.add(createLog(vo, "创建", "失败", SystemEnv.getHtmlLabelName(83521, userlanguage)));
                                        continue;
                                    }
                                }
                            }
                        }

                        //添加人员信息 license 人员上限判断

                        if (keyMap.get(key) == null && StringUtils.isNotBlank(vo.getLoginid())
                                && ("主账号".equals(vo.getAccounttype()) || StringUtils.isBlank(vo.getAccounttype()))
                                && "正式,试用,临时,试用延期".contains(Util.null2String(vo.getStatus()))) {
                            license.reloadLicenseInfo();
                            if (license.CkHrmnum() >= 0) {
                                resultList.add(createLog(vo, "创建", "失败", SystemEnv.getHtmlLabelName(83522, userlanguage)));
                                continue;
                            }
                        }
                        // 分部Id
                        String subCompanyNames = vo.getSubcompanyid1();
                        String tempSubCompanyName = "";
                        if (subCompanyNames != null) {
                            if (!subCompanyNames.equals(subCompanyName)) {
                                tempSubCompanyName = subCompanyName;
                                subCompanyName = subCompanyNames;
                                subcompanyid1 = getSubCompanyId(subCompanyName);
                            }
                            if (subcompanyid1 == 0) {
                                resultList.add(createLog(vo, "创建", "失败", "分部未找到"));
                                continue;
                            }

                            if (subcompanyid1 == -9) {
                                resultList.add(createLog(vo, "创建", "失败", SystemEnv.getErrorMsgName(56, userlanguage)));
                                continue;
                            }
                            if (subcompanyid1 == -2) {
                                resultList.add(createLog(vo, "创建", "失败", SystemEnv.getHtmlLabelName(126274, userlanguage)));
                                continue;
                            }
                            if (subcompanyid1 == -1) {
                                resultList.add(createLog(vo, "创建", "失败", SystemEnv.getHtmlLabelName(83524, userlanguage)));
                                continue;
                            }
                            if (StringUtil.parseToInt(license.getConcurrentFlag(), 0) != 1) {
                                if (new HrmResourceManager().noMore(String.valueOf(subcompanyid1))) {
                                    resultList.add(createLog(vo, "创建", "失败", SystemEnv.getHtmlLabelName(83525, userlanguage)));
                                    continue;
                                }
                            }
                            hrm.setSubcompanyid1(subcompanyid1);
                        } else {
                            resultList.add(createLog(vo, "创建", "失败", SystemEnv.getHtmlLabelName(83526, userlanguage)));
                            continue;
                        }

                        // 部门id
                        String departmentNames = vo.getDepartmentid();
                        if (departmentNames != null) {
                            if (!subCompanyNames.equals(tempSubCompanyName) || !departmentNames.equals(departmentName)) {
                                departmentName = departmentNames;
                                departmentid = getDeptId(departmentName, subcompanyid1);
                            }
                            if (departmentid == 0) {
                                resultList.add(createLog(vo, "创建", "失败", SystemEnv.getHtmlLabelName(83537, userlanguage)));
                                continue;
                            }

                            if (departmentid == -2) {
                                resultList.add(createLog(vo, "创建", "失败", SystemEnv.getHtmlLabelName(126275, userlanguage)));
                                continue;
                            }
                            hrm.setDepartmentid(departmentid);
                        } else {
                            resultList.add(createLog(vo, "创建", "失败", SystemEnv.getHtmlLabelName(83527, userlanguage)));
                            continue;
                        }

                        if (vo.getLastname() == null) {
                            resultList.add(createLog(vo, "创建", "失败", SystemEnv.getHtmlLabelName(83529, userlanguage)));
                            continue;
                        }

                        //主账号id-sunjsh
                        if (vo.getAccounttype() != null && !"".equals(vo.getAccounttype())) {
                            if ("主账号".equals(vo.getAccounttype())) {
                                hrm.setBelongto(-1);
                                hrm.setAccounttype(0);
                            } else if ("次账号".equals(vo.getAccounttype())) {
                                if (vo.getBelongto() != null && !"".equals(vo.getBelongto().trim())) {
                                    int belongto = getBelongId(vo.getBelongto(), keyField);
                                    hrm.setBelongto(belongto);
                                    if (!"".equals(vo.getBelongto()) && belongto == 0) {
                                        resultList.add(createLog(vo, "创建", "失败", SystemEnv.getHtmlLabelName(131279, userlanguage)));
                                        continue;
                                    } else {
                                        hrm.setAccounttype(1);
                                    }
                                } else {
                                    resultList.add(createLog(vo, "创建", "失败", SystemEnv.getHtmlLabelName(131279, userlanguage)));
                                    continue;
                                }
                            } else {
                                hrm.setBelongto(-1);
                                hrm.setAccounttype(0);
                            }
                        } else if (vo.getBelongto() != null && !"".equals(vo.getBelongto().trim())) {
                            int belongto = getBelongId(vo.getBelongto(), keyField);
                            hrm.setBelongto(belongto);
                            if (!"".equals(vo.getBelongto()) && belongto == 0) {
                                resultList.add(createLog(vo, "创建", "失败", SystemEnv.getHtmlLabelName(131279, userlanguage)));
                                continue;
                            } else {
                                hrm.setAccounttype(1);
                            }
                        } else {
                            hrm.setBelongto(-1);
                            hrm.setAccounttype(0);
                        }

                        // 岗位id
                        if (vo.getJobtitle() != null && vo.getJobactivityid() != null && vo.getJobgroupid() != null) {
                            int jobtitle = getJobTitles(vo.getJobtitle(), vo
                                    .getJobactivityid(), vo.getJobgroupid());
                            hrm.setJobtitle(jobtitle);
                        } else {
                            resultList.add(createLog(vo, "创建", "失败", SystemEnv.getHtmlLabelName(83531, userlanguage)));
                            continue;
                        }

                        //上级id
                        if (vo.getManagerid() != null) {
                            int managerid = 0;           // 上级Id
                            String managerstr = "";       //所有上级
                            Map<String, Comparable> managerInfo = getManagerIdAndStr("", vo.getManagerid(), keyField);
                            if (managerInfo != null) {
                                managerid = managerInfo.get("managerid") != null ? (Integer) managerInfo.get("managerid") : 0;
                                managerstr = (String) (managerInfo.get("managerstr") != null ? managerInfo.get("managerstr") : "");
                            }
                            hrm.setManagerid(managerid);
                            hrm.setManagerstr(managerstr);

                            //如果vo.getManagerid()有值，但manageid未找到，说明填写有误
                            if (!"".equals(vo.getManagerid()) && managerid == 0) {
                                resultList.add(createLog(vo, "创建", "失败", SystemEnv.getHtmlLabelName(83532, userlanguage)));
                                continue;
                            }
                        } else {

                            hrm.setManagerid(0);
                            hrm.setManagerstr("");
                        }

                        // 助理id
                        if (vo.getAssistantid() != null) {
                            int assistantid;
                            assistantid = getAssistantid(vo.getAssistantid(), keyField);
                            hrm.setAssistantid(assistantid);
                            if (!"".equals(vo.getAssistantid()) && assistantid == 0) {
                                resultList.add(createLog(vo, "创建", "失败", SystemEnv.getHtmlLabelName(24678, userlanguage)));
                                continue;
                            }
                        }

                        // 办公地点
                        if (vo.getLocationid() != null) {
                            int locationid = getLocationid(vo.getLocationid());
                            hrm.setLocationid(locationid);
                        } else {
                            resultList.add(createLog(vo, "创建", "失败", SystemEnv.getHtmlLabelName(83533, userlanguage)));
                            continue;
                        }

                        //邮箱-sunjsh
                        if (vo.getEmail() != null) {
                            if (!"".equals(vo.getEmail().trim()) && vo.getEmail().contains("*")) {
                                vo.setEmail(null);
                            } else if ("".equals(vo.getEmail().trim())) {
                                hrm.setEmail("");
                            } else {
                                Pattern pattern = Pattern.compile("^([a-zA-Z0-9_\\-]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(?)$");
                                Matcher matcher = pattern.matcher(vo.getEmail());
                                if (!matcher.matches()) {
                                    resultList.add(createLog(vo, "创建", "失败", SystemEnv.getHtmlLabelName(24570, userlanguage)));
                                    continue;
                                } else {
                                    hrm.setEmail(vo.getEmail());
                                }
                            }
                        }

                        //mobile-sunjsh
                        if (vo.getMobile() != null) {
                            if ("".equals(vo.getMobile().trim()) || (!"".equals(vo.getMobile().trim()) && vo.getMobile().contains("*"))) {
                                vo.setMobile(null);
                            }
                        } else {
                            hrm.setMobile("");
                        }

                        //工资银行-sunjsh
                        if (vo.getBankid1() != null && !"".equals(vo.getBankid1())) {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("fieldid", 0);
                            jsonObject.put("fieldhtmltype", 3);
                            jsonObject.put("type", 284);
                            jsonObject.put("dmlurl", "");
                            jsonObject.put("fieldvalue", vo.getBankid1());

                            String fieldvalue = HrmFieldManager.getReallyFieldvalue(jsonObject);
                            if (!"".equals(fieldvalue)) {
                                hrm.setBankid1(new Integer(fieldvalue));
                            } else {
//                                vo.setBankid1(null);
                                hrm.setBankid1(this.getBankId(vo.getBankid1()));
                            }
                        }

                        //sunjsh-入职日期
                        if (vo.getCompanystartdate() != null && !"".equals(vo.getCompanystartdate())) {
                            hrm.setCompanystartdate(vo.getCompanystartdate());
//                            hrm.setCompanyworkyear(this.calculateDate(vo.getCompanystartdate()));
                        }

                        //sunjsh-参加工作日期
                        if (vo.getWorkstartdate() != null && !"".equals(vo.getWorkstartdate())) {
                            hrm.setWorkstartdate(vo.getWorkstartdate());
//                            hrm.setWorkyear(this.calculateDate(vo.getWorkstartdate()));
                        }
                        // 性别，为空或其他情况统一为0(男)
                        String sex = "女".equals(vo.getSex()) ? "1" : "0";
                        hrm.setSex(sex);

                        // 职称
                        if (vo.getJobcall() != null) {
                            int jobcall = getJobcall(vo.getJobcall());
                            hrm.setJobcall(jobcall);
                        }
                        // 系统语言，默认简体中文
                        if (vo.getSystemlanguage() != null) {
                            int systemlanguage = getSystemlanguage(vo.getSystemlanguage());

                            if (systemlanguage == -1) {    //只能选择简体中文|Englisth|繁体中文
                                resultList.add(createLog(vo, "创建", "失败", SystemEnv.getHtmlLabelName(518929, userlanguage)));
                                continue;
                            }
                            if (systemlanguage == 0) {    //系统不支持多语言
                                resultList.add(createLog(vo, "创建", "失败", SystemEnv.getHtmlLabelName(84810, userlanguage)));
                                continue;
                            }
                            hrm.setSystemlanguage(systemlanguage);
                        } else {
                            hrm.setSystemlanguage(7);
                        }

                        // 婚姻状况，如果不是以下选项，则默认为未婚
                        String maritalstatus = "已婚".equals(vo.getMaritalstatus()) ? "1"
                                : "离异".equals(vo.getMaritalstatus()) ? "2" : "0";
                        hrm.setMaritalstatus(maritalstatus);

                        // 员工状态
                        if (!"".equals(Util.null2String(vo.getStatus()))) {
                            int status = getStatus(vo.getStatus());
                            hrm.setStatus(status);
                        } else {
                            hrm.setStatus(1);
                        }

                        // 人员密级
                        if (!"".equals(Util.null2String(vo.getClassification()))) {
                            int classification = getClassification(vo.getClassification());
                            hrm.setClassification(classification);
                        }
                        // 学历
                        if (vo.getEducationlevel() != null) {
                            int educationlevel = getEducationlevel(vo
                                    .getEducationlevel());
                            hrm.setEducationlevel(educationlevel);
                        }

                        // 工会会员,默认为是
                        String islabouunion = "是".equals(vo.getIslabouunion()) ? "1" : "0";
                        hrm.setIslabouunion(islabouunion);

                        // 健康状况
                        if (vo.getHealthinfo() != null) {
                            String healthinfo = getHealthinfo(vo.getHealthinfo());
                            hrm.setHealthinfo(healthinfo);
                        } else {
                            hrm.setHealthinfo("0");
                        }

                        //安全级别不能大于999
                        if (Util.getIntValue(vo.getSeclevel(), 0) > 999) {
                            resultList.add(createLog(vo, "创建", "失败", SystemEnv.getHtmlLabelName(515522, userlanguage)));
                            continue;
                        }
                        //安全级别不能小于-999
                        if (Util.getIntValue(vo.getSeclevel(), 0) < -999) {
                            resultList.add(createLog(vo, "创建", "失败", SystemEnv.getHtmlLabelName(515523, userlanguage)));
                            continue;
                        }
                        //安全级别必须是数字
                        if (!"".equals(Util.null2String(vo.getSeclevel()))) {
                            if (Util.getIntValue(vo.getSeclevel(), -1000) == -1000) {
                                resultList.add(createLog(vo, "创建", "失败", "安全级别必须是数字"));
                                continue;
                            } else {
                                hrm.setSeclevel((short) Util.getIntValue(vo.getSeclevel()));
                            }
                        } else {
                            //安全级别为空时取缓存类中的安全级别
                            hrm.setSeclevel((short) (0));
                        }

                        //职级
                        if (isInteger(vo.getJoblevel())) {
                            int joblevel = "".equals(vo.getJoblevel()) ? 0 : Integer.parseInt(vo.getJoblevel());
                            hrm.setJoblevel((short) joblevel);
                        } else {
                            hrm.setJoblevel((short) 0);
                        }
                        //用工性质
                        if (vo.getUsekind() != null) {
                            int usekind = getUseKind(vo.getUsekind());
                            hrm.setUsekind(usekind);
                        } else {
                            hrm.setUsekind(0);
                        }
                        //如果新增导入的时候，登陆名不为空，需要校验一下当前的license


                        // 手机 办公电话
                        CheckItemBean mobileBean = new CheckItemBean("mobile", vo.getMobile());
                        ValidateFieldManager.validate(mobileBean);
                        if (!mobileBean.isPass()) {
                            resultList.add(createLog(vo, "创建", "失败", mobileBean.getCheckMsg()));
                            continue;
                        }
                        CheckItemBean telephoneBean = new CheckItemBean("telephone", vo.getTelephone());
                        ValidateFieldManager.validate(telephoneBean);
                        if (!telephoneBean.isPass()) {
                            resultList.add(createLog(vo, "创建", "失败", telephoneBean.getCheckMsg()));
                            continue;
                        }


                        //id，非自动增长
                        recordSet.executeProc("HrmResourceMaxId_Get", "");
                        recordSet.next();
                        id = recordSet.getInt(1);
                        hrm.setId(id);


                        //密码 加密
                        String password_tmp = Util.null2String(vo.getPassword()).trim();
                        if ("".equals(password_tmp)) {
                            password_tmp = "1";
                            //人员导入文件中，将密码这一列删除或者密码这一列存在，但是不填写都默认为初始密码
                            if (defaultPasswordEnable) {
                                if (!"".equals(defaultPassword)) {
                                    if (weakPasswordDisable && this.hrmWeakPasswordUtil.isWeakPsd(defaultPassword)) {
                                        resultList.add(createLog(vo, "创建", "失败", SystemEnv.getHtmlLabelName(515436, userlanguage)));
                                        continue;
                                    } else {
                                        password_tmp = defaultPassword;
                                    }
                                } else {
                                    resultList.add(createLog(vo, "创建", "失败", SystemEnv.getHtmlLabelName(516347, userlanguage)));
                                    continue;
                                }
                            }
                        }

                        String[] encrypts = PasswordUtil.encrypt(password_tmp);
                        HrmFaceCheckManager.setUserPassowrd(id + "", password_tmp);

                        String password = encrypts[0];
                        String salt = encrypts[1];
                        hrm.setPassword(password);

                        boolean flag = true;

                        /*添加人员信息*/
                        String insertStr = "insert into hrmResource(";
                        StringBuilder insertFields = new StringBuilder();
                        StringBuilder insertValues = new StringBuilder();

                        String workcode = vo.getWorkcode();
                        workcode = CodeRuleManager.getCodeRuleManager().generateRuleCode(RuleCodeType.USER, String.valueOf(hrm.getSubcompanyid1()), String.valueOf(hrm.getDepartmentid()), String.valueOf(hrm.getJobtitle()), workcode);
                        vo.setWorkcode(workcode);

                        for (String s : fields) {
                            Field hrmField = hrmClass.getDeclaredField(s);
                            Field voField = voClass.getDeclaredField(s);

                            String hrmFieldType = hrmField.getType().getName();
                            String voFieldType = voField.getType().getName();

                            hrmField.setAccessible(true);
                            voField.setAccessible(true);

                            //首先取hrm对象中的数据，没有去vo中的
                            if (hrmField.get(hrm) != null) {
                                if (hrmFieldType.endsWith("String")) {
                                    insertFields.append(s).append(",");
                                    insertValues.append("'").append(hrmField.get(hrm)).append("',");
                                } else if (hrmFieldType.endsWith("Integer") || hrmFieldType.endsWith("Short") || hrmFieldType.endsWith("Float")) {
                                    insertFields.append(s).append(",");
                                    String insertValueStr = Util.null2String(hrmField.get(hrm));
                                    if ("".equals(insertValueStr) && "postgresql".equalsIgnoreCase(recordSet.getDBType())) {
                                        insertValues.append("null,");
                                    } else {
                                        insertValues.append(hrmField.get(hrm)).append(",");
                                    }
                                }
                            } else if (voField.get(vo) != null) {
                                if (voFieldType.endsWith("String")) {
                                    if ("mysql".equalsIgnoreCase(recordSet.getDBType()) || "postgresql".equalsIgnoreCase(recordSet.getDBType())) {
                                        if ("".equals(Util.null2String(voField.get(vo)))) {
                                            insertFields.append(s).append(",");
                                            insertValues.append("null,");
                                        } else {
                                            insertFields.append(s).append(",");
                                            insertValues.append("'").append(voField.get(vo)).append("',");
                                        }
                                    } else {
                                        insertFields.append(s).append(",");
                                        insertValues.append("'").append(voField.get(vo)).append("',");
                                    }
                                } else if (hrmFieldType.endsWith("Integer") || hrmFieldType.endsWith("Short") || hrmFieldType.endsWith("Float")) {
                                    insertFields.append(s).append(",");
                                    String insertValueStr = Util.null2String(voField.get(vo));
                                    if ("".equals(insertValueStr) && "postgresql".equalsIgnoreCase(recordSet.getDBType())) {
                                        insertValues.append("null,");
                                    } else {
                                        insertValues.append(voField.get(vo)).append(",");
                                    }

                                }
                            }
                        }
                        ChgPasswdReminder cpr = new ChgPasswdReminder();
                        RemindSettings hrmsettings = cpr.getRemindSettings();
                        insertStr = insertStr + insertFields + "createrid,createdate,lastmodid,lastmoddate,lastlogindate,managerstr,mobileshowtype ," + DbFunctionUtil.getInsertColumnSql() + ") values("
                                + insertValues + createrid + ",'" + date + "'," + lastmodid + ",'" + lastmoddate + "','" + date + "','" + hrm.getManagerstr() + "'," + Util.getIntValue(hrmsettings.getMobileShowTypeDefault(), 0) + " ," + DbFunctionUtil.getInsertColumnValueSql(recordSet.getDBType(), lastmodid) + ")";


                        boolean resourceInsertFlag = true;
                        if (!execSql(insertStr)) {//添加人员信息
                            flag = false;
                            resourceInsertFlag = false;
                        }
                        if (resourceInsertFlag) {// 仅当人员插入成功后才进行自定义字段操作
                            PasswordUtil.updateResourceSalt(id + "", salt);

                            if (updateBaseData(vo.getBaseFields(), vo.getBaseFieldsValue(), id)) //添加基础字段信息
                            {
                                flag = false;
                            }
                            if (updatePersonData(vo.getPersonFields(), vo.getPersonFieldsValue(), id)) //添加个人字段信息
                            {
                                flag = false;
                            }
                            if (updateWorkData(vo.getWorkFields(), vo.getWorkFieldsValue(), id))      //添加工作字段信息
                            {
                                flag = false;
                            }
                        }

                        /*添加人员缓存，人员默认按id显示顺序,HrmResource_Trigger_Insert 人员共享 入职维护项目状态*/
                        if (flag) {

                            //HrmUserSettingManager.checkUserSettingInit(id) ;

                            //人员显示顺序
                            if (vo.getDsporder() == null) {
                                String taxissql = ("update HrmResource set dsporder = " + id + " where id = " + id);
                                recordSet.executeSql(taxissql);
                            }
                            //构建pinyin快速搜索
                            if (vo.getLastname() != null) {
                                String quickSearchStr = new HrmCommonServiceImpl().generateQuickSearchStr(vo.getLastname());
                                String sqlStr = "update HrmResource set pinyinlastname = ?, ecology_pinyin_search = ? where id = ?";
                                recordSet.executeUpdate(sqlStr, quickSearchStr, quickSearchStr, id);
                            }

                            //触发器
                            String para = "" + id + separator + hrm.getManagerid() + separator + hrm.getDepartmentid() + separator + hrm.getSubcompanyid1() + separator + hrm.getSeclevel() + separator + hrm.getManagerstr();
                            recordSet.executeProc("HrmResource_Trigger_Insert", para);

                            //共享信息
	                 /*String p_para = "" + id + separator + hrm.getDepartmentid()  + separator + hrm.getSubcompanyid1() + separator + hrm.getManagerid() + separator + hrm.getSeclevel() + separator + hrm.getManagerstr() + separator + "0" + separator + "0" + separator + "0" + separator + "0" + separator + "0" + separator + "0";
	                 recordSet.executeProc("HrmResourceShare", p_para);*/

                            //入职维护状态
                            String sql_1 = ("insert into HrmInfoStatus (itemid,hrmid,status) values(1," + id + ",1)");
                            recordSet.executeSql(sql_1);
                            String sql_2 = ("insert into HrmInfoStatus (itemid,hrmid) values(2," + id + ")");
                            recordSet.executeSql(sql_2);
                            String sql_3 = ("insert into HrmInfoStatus (itemid,hrmid) values(3," + id + ")");
                            recordSet.executeSql(sql_3);

                            String sql_10 = ("insert into HrmInfoStatus (itemid,hrmid) values(10," + id + ")");
                            recordSet.executeSql(sql_10);

                            HrmFaceCheckManager.sync(id + "", HrmFaceCheckManager.getOptInsert(), "hrm_e9_import_resource", HrmFaceCheckManager.getOaResource());

                            new HrmDateCheck().calWorkInfo("" + id);
                            // 刷新组织结构图
                            // TODO new Thread(new HrmResourceTriggerRunnable((long) id)).start();

                        }

                        /*写日志*/
                        if (flag) {
                            resultList.add(createLog(vo, "创建", "成功", ""));
                            if (!"".equals(vo.getLoginid())) {
                                rtxService.addUser(id);//添加到rtx
                            }
                        } else {
                            resultList.add(createLog(vo, "创建", "失败", "系统错误，请联系管理员"));
                        }

                    } else {    //更新人员
                        if (keyMap.get(key) == null) {
                            resultList.add(createLog(vo, "更新", "失败", SystemEnv.getHtmlLabelName(83535, userlanguage)));
                            continue;
                        }

                        vo.setId(Util.getIntValue(keyMap.get(key)));//设置id
                        if (this.checkInfo(vo, resultList)) {
                            continue;
                        }

                        if (vo.getAccounttype() == null || "".equalsIgnoreCase(Util.null2String(vo.getAccounttype()))) {
                            if (StringUtil.isNotNull(vo.getCertificatenum()) && certificateNums.get(StringUtil.vString(vo.getCertificatenum())) != null) {
                                if (StringUtil.parseToInt(String.valueOf(keyMap.get(key))) != StringUtil.parseToInt(String.valueOf(certificateNums.get(StringUtil.vString(vo.getCertificatenum()))))) {
                                    resultList.add(createLog(vo, "更新", "失败", SystemEnv.getHtmlLabelName(83521, userlanguage)));
                                    continue;
                                }
                            }
                        } else {
                            if (vo.getAccounttype() != null && !"".equals(vo.getAccounttype())) {
                                if ("主账号".equals(vo.getAccounttype())) {
                                    if (StringUtil.isNotNull(vo.getCertificatenum()) && certificateNums.get(StringUtil.vString(vo.getCertificatenum())) != null) {
                                        if (StringUtil.parseToInt(String.valueOf(keyMap.get(key))) != StringUtil.parseToInt(String.valueOf(certificateNums.get(StringUtil.vString(vo.getCertificatenum()))))) {
                                            resultList.add(createLog(vo, "更新", "失败", SystemEnv.getHtmlLabelName(83521, userlanguage)));
                                            continue;
                                        }
                                    }
                                }
                            }
                        }

                        final String hrmId = String.valueOf(keyMap.get(key));

                        //分部id
                        String subCompanyNames = vo.getSubcompanyid1();
                        boolean issameSub = true;
                        if (!"".equals(Util.null2String(subCompanyNames))) {
                            if (!subCompanyNames.equals(subCompanyName)) {
                                subCompanyName = subCompanyNames;
                                subcompanyid1 = getSubCompanyId(subCompanyName);
                                issameSub = false;

                            }

                            if (subcompanyid1 == -9) {
                                resultList.add(createLog(vo, "更新", "失败", SystemEnv.getErrorMsgName(56, userlanguage)));
                                continue;
                            }
                            if (subcompanyid1 == -2) {
                                resultList.add(createLog(vo, "更新", "失败", SystemEnv.getHtmlLabelName(126274, userlanguage)));
                                continue;
                            }
                            if (subcompanyid1 == 0 || subcompanyid1 == -1) {
                                resultList.add(createLog(vo, "更新", "失败", subcompanyid1 == 0 ? SystemEnv.getHtmlLabelName(83536, userlanguage) : SystemEnv.getHtmlLabelName(83524, userlanguage)));
                                continue;
                            }

                            //qc139575 在验证并发非并发之前需要先CkHrmnum
                            license.CkHrmnum();
                            if (StringUtil.parseToInt(license.getConcurrentFlag(), 0) != 1) {
                                if (!issameSub && new HrmResourceManager().noMore(String.valueOf(subcompanyid1))) {
                                    resultList.add(createLog(vo, "更新", "失败", SystemEnv.getHtmlLabelName(83525, userlanguage)));
                                    continue;
                                }
                            }
                            hrm.setSubcompanyid1(subcompanyid1);
                        }

                        // 部门id
                        String departmentNames = vo.getDepartmentid();
                        if (!"".equals(Util.null2String(departmentNames))) {  //部门存在时
                            if (!issameSub || !departmentNames.equals(departmentName)) {
                                departmentName = departmentNames;
                                departmentid = getDeptId(departmentName, subcompanyid1);

                                if (departmentid == 0) {
                                    resultList.add(createLog(vo, "更新", "失败", SystemEnv.getHtmlLabelName(83537, userlanguage)));
                                    continue;
                                }
                                if (departmentid == -2) {
                                    resultList.add(createLog(vo, "更新", "失败", SystemEnv.getHtmlLabelName(126275, userlanguage)));
                                    continue;
                                }
                            } else {  //add sjh 50102需要考虑不同公司名称相同部门架构情况 此时部门ID是不同的
                                departmentid = getDeptId(departmentName, subcompanyid1);
                                if (departmentid == 0) {
                                    resultList.add(createLog(vo, "更新", "失败", SystemEnv.getHtmlLabelName(83537, userlanguage)));
                                    continue;
                                }
                                if (departmentid == -2) {
                                    resultList.add(createLog(vo, "更新", "失败", SystemEnv.getHtmlLabelName(126275, userlanguage)));
                                    continue;
                                }
                            }
                            hrm.setDepartmentid(departmentid);
                        }

                        //主账号id-sunjsh
                        if (vo.getAccounttype() != null && !"".equals(vo.getAccounttype())) {
                            if ("主账号".equals(vo.getAccounttype())) {
                                hrm.setBelongto(-1);
                                hrm.setAccounttype(0);
                            } else if ("次账号".equals(vo.getAccounttype())) {
                                if (vo.getBelongto() != null && !"".equals(vo.getBelongto().trim())) {
                                    int belongto = getBelongId(vo.getBelongto(), keyField);
                                    hrm.setBelongto(belongto);
                                    if (!"".equals(vo.getBelongto()) && belongto == 0) {
                                        resultList.add(createLog(vo, "更新", "失败", SystemEnv.getHtmlLabelName(131279, userlanguage)));
                                        continue;
                                    } else {
                                        hrm.setAccounttype(1);
                                    }
                                } else {
                                    resultList.add(createLog(vo, "更新", "失败", SystemEnv.getHtmlLabelName(131279, userlanguage)));
                                    continue;
                                }
                            } else {
                                hrm.setBelongto(-1);
                                hrm.setAccounttype(0);
                            }
                        } else if (vo.getBelongto() != null && !"".equals(vo.getBelongto().trim())) {
                            int belongto = getBelongId(vo.getBelongto(), keyField);
                            hrm.setBelongto(belongto);
                            if (!"".equals(vo.getBelongto()) && belongto == 0) {
                                resultList.add(createLog(vo, "更新", "失败", SystemEnv.getHtmlLabelName(131279, userlanguage)));
                                continue;
                            } else {
                                hrm.setAccounttype(1);
                            }
                        }

                        // 岗位id
                        if ("".equals(Util.null2String(vo.getJobtitle())) && (!"".equals(Util.null2String(vo.getJobactivityid())) || !"".equals(Util.null2String(vo.getJobgroupid())))) {
                            resultList.add(createLog(vo, "更新", "失败", SystemEnv.getHtmlLabelName(83544, userlanguage)));
                            continue;
                        }
                        if (!"".equals(Util.null2String(vo.getJobtitle()))) {
                            String jobtitle = "";
                            String jobactivityid = "";
                            String jobactivityname = "";
                            String jobgroupid = "";
                            String jobgroupname = "";
                            if (vo.getJobactivityid() == null) {
                                jobtitle = resourcecominfo.getJobTitle(hrmId);
                                jobactivityid = jobTitlesComInfo.getJobactivityid(jobtitle);
                                jobactivityname = jobActivitiesComInfo.getJobActivitiesname(jobactivityid);
                            } else {
                                jobactivityname = vo.getJobactivityid();
                            }
                            if (vo.getJobgroupid() == null) {
                                jobtitle = resourcecominfo.getJobTitle(hrmId);
                                jobactivityid = jobTitlesComInfo.getJobactivityid(jobtitle);
                                jobgroupid = jobActivitiesComInfo.getJobgroupid(jobactivityid);
                                jobgroupname = jobGroupsComInfo.getJobGroupsname(jobgroupid);
                            } else {
                                jobgroupname = vo.getJobgroupid();
                            }
                            int jobtitleid = getJobTitles(vo.getJobtitle(), jobactivityname, jobgroupname);
                            hrm.setJobtitle(jobtitleid);
                        }

                        if (Util.getIntValue(hrmId) < 0) {
                            continue;
                        }

                        //上级id
                        String managerstr = "";    //所有上级
                        String oldmanagerstr = resourcecominfo.getManagersIDs(hrmId);//原来的所有上sex
                        // 级序列
                        if (!"".equals(Util.null2String(vo.getManagerid()))) {
                            int managerid = 0;        // 上级Id

                            Map<String, Comparable> managerInfo = getManagerIdAndStr(hrmId, vo.getManagerid(), keyField);
                            if (managerInfo != null) {
                                managerid = managerInfo.get("managerid") != null ? (Integer) managerInfo.get("managerid") : 0;
                                managerstr = (String) (managerInfo.get("managerstr") != null ? managerInfo.get("managerstr") : "");
                            }

                            //如果vo.getManagerid()有值，但manageid未找到，说明填写有误
                            if (vo.getManagerid() != null && !"".equals(vo.getManagerid()) && managerid == 0) {
                                resultList.add(createLog(vo, "更新", "失败", SystemEnv.getHtmlLabelName(83532, userlanguage)));
                                continue;
                            }
                            hrm.setManagerid(managerid);
                            hrm.setManagerstr(managerstr);
                        } else {
                            if (vo.getManagerid() == null) {
                                hrm.setManagerid(StringUtil.parseToInt(resourcecominfo.getManagerID(hrmId), 0));
                                hrm.setManagerstr(resourcecominfo.getManagersIDs(hrmId));
                                managerstr = resourcecominfo.getManagersIDs(hrmId);
                                vo.setManagerid(resourcecominfo.getManagerID(hrmId));
                            } else {
                                hrm.setManagerid(0);
                                hrm.setManagerstr("");
                            }
                        }
                        // 助理id
                        if (!"".equals(Util.null2String(vo.getAssistantid()))) {
                            int assistantid;
                            assistantid = getAssistantid(vo.getAssistantid(), keyField);
                            if (vo.getAssistantid() != null && !"".equals(vo.getAssistantid()) && assistantid == 0) {
                                resultList.add(createLog(vo, "更新", "失败", SystemEnv.getHtmlLabelName(24678, userlanguage)));
                                continue;
                            }
                            hrm.setAssistantid(assistantid);
                        }
                        // 办公地点
                        if (!"".equals(Util.null2String(vo.getLocationid()))) {
                            int locationid = getLocationid(vo.getLocationid());
                            hrm.setLocationid(locationid);
                        }

                        //邮箱-sunjsh
                        if (vo.getEmail() != null) {
                            if (!"".equals(vo.getEmail().trim()) && vo.getEmail().contains("*")) {
                                vo.setEmail(null);
                            } else if ("".equals(vo.getEmail().trim())) {
                                hrm.setEmail("");
                            } else {
                                Pattern pattern = Pattern.compile("^([a-zA-Z0-9_\\-]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(?)$");
                                Matcher matcher = pattern.matcher(vo.getEmail());
                                if (!matcher.matches()) {
                                    resultList.add(createLog(vo, "更新", "失败", SystemEnv.getHtmlLabelName(24570, userlanguage)));
                                    continue;
                                } else {
                                    hrm.setEmail(vo.getEmail());
                                }
                            }
                        }

                        //mobile-sunjsh
                        if (vo.getMobile() != null) {
                            if ("".equals(vo.getMobile().trim())) {
                                hrm.setMobile("");
                            } else if (!"".equals(vo.getMobile().trim()) && vo.getMobile().contains("*")) {
                                vo.setMobile(null);
                            }
                        }

                        //工资银行-sunjsh
                        if (vo.getBankid1() != null && !"".equals(vo.getBankid1())) {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("fieldid", 0);
                            jsonObject.put("fieldhtmltype", 3);
                            jsonObject.put("type", 284);
                            jsonObject.put("dmlurl", "");
                            jsonObject.put("fieldvalue", vo.getBankid1());

                            String fieldvalue = HrmFieldManager.getReallyFieldvalue(jsonObject);
                            if (!"".equals(fieldvalue)) {
                                hrm.setBankid1(new Integer(fieldvalue));
                            } else {
//                                vo.setBankid1(null);
                                hrm.setBankid1(this.getBankId(vo.getBankid1()));
                            }
                        }

                        //sunjsh-入职日期
                        if (vo.getCompanystartdate() != null && !"".equals(vo.getCompanystartdate())) {
                            hrm.setCompanystartdate(vo.getCompanystartdate());
//                            hrm.setCompanyworkyear(this.calculateDate(vo.getCompanystartdate()));
                        } else {
                            vo.setCompanystartdate(null);
                        }

                        //sunjsh-参加工作日期
                        if (vo.getWorkstartdate() != null && !"".equals(vo.getWorkstartdate())) {
                            hrm.setWorkstartdate(vo.getWorkstartdate());
//                            hrm.setWorkyear(this.calculateDate(vo.getWorkstartdate()));
                        } else {
                            vo.setWorkstartdate(null);
                        }
                        // 职称
                        if (!"".equals(Util.null2String(vo.getJobcall()))) {
                            int jobcall = getJobcall(vo.getJobcall());
                            hrm.setJobcall(jobcall);
                        }
                        // 系统语言，默认简体中文
                        if (!"".equals(Util.null2String(vo.getSystemlanguage()))) {
                            int systemlanguage = getSystemlanguage(vo.getSystemlanguage());

                            if (systemlanguage == -1) {    //只能选择简体中文|Englisth|繁体中文
                                resultList.add(createLog(vo, "更新", "失败", SystemEnv.getHtmlLabelName(518929, userlanguage)));
                                continue;
                            }
                            //系统不支持多语言
                            if (systemlanguage == 0) {
                                resultList.add(createLog(vo, "更新", "失败", SystemEnv.getHtmlLabelName(84810, userlanguage)));
                                continue;
                            }
                            hrm.setSystemlanguage(systemlanguage);
                        }

                        // 性别，为空或其他情况统一为0(男)
                        if (!"".equals(Util.null2String(vo.getSex()))) {
                            String sex = "女".equals(vo.getSex()) ? "1" : "0";
                            hrm.setSex(sex);
                        }

                        // 婚姻状况，如果不是以下选项，则默认为未婚
                        if (!"".equals(Util.null2String(vo.getMaritalstatus()))) {
                            String maritalstatus = "已婚".equals(vo.getMaritalstatus()) ? "1"
                                    : "离异".equals(vo.getMaritalstatus()) ? "2" : "0";
                            hrm.setMaritalstatus(maritalstatus);
                        }

                        // 员工状态
                        if (!"".equals(Util.null2String(vo.getStatus()))) {
                            int status = getStatus(vo.getStatus());
                            hrm.setStatus(status);
                        }

                        // 人员密级
                        if (!"".equals(Util.null2String(vo.getClassification()))) {
                            int classification = getClassification(vo.getClassification());
                            hrm.setClassification(classification);
                        }

                        // 学历
                        if (!"".equals(Util.null2String(vo.getEducationlevel()))) {
                            int educationlevel = getEducationlevel(vo
                                    .getEducationlevel());
                            hrm.setEducationlevel(educationlevel);
                        }

                        // 工会会员,默认为是
                        if (!"".equals(Util.null2String(vo.getIslabouunion()))) {
                            String islabouunion = "是".equals(vo.getIslabouunion()) ? "1"
                                    : "0";
                            hrm.setIslabouunion(islabouunion);
                        }

                        // 健康状况
                        if (!"".equals(Util.null2String(vo.getHealthinfo()))) {
                            String healthinfo = getHealthinfo(vo.getHealthinfo());
                            hrm.setHealthinfo(healthinfo);
                        }

                        //安全级别不能大于999
                        if (Util.getIntValue(vo.getSeclevel(), 0) > 999) {
                            resultList.add(createLog(vo, "更新", "失败", SystemEnv.getHtmlLabelName(515522, userlanguage)));
                            continue;
                        }
                        //安全级别不能小于-999
                        if (Util.getIntValue(vo.getSeclevel(), 0) < -999) {
                            resultList.add(createLog(vo, "更新", "失败", SystemEnv.getHtmlLabelName(515523, userlanguage)));
                            continue;
                        }
                        //安全级别必须是数字
                        if (!"".equals(Util.null2String(vo.getSeclevel()))) {
                            if (Util.getIntValue(vo.getSeclevel(), -1000) == -1000) {
                                resultList.add(createLog(vo, "更新", "失败", "安全级别必须是数字"));
                                continue;
                            } else {
                                hrm.setSeclevel((short) Util.getIntValue(vo.getSeclevel()));
                            }
                        } else {
                            //安全级别为空时取缓存类中的安全级别
                            hrm.setSeclevel(Short.parseShort(resourcecominfo.getSeclevel(hrmId)));
                        }

                        //职级
                        if (isInteger(vo.getJoblevel())) {
                            int joblevel = "".equals(vo.getJoblevel()) ? 0 : Integer.parseInt(vo.getJoblevel());
                            hrm.setJoblevel((short) joblevel);
                        }

                        //用工性质
                        if (vo.getUsekind() != null) {
                            int usekind = getUseKind(vo.getUsekind());
                            hrm.setUsekind(usekind);
                        }


                        //更新导入的时候，如果登录名不为空，需要校验一下当前的license
                        if (needCheckLicenseForUpdate(resourcecominfo, hrmId, vo)) {
                            license.reloadLicenseInfo();
                            if (license.CkHrmnum() >= 0) {
                                resultList.add(createLog(vo, "更新", "失败", SystemEnv.getHtmlLabelName(83522, userlanguage)));
                                continue;
                            }
                        }

                        // 手机 办公电话
                        CheckItemBean mobileBean = new CheckItemBean("mobile", vo.getMobile());
                        ValidateFieldManager.validate(mobileBean);
                        if (!mobileBean.isPass()) {
                            resultList.add(createLog(vo, "更新", "失败", mobileBean.getCheckMsg()));
                            continue;
                        }
                        CheckItemBean telephoneBean = new CheckItemBean("telephone", vo.getTelephone());
                        ValidateFieldManager.validate(telephoneBean);
                        if (!telephoneBean.isPass()) {
                            resultList.add(createLog(vo, "更新", "失败", telephoneBean.getCheckMsg()));
                            continue;
                        }


                        //密码 加密
                        if (!"".equals(Util.null2String(vo.getPassword()))) {

                            String orgPwd = "1";
                            if (!"".equals(vo.getPassword())) {
                                orgPwd = vo.getPassword();
                            }
                            String[] pwdArr = PasswordUtil.encrypt(orgPwd);
                            String salt = pwdArr[1];
                            hrm.setPassword(pwdArr[0]);

                            PasswordUtil.updateResourceSalt(keyMap.get(key) + "", salt);
                            HrmFaceCheckManager.setUserPassowrd(keyMap.get(key) + "", orgPwd);

                        }
                        boolean flag = true;

                        StringBuilder updateStr = new StringBuilder("update hrmresource set ");

                        String tmpstatus = "";
                        //k从1开始，id不是update字段
//                        String workcode = vo.getWorkcode();
//                         workcode = CodeRuleManager.getCodeRuleManager().generateRuleCode(RuleCodeType.USER, String.valueOf(hrm.getSubcompanyid1()), String.valueOf(hrm.getDepartmentid()), String.valueOf(hrm.getJobtitle()), workcode);
//                            vo.setWorkcode(workcode);
                        for (int k = 1; k < fields.length; k++) {
                            Field hrmField = hrmClass.getDeclaredField(fields[k]);
                            Field voField = voClass.getDeclaredField(fields[k]);

                            String hrmFieldType = hrmField.getType().getName();
                            String voFieldType = voField.getType().getName();

                            hrmField.setAccessible(true);
                            voField.setAccessible(true);

                            if (Util.null2String(hrmField.get(hrm)).trim().length() > 0) {
                                if (hrmFieldType.endsWith("String")) {
                                    updateStr.append(fields[k]).append("='").append(hrmField.get(hrm)).append("',");
                                } else if (hrmFieldType.endsWith("Integer") || hrmFieldType.endsWith("Short") || hrmFieldType.endsWith("Float")) {
                                    updateStr.append(fields[k]).append("=").append(hrmField.get(hrm)).append(",");
                                }

                                if ("status".equals(fields[k])) {
                                    tmpstatus = Util.null2String(hrmField.get(hrm));
                                }
                            } else if (Util.null2String(voField.get(vo)).trim().length() > 0) {
                                if (voFieldType.endsWith("String")) {
                                    if ("mysql".equalsIgnoreCase(recordSet.getDBType()) || "postgresql".equalsIgnoreCase(recordSet.getDBType())) {
                                        if ("".equals(Util.null2String(voField.get(vo)))) {
                                            updateStr.append(fields[k]).append("=null,");
                                        } else {
                                            updateStr.append(fields[k]).append("='").append(voField.get(vo)).append("',");
                                        }
                                    } else {
                                        updateStr.append(fields[k]).append("='").append(voField.get(vo)).append("',");
                                    }
                                } else if (voFieldType.endsWith("Integer") || voFieldType.endsWith("Short") || voFieldType.endsWith("Float")) {
                                    if (voFieldType.endsWith("Integer") && (voField.get(vo).equals(0x7fffffff))) {
                                        updateStr.append(fields[k]).append("=null,");
                                    } else {
                                        updateStr.append(fields[k]).append("=").append(voField.get(vo)).append(",");
                                    }
                                }
                                if ("status".equals(fields[k])) {
                                    tmpstatus = Util.null2String(voField.get(vo));
                                }
                            }
                        }

                        updateStr.append(" lastmodid=").append(lastmodid).append(",lastmoddate='").append(lastmoddate).append("',managerstr='").append(hrm.getManagerstr()).append("',").append(DbFunctionUtil.getUpdateSetSql(new RecordSet().getDBType(), lastmodid)).append("  where id=").append(keyMap.get(key));

                        if (!execSql(updateStr.toString())) {
                            flag = false;
                        }

                        //同步密码到AD
                        if (flag && !"".equals(Util.null2String(vo.getPassword()))) {
                            String userid = Util.null2String(keyMap.get(key));
                            String loginid = Util.null2String(resourcecominfo.getLoginID(userid));
                            String isADAccount = Util.null2String(isADAccountMap.get(userid));
                            if ("1".equals(isADAccount) && !"1".equals(userid) && new AuthenticUtil().checkType(loginid)) {
                                Map<String, String> map = new HashMap<>();
                                map.put("userid", userid);//OA人员id
                                map.put("loginid", loginid);//人员帐号
                                map.put("password", Util.null2String(vo.getPassword()));//新密码
                                map.put("issysadmin", "true");//是否需要检验旧密码。0，是检验。1,不需要检验。
                                String optype = "4"; //1，强制修改密码操作。2，首次登录密码操作，3，忘记密码找回。其它，系统修改ad操作。
                                map.put("optype", optype);
                                Map<String, Object> retInfo = new OaSync("", "").modifyADPWDNew(map);
                                if ("0".equals(Util.null2String(retInfo.get("code")))) {
                                    //更新修改密码时间
                                    String passwdchgdate = Util.null2String(TimeUtil.getCurrentDateString());
                                    flag = recordSet.executeUpdate("update hrmresource set passwdchgdate=?, haschangepwd='y' where id = ?", passwdchgdate, userid);
                                } else {
                                    flag = false;
                                    writeLog("人员导入，更新人员密码，同步至AD失败___retInfo___" + com.alibaba.fastjson.JSONObject.toJSONString(retInfo));
                                }
                            }
                        }

                        //如果更新为解聘、离职、退休，处理相关数据
                        if (("4".equals(tmpstatus) || "5".equals(tmpstatus) || "6".equals(tmpstatus)) && !tmpstatus.equals(resourcecominfo.getStatus("" + keyMap.get(key)))) {
                            OrganisationCom orgCom = new OrganisationCom();
                            HrmServiceManager hrmaction = new HrmServiceManager();
                            String tmpid;
                            String type = "5";
                            String procType = "HrmResource_Dismiss";
                            String statusType = "5";
                            if ("4".equals(tmpstatus)) {
                                type = "1";
                                procType = "HrmResource_Fire";
                                statusType = "4";
                            } else if ("6".equals(tmpstatus)) {
                                type = "6";
                                procType = "HrmResource_Retire";
                                statusType = "6";
                            }
                            int resourceid = keyMap.get(key);
                            String changedate = TimeUtil.getCurrentDateString();
                            String changereason = SystemEnv.getHtmlLabelName(17887, userlanguage);
                            String changecontractid = "";
                            String infoman = "";
                            String oldjobtitleid = resourcecominfo.getJobTitle("" + resourceid);
                            String para = "" + resourceid + separator + changedate + separator + changereason + separator + changecontractid + separator + infoman + separator + oldjobtitleid + separator + type + separator + "1";
                            recordSet.executeProc(procType, para);
                            recordSet.executeSql("select max(id) from HrmStatusHistory");
                            recordSet.next();
                            tmpid = recordSet.getString(1);

                            //删除角色成员
                            recordSet.executeSql("delete from hrmrolemembers where resourcetype =1 and resourceid=" + resourceid);
                            //删除手机版中设置的登录人员
                            recordSet.executeSql("delete from PluginLicenseUser where plugintype='mobile' and sharetype='0' and sharevalue='" + resourceid + "'");
                            //更新人员未离职，清空账号
                            recordSet.executeSql("update HrmResource set status = " + statusType + " ,loginid='',password='',account='', email='', tokenkey='', lastmoddate='" + changedate + "' where id = " + resourceid);
                            //删除自定义组成员
                            recordSet.executeSql("delete hrmgroupmembers where userid=" + resourceid);
                            //更新变更记录状态为已处理
                            recordSet.executeSql("update HrmStatusHistory set isdispose = 1 where id=" + tmpid);
                            boolean exist = orgCom.checkUser(resourceid);
                            if (exist) {
                                orgCom.deleteUser2(resourceid);
                            }
                            //OA与第三方接口单条数据同步方法开始
                            hrmaction.SynInstantHrmResource("" + resourceid, "3");
                            //OA与第三方接口单条数据同步方法结束
                        }

                        if (updateBaseData(vo.getBaseFields(), vo.getBaseFieldsValue().trim(), keyMap.get(key))) {
                            flag = false;
                        }

                        if (updatePersonData(vo.getPersonFields(), vo.getPersonFieldsValue().trim(), keyMap.get(key))) {
                            flag = false;
                        }

                        if (updateWorkData(vo.getWorkFields().trim(), vo.getWorkFieldsValue(), keyMap.get(key))) {
                            flag = false;
                        }

                        /*update HrmResource_Trigger */
                        if (flag) {
                            recordSet.executeSql("select id from HrmResource_Trigger where id=" + hrmId);
                            if (recordSet.next()) {
                                recordSet.executeSql("update HrmResource_Trigger set managerid=" + hrm.getManagerid() + ",departmentid=" + hrm.getDepartmentid() + ",subcompanyid1=" + hrm.getSubcompanyid1() + ",seclevel=" + hrm.getSeclevel() + ",managerstr='" + hrm.getManagerstr() + "' where id=" + hrmId);
                            } else {
                                String para = "" + hrmId + separator + hrm.getManagerid() + separator + hrm.getDepartmentid() + separator + hrm.getSubcompanyid1() + separator + hrm.getSeclevel() + separator + hrm.getManagerstr();
                                recordSet.executeProc("HrmResource_Trigger_Insert", para);
                            }

                            //构建pinyin快速搜索
                            if (vo.getLastname() != null) {
                                String quickSearchStr = new HrmCommonServiceImpl().generateQuickSearchStr(vo.getLastname());
                                String sqlStr = "update HrmResource set pinyinlastname = ?, ecology_pinyin_search = ? where id = ?";
                                recordSet.executeUpdate(sqlStr, quickSearchStr, quickSearchStr, hrmId);
                            }
                        }

                        //更新下级managerstr
                        if (flag && !"".equals(Util.null2String(vo.getManagerid()))) {
                            String temOldmanagerstr = "," + hrmId + oldmanagerstr;
                            temOldmanagerstr = temOldmanagerstr.endsWith(",") ? temOldmanagerstr : (temOldmanagerstr + ",");
                            String sql = "select id,departmentid,subcompanyid1,managerid,seclevel,managerstr from HrmResource where managerstr like '%" + temOldmanagerstr + "'";
                            recordSet.executeSql(sql);
                            while (recordSet.next()) {
                                String nowmanagerstr = Util.null2String(recordSet.getString("managerstr"));
                                String resourceid = recordSet.getString("id");
                                //指定上级为自身的情况，不更新自身上级
                                if (hrmId.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) ? "" : ",");
                                    }

                                }
                                RecordSetTrans rst = new RecordSetTrans();
                                rst.setAutoCommit(false);
                                try {
                                    String para = resourceid + separator + nowmanagerstr2;
                                    rst.executeProc("HrmResource_UpdateManagerStr", para);
                                    rst.commit();
                                } catch (Exception e) {
                                    rst.rollback();
                                    writeLog(e);
                                }

                            }
                        }
                        if (flag) {

                            HrmFaceCheckManager.sync(keyMap.get(key) + "", HrmFaceCheckManager.getOptUpdate(), "hrm_e9_import_resource", HrmFaceCheckManager.getOaResource());
                            new HrmDateCheck().calWorkInfo(hrmId);
                            resultList.add(createLog(vo, "更新", "成功", ""));
                            //qc313055 [80][90][缺陷]IM集成-解决人员导入更新人员信息时，无账号列时，IM同步会进行删除操作的问题 ---start
                            RecordSet rst = new RecordSet();
                            if (vo.getLoginid() != null) {

                                //此时resourcecominfo对象还没有更新，可以直接取
                                if (!"".equals(vo.getLoginid())) {
                                    if (!rtxService.checkUser(Integer.parseInt(hrmId))) {
                                        rtxService.addUser(Integer.parseInt(hrmId));//更新人员rtx
                                    }
                                } else {
                                    rst.executeSql("select * from hrmresource where id='" + hrmId + "'");
                                    String loginid = "";
                                    if (rst.next()) {
                                        loginid = rst.getString("loginid");
                                    }
                                    if (loginid != null && !"".equals(loginid)) {
                                        if (!rtxService.checkUser(Integer.parseInt(hrmId))) {
                                            rtxService.addUser(Integer.parseInt(hrmId));//更新人员rtx
                                        }
                                    } else {
                                        rtxService.deleteUser2(Integer.parseInt(hrmId));
                                    }

                                }
                            } else {
                                rst.executeSql("select * from hrmresource where id='" + hrmId + "'");
                                String loginid = "";
                                if (rst.next()) {
                                    loginid = rst.getString("loginid");
                                }
                                if (loginid != null && !"".equals(loginid)) {
                                    if (!rtxService.checkUser(Integer.parseInt(hrmId))) {
                                        rtxService.addUser(Integer.parseInt(hrmId));//更新人员rtx
                                    }
                                } else {
                                    rtxService.deleteUser2(Integer.parseInt(hrmId));
                                }
                                //qc313055 [80][90][缺陷]IM集成-解决人员导入更新人员信息时，无账号列时，IM同步会进行删除操作的问题 ---end
                            }
                        } else {
                            resultList.add(createLog(vo, "更新", "失败", "系统错误，请联系管理员"));
                        }
                        // 刷新组织结构图
                        // TODO new Thread(new HrmResourceTriggerRunnable((long) keyMap.get(key))).start();
                    }
                } catch (Exception e) {
                    //数据异常
                    writeLog(e);
                }
            }
            try {
                HrmTlevelManager.setUpdate();
            } catch (Exception e) {
                writeLog(e);
            }

            //更新人员、分部、部门、职位、岗位、职位类型缓存

            resourcecominfo.removeResourceCache();
            departmentComInfo.removeCompanyCache();
            subCompanyComInfo.removeCompanyCache();
            jobActivitiesComInfo.removeJobActivitiesCache();
            jobTitlesComInfo.removeJobTitlesCache();
            jobGroupsComInfo.removeCompanyCache();
            locationComInfo.removeLocationCache();
            useKindComInfo.removeUseKindCache();
            //初始化应用分权
            new weaver.hrm.appdetach.AppDetachComInfo().initSubDepAppData();

            MapperProxyFactory.getProxy(JclImportHistoryMapper.class).updateHistoryStatus((long) this.pId, "over");
        } catch (Exception e) {
            writeLog(e);
            MapperProxyFactory.getProxy(JclImportHistoryMapper.class).updateHistoryStatus((long) this.pId, "error");
        }
    }

    /**
     * 插入基础自定义字段信息
     *
     * @param baseFild  存储人员自定义数据的字段
     * @param baseValue 自定义数据值
     * @param id        需要添加自定义信息的人员id
     * @return
     */
    public boolean addBaseData(String baseFild, String baseValue, int id) {
        if (baseFild == null || "".equals(baseFild)) {
            return true;
        }
        String[] baseValues = baseValue.split(";");
        String[] baseFields = baseFild.split(",");
        String fielddbType;
        String sql = "";
        String scopeId = "-1";
        EncryptUtil encryptUtil = new EncryptUtil();
        RecordSet recordSet = new RecordSet();
        try {
            if (baseTypeMap == null) {
                baseTypeMap = new HashMap<>();
                String baseSql = "select t1.fieldid,t1.hrm_fieldlable,t1.ismand,t2.fielddbtype,t2.fieldhtmltype,t2.type,t1.dmlurl from cus_formfield t1, cus_formdict t2 where t1.scope='HrmCustomFieldByInfoType' and t1.scopeid=-1 and t1.fieldid=t2.id order by t1.fieldorder";
                recordSet.execute(baseSql);
                while (recordSet.next()) {
                    String fieldid = Util.null2String(recordSet.getString("fieldid"));
                    String fielddbtype = Util.null2String(recordSet.getString("fielddbtype"));
                    String fieldhtmltype = Util.null2String(recordSet.getString("fieldhtmltype"));
                    String type = Util.null2String(recordSet.getString("type"));
                    String dmlurl = Util.null2String(recordSet.getString("dmlurl"));

                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("fieldid", fieldid);
                    jsonObject.put("fielddbtype", fielddbtype);
                    jsonObject.put("fieldhtmltype", fieldhtmltype);
                    jsonObject.put("type", type);
                    jsonObject.put("dmlurl", dmlurl);
                    baseTypeMap.put("field" + recordSet.getInt("fieldid"), jsonObject);
                }
            }

            sql = "insert into cus_fielddata  ";
            StringBuilder valueStr = new StringBuilder();
            for (int i = 0; i < baseFields.length; i++) {
                String fieldname = baseFields[i];
                JSONObject jsonObject = baseTypeMap.get(baseFields[i]);
                fielddbType = jsonObject.getString("fielddbtype");
                jsonObject.put("fieldvalue", baseValues[i]);
                String fieldvalue = HrmFieldManager.getReallyFieldvalue(jsonObject);

                EncryptFieldEntity encryptFieldEntity = new EncryptFieldConfigComInfo().getFieldEncryptConfig("cus_fielddata", fieldname, "HrmCustomFieldByInfoType", scopeId);
                if (encryptFieldEntity != null && "1".equals(encryptFieldEntity.getIsEncrypt())) {
                    //是否需要加密
                    fieldvalue = Util.null2String(encryptUtil.encryt("cus_fielddata", fieldname, "HrmCustomFieldByInfoType", scopeId, fieldvalue, fieldvalue));
                }

                if (fielddbType.toLowerCase().startsWith("char") || fielddbType.toLowerCase().startsWith("varchar") || fielddbType.toLowerCase().startsWith("text")) {
                    valueStr.append(",").append("'").append(!"".equals(fieldvalue) ? fieldvalue : "").append("'");
                } else {
                    valueStr.append(",").append(!"".equals(fieldvalue) ? fieldvalue : "NULL");
                }
            }
            valueStr = new StringBuilder(valueStr.substring(1));
            sql += "(scope,scopeid,id," + baseFild + ") values('HrmCustomFieldByInfoType'," + -1 + "," + id + "," + valueStr + ")";
        } catch (Exception e) {
            writeLog(e);
        }
        recordSet.setNoAutoEncrypt(true);
        return recordSet.execute(sql);
    }


    /**
     * 更新基础自定义字段
     *
     * @param baseFild  存储人员自定义数据的字段
     * @param baseValue 自定义数据值
     * @param id        需要添加自定义信息的人员id
     * @return
     */
    public boolean updateBaseData(String baseFild, String baseValue, int id) {
        if (baseFild == null || "".equals(baseFild)) {
            return false;
        }

        //检查cus_fielddata表中是否存在，对应id人员的基础自定义信息，如果不存在则向数据库添加
        RecordSet recordSet = new RecordSet();
        String checkbaseInfo = "select id from cus_fielddata where scope='HrmCustomFieldByInfoType' and scopeid=-1 and id=" + id;
        recordSet.execute(checkbaseInfo);
        if (!recordSet.next()) {
            return !addBaseData(baseFild, baseValue, id);
        }

        String[] baseValues = baseValue.split(";");
        String[] baseFields = baseFild.split(",");
        String fielddbType;
        String sql = "";
        String scopeId = "-1";
        EncryptUtil encryptUtil = new EncryptUtil();
        boolean flag = false;
        try {
            if (baseTypeMap == null) {
                baseTypeMap = new HashMap<>();
                String personSql = "select t1.fieldid,t1.hrm_fieldlable,t1.ismand,t2.fielddbtype,t2.fieldhtmltype,t2.type,t1.dmlurl from cus_formfield t1, cus_formdict t2 where t1.scope='HrmCustomFieldByInfoType' and t1.scopeid=-1 and t1.fieldid=t2.id order by t1.fieldorder";
                recordSet.execute(personSql);
                while (recordSet.next()) {
                    String fieldid = Util.null2String(recordSet.getString("fieldid"));
                    String fielddbtype = Util.null2String(recordSet.getString("fielddbtype"));
                    String fieldhtmltype = Util.null2String(recordSet.getString("fieldhtmltype"));
                    String type = Util.null2String(recordSet.getString("type"));
                    String dmlurl = Util.null2String(recordSet.getString("dmlurl"));

                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("fieldid", fieldid);
                    jsonObject.put("fielddbtype", fielddbtype);
                    jsonObject.put("fieldhtmltype", fieldhtmltype);
                    jsonObject.put("type", type);
                    jsonObject.put("dmlurl", dmlurl);
                    baseTypeMap.put("field" + recordSet.getInt("fieldid"), jsonObject);
                }
            }

            sql = "update cus_fielddata set ";
            StringBuilder setStr = new StringBuilder();
            for (int i = 0; i < baseFields.length; i++) {
                String fieldname = baseFields[i];
                JSONObject jsonObject = baseTypeMap.get(baseFields[i]);
                fielddbType = jsonObject.getString("fielddbtype");
                jsonObject.put("fieldvalue", baseValues[i]);
                String fieldvalue = HrmFieldManager.getReallyFieldvalue(jsonObject);
                EncryptFieldEntity encryptFieldEntity = new EncryptFieldConfigComInfo().getFieldEncryptConfig("cus_fielddata", fieldname, "HrmCustomFieldByInfoType", scopeId);
                if (encryptFieldEntity != null && "1".equals(encryptFieldEntity.getIsEncrypt())) {
                    //是否需要加密
                    fieldvalue = Util.null2String(encryptUtil.encryt("cus_fielddata", fieldname, "HrmCustomFieldByInfoType", scopeId, fieldvalue, fieldvalue));
                }
                if (fieldvalue.startsWith(",")) {
                    fieldvalue = fieldvalue.substring(1);
                }
                if (fieldvalue.endsWith(",")) {
                    fieldvalue = fieldvalue.substring(0, fieldvalue.length() - 1);
                }
                if (!"".equals(fieldvalue)) {
                    flag = true;
                    if (fielddbType.toLowerCase().startsWith("char") || fielddbType.toLowerCase().startsWith("varchar") || fielddbType.toLowerCase().startsWith("text")) {
                        setStr.append(",").append(baseFields[i]).append("='").append(fieldvalue).append("'");
                    } else {
                        setStr.append(",").append(baseFields[i]).append("=").append(fieldvalue);
                    }
                }
            }
            sql += setStr.substring(1) + " where scope='HrmCustomFieldByInfoType' and scopeid=-1 and id=" + id;
        } catch (Exception e) {
            writeLog(e);
        }
        recordSet.setNoAutoEncrypt(true);
        if (flag) {
            return !recordSet.execute(sql);
        } else {
            return false;
        }
    }


    /**
     * 插入个人自定义字段信息
     *
     * @param personFild  存储人员自定义数据的字段
     * @param personValue 自定义数据值
     * @param id          需要添加自定义信息的人员id
     * @return
     */
    public boolean addPersonData(String personFild, String personValue, int id) {
        if (personFild == null || "".equals(personFild)) {
            return true;
        }
        String[] personValues = personValue.split(";");
        String[] personFields = personFild.split(",");
        String fielddbType;
        String sql = "";
        String scopeId = "1";
        EncryptUtil encryptUtil = new EncryptUtil();
        RecordSet recordSet = new RecordSet();
        try {
            if (personTypeMap == null) {
                personTypeMap = new HashMap<>();
                String personSql = "select t1.fieldid,t1.hrm_fieldlable,t1.ismand,t2.fielddbtype,t2.fieldhtmltype,t2.type,t1.dmlurl from cus_formfield t1, cus_formdict t2 where t1.scope='HrmCustomFieldByInfoType' and t1.scopeid=1 and t1.fieldid=t2.id order by t1.fieldorder";
                recordSet.execute(personSql);
                while (recordSet.next()) {
                    String fieldid = Util.null2String(recordSet.getString("fieldid"));
                    String fielddbtype = Util.null2String(recordSet.getString("fielddbtype"));
                    String fieldhtmltype = Util.null2String(recordSet.getString("fieldhtmltype"));
                    String type = Util.null2String(recordSet.getString("type"));
                    String dmlurl = Util.null2String(recordSet.getString("dmlurl"));

                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("fieldid", fieldid);
                    jsonObject.put("fielddbtype", fielddbtype);
                    jsonObject.put("fieldhtmltype", fieldhtmltype);
                    jsonObject.put("type", type);
                    jsonObject.put("dmlurl", dmlurl);
                    personTypeMap.put("field" + recordSet.getInt("fieldid"), jsonObject);
                }
            }

            sql = "insert into cus_fielddata  ";
            StringBuilder valueStr = new StringBuilder();
            for (int i = 0; i < personFields.length; i++) {
                String fieldname = personFields[i];
                JSONObject jsonObject = personTypeMap.get(personFields[i]);
                fielddbType = jsonObject.getString("fielddbtype");
                jsonObject.put("fieldvalue", personValues[i]);
                String fieldvalue = HrmFieldManager.getReallyFieldvalue(jsonObject);
                EncryptFieldEntity encryptFieldEntity = new EncryptFieldConfigComInfo().getFieldEncryptConfig("cus_fielddata", fieldname, "HrmCustomFieldByInfoType", scopeId);
                if (encryptFieldEntity != null && "1".equals(encryptFieldEntity.getIsEncrypt())) {
                    //是否需要加密
                    fieldvalue = Util.null2String(encryptUtil.encryt("cus_fielddata", fieldname, "HrmCustomFieldByInfoType", scopeId, fieldvalue, fieldvalue));
                }
                if (fielddbType.toLowerCase().startsWith("char") || fielddbType.toLowerCase().startsWith("varchar") || fielddbType.toLowerCase().startsWith("text")) {
                    valueStr.append(",").append("'").append(!"".equals(fieldvalue) ? fieldvalue : "").append("'");
                } else {
                    valueStr.append(",").append(!"".equals(fieldvalue) ? fieldvalue : "NULL");
                }
            }
            valueStr = new StringBuilder(valueStr.substring(1));
            sql += "(scope,scopeid,id," + personFild + ") values('HrmCustomFieldByInfoType'," + 1 + "," + id + "," + valueStr + ")";
        } catch (Exception e) {
            writeLog(e);
        }
        recordSet.setNoAutoEncrypt(true);
        return recordSet.execute(sql);
    }


    /**
     * 更新个人自定义字段
     *
     * @param personFild  存储人员自定义数据的字段
     * @param personValue 自定义数据值
     * @param id          需要添加自定义信息的人员id
     * @return
     */
    public boolean updatePersonData(String personFild, String personValue, int id) {
        if (personFild == null || "".equals(personFild)) {
            return false;
        }
        //检查cus_fielddata表中是否存在，对应id人员的个人自定义信息，如果不存在则向数据库添加
        String checkWorkInfo = "select id from cus_fielddata where scope='HrmCustomFieldByInfoType' and scopeid=1 and id=" + id;
        RecordSet recordSet = new RecordSet();
        recordSet.execute(checkWorkInfo);
        if (!recordSet.next()) {
            return !addPersonData(personFild, personValue, id);
        }

        String[] personValues = personValue.split(";");
        String[] personFields = personFild.split(",");
        String fielddbType;
        String sql = "";
        String scopeId = "1";
        EncryptUtil encryptUtil = new EncryptUtil();
        boolean flag = false;
        try {
            if (personTypeMap == null) {
                personTypeMap = new HashMap<>();
                String personSql = "select t1.fieldid,t1.hrm_fieldlable,t1.ismand,t2.fielddbtype,t2.fieldhtmltype,t2.type,t1.dmlurl from cus_formfield t1, cus_formdict t2 where t1.scope='HrmCustomFieldByInfoType' and t1.scopeid=1 and t1.fieldid=t2.id order by t1.fieldorder";
                recordSet.execute(personSql);
                while (recordSet.next()) {
                    String fieldid = Util.null2String(recordSet.getString("fieldid"));
                    String fielddbtype = Util.null2String(recordSet.getString("fielddbtype"));
                    String fieldhtmltype = Util.null2String(recordSet.getString("fieldhtmltype"));
                    String type = Util.null2String(recordSet.getString("type"));
                    String dmlurl = Util.null2String(recordSet.getString("dmlurl"));

                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("fieldid", fieldid);
                    jsonObject.put("fielddbtype", fielddbtype);
                    jsonObject.put("fieldhtmltype", fieldhtmltype);
                    jsonObject.put("type", type);
                    jsonObject.put("dmlurl", dmlurl);
                    personTypeMap.put("field" + recordSet.getInt("fieldid"), jsonObject);
                }
            }

            sql = "update cus_fielddata set ";
            StringBuilder setStr = new StringBuilder();
            for (int i = 0; i < personFields.length; i++) {
                String fieldname = personFields[i];
                JSONObject jsonObject = personTypeMap.get(personFields[i]);
                fielddbType = jsonObject.getString("fielddbtype");
                jsonObject.put("fieldvalue", personValues[i]);
                String fieldvalue = HrmFieldManager.getReallyFieldvalue(jsonObject);
                EncryptFieldEntity encryptFieldEntity = new EncryptFieldConfigComInfo().getFieldEncryptConfig("cus_fielddata", fieldname, "HrmCustomFieldByInfoType", scopeId);
                if (encryptFieldEntity != null && "1".equals(encryptFieldEntity.getIsEncrypt())) {
                    //是否需要加密
                    fieldvalue = Util.null2String(encryptUtil.encryt("cus_fielddata", fieldname, "HrmCustomFieldByInfoType", scopeId, fieldvalue, fieldvalue));
                }
                if (fieldvalue.startsWith(",")) {
                    fieldvalue = fieldvalue.substring(1);
                }
                if (fieldvalue.endsWith(",")) {
                    fieldvalue = fieldvalue.substring(0, fieldvalue.length() - 1);
                }
                if (!"".equals(fieldvalue)) {
                    flag = true;
                    if (fielddbType.toLowerCase().startsWith("char") || fielddbType.toLowerCase().startsWith("varchar") || fielddbType.toLowerCase().startsWith("text")) {
                        setStr.append(",").append(personFields[i]).append("='").append(fieldvalue).append("'");
                    } else {
                        setStr.append(",").append(personFields[i]).append("=").append(fieldvalue);
                    }
                }
            }
            sql += setStr.substring(1) + " where scope='HrmCustomFieldByInfoType' and scopeid=1 and id=" + id;
        } catch (Exception e) {
            writeLog(e);
        }
        recordSet.setNoAutoEncrypt(true);
        return (flag && !recordSet.execute(sql));
    }


    /**
     * 插入工作自定义字段
     *
     * @param workField 存储工作信息自定义数据的字段
     * @param workValue 自定义数据值
     * @param id        需要添加自定义信息的人员id
     * @return
     */
    public boolean addWorkData(String workField, String workValue, int id) {
        if (workField == null || "".equals(workField)) {
            return true;
        }
        String[] workValues = workValue.split(";");
        String[] workFields = workField.split(",");
        String fielddbType;
        String sql = "";
        String scopeId = "3";
        EncryptUtil encryptUtil = new EncryptUtil();
        RecordSet recordSet = new RecordSet();
        try {
            if (workTypeMap == null) {
                workTypeMap = new HashMap<>();
                String workSql = "select t1.fieldid,t1.hrm_fieldlable,t1.ismand,t2.fielddbtype,t2.fieldhtmltype,t2.type,t1.dmlurl from cus_formfield t1, cus_formdict t2 where t1.scope='HrmCustomFieldByInfoType' and t1.scopeid=3 and t1.fieldid=t2.id order by t1.fieldorder";
                recordSet.execute(workSql);
                while (recordSet.next()) {
                    String fieldid = Util.null2String(recordSet.getString("fieldid"));
                    String fielddbtype = Util.null2String(recordSet.getString("fielddbtype"));
                    String fieldhtmltype = Util.null2String(recordSet.getString("fieldhtmltype"));
                    String type = Util.null2String(recordSet.getString("type"));
                    String dmlurl = Util.null2String(recordSet.getString("dmlurl"));

                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("fieldid", fieldid);
                    jsonObject.put("fielddbtype", fielddbtype);
                    jsonObject.put("fieldhtmltype", fieldhtmltype);
                    jsonObject.put("type", type);
                    jsonObject.put("dmlurl", dmlurl);
                    workTypeMap.put("field" + recordSet.getInt("fieldid"), jsonObject);
                }
            }
            sql = "insert into cus_fielddata  ";
            StringBuilder valueStr = new StringBuilder();
            for (int i = 0; i < workFields.length; i++) {
                String fieldname = workFields[i];
                JSONObject jsonObject = workTypeMap.get(workFields[i]);
                fielddbType = jsonObject.getString("fielddbtype");
                jsonObject.put("fieldvalue", workValues[i]);
                String fieldvalue = HrmFieldManager.getReallyFieldvalue(jsonObject);
                EncryptFieldEntity encryptFieldEntity = new EncryptFieldConfigComInfo().getFieldEncryptConfig("cus_fielddata", fieldname, "HrmCustomFieldByInfoType", scopeId);
                if (encryptFieldEntity != null && "1".equals(encryptFieldEntity.getIsEncrypt())) {
                    //是否需要加密
                    fieldvalue = Util.null2String(encryptUtil.encryt("cus_fielddata", fieldname, "HrmCustomFieldByInfoType", scopeId, fieldvalue, fieldvalue));
                }
                if (fielddbType.toLowerCase().startsWith("char") || fielddbType.toLowerCase().startsWith("varchar") || fielddbType.toLowerCase().startsWith("text")) {
                    valueStr.append(",").append("'").append(!"".equals(fieldvalue) ? fieldvalue : "").append("'");
                } else {
                    valueStr.append(",").append(!"".equals(fieldvalue) ? fieldvalue : "NULL");
                }
            }
            valueStr = new StringBuilder(valueStr.substring(1));
            sql += "(scope,scopeid,id," + workField + ") values('HrmCustomFieldByInfoType'," + 3 + "," + id + "," + valueStr + ")";
        } catch (Exception e) {
            writeLog(e);
        }
        recordSet.setNoAutoEncrypt(true);
        return recordSet.execute(sql);
    }


    /**
     * 更新工作自定义字段
     *
     * @param workField 存储工作信息自定义数据的字段
     * @param workValue 自定义数据值
     * @param id        需要添加自定义信息的人员id
     * @return
     */
    public boolean updateWorkData(String workField, String workValue, int id) {
        if (workField == null || "".equals(workField)) {
            return false;
        }

        //检查cus_fielddata表中是否存在，对应id人员的工作自定义信息，如果不存在则向数据库添加
        String checkWorkInfo = "select id from cus_fielddata where scope='HrmCustomFieldByInfoType' and scopeid=3 and id=" + id;
        RecordSet recordSet = new RecordSet();
        recordSet.execute(checkWorkInfo);
        if (!recordSet.next()) {
            return !addWorkData(workField, workValue, id);
        }

        String[] workValues = workValue.split(";");
        String[] workFields = workField.split(",");
        String fielddbType;
        String sql = "";
        String scopeId = "3";
        EncryptUtil encryptUtil = new EncryptUtil();
        boolean flag = false;
        try {
            if (workTypeMap == null) {
                workTypeMap = new HashMap<>();
                String workSql = "select t1.fieldid,t1.hrm_fieldlable,t1.ismand,t2.fielddbtype,t2.fieldhtmltype,t2.type,t1.dmlurl from cus_formfield t1, cus_formdict t2 where t1.scope='HrmCustomFieldByInfoType' and t1.scopeid=3 and t1.fieldid=t2.id order by t1.fieldorder";
                recordSet.execute(workSql);
                while (recordSet.next()) {
                    String fieldid = Util.null2String(recordSet.getString("fieldid"));
                    String fielddbtype = Util.null2String(recordSet.getString("fielddbtype"));
                    String fieldhtmltype = Util.null2String(recordSet.getString("fieldhtmltype"));
                    String type = Util.null2String(recordSet.getString("type"));
                    String dmlurl = Util.null2String(recordSet.getString("dmlurl"));

                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("fieldid", fieldid);
                    jsonObject.put("fielddbtype", fielddbtype);
                    jsonObject.put("fieldhtmltype", fieldhtmltype);
                    jsonObject.put("type", type);
                    jsonObject.put("dmlurl", dmlurl);
                    workTypeMap.put("field" + recordSet.getInt("fieldid"), jsonObject);
                }
            }

            sql = "update cus_fielddata set ";
            StringBuilder setStr = new StringBuilder();
            for (int i = 0; i < workFields.length; i++) {
                String fieldname = workFields[i];
                JSONObject jsonObject = workTypeMap.get(workFields[i]);
                fielddbType = jsonObject.getString("fielddbtype");
                jsonObject.put("fieldvalue", workValues[i]);
                String fieldvalue = HrmFieldManager.getReallyFieldvalue(jsonObject);
                EncryptFieldEntity encryptFieldEntity = new EncryptFieldConfigComInfo().getFieldEncryptConfig("cus_fielddata", fieldname, "HrmCustomFieldByInfoType", scopeId);
                if (encryptFieldEntity != null && "1".equals(encryptFieldEntity.getIsEncrypt())) {
                    //是否需要加密
                    fieldvalue = Util.null2String(encryptUtil.encryt("cus_fielddata", fieldname, "HrmCustomFieldByInfoType", scopeId, fieldvalue, fieldvalue));
                }
                if (fieldvalue.startsWith(",")) {
                    fieldvalue = fieldvalue.substring(1);
                }
                if (fieldvalue.endsWith(",")) {
                    fieldvalue = fieldvalue.substring(0, fieldvalue.length() - 1);
                }
                if (!"".equals(fieldvalue)) {
                    flag = true;
                    if (fielddbType.toLowerCase().startsWith("char") || fielddbType.toLowerCase().startsWith("varchar") || fielddbType.toLowerCase().startsWith("text")) {
                        setStr.append(",").append(workFields[i]).append("='").append(fieldvalue).append("'");
                    } else {
                        setStr.append(",").append(workFields[i]).append("=").append(fieldvalue);
                    }
                }
            }

            sql += setStr.substring(1) + " where scope='HrmCustomFieldByInfoType' and scopeid=3 and id=" + id;
        } catch (Exception e) {
            writeLog(e);
        }
        recordSet.setNoAutoEncrypt(true);
        return (flag && !recordSet.execute(sql));
    }

    /**
     * 根据分部名称获取分部Id
     *
     * @param subCompanyName 分部名称 eg：泛微广东>泛微深圳
     * @return
     */
    public int getSubCompanyId(String subCompanyName) {

        String[] subCompanyNames = subCompanyName.split(">");
        if (subCompanyNames.length >= 10) {
            return -9;
        }
        int currentId = 0;
        int parentId = 0;
        int iscanceled;

        String currentidsql;
        String canceledsql;
        String sql;
        RecordSet recordSet = new RecordSet();

        String supsubcomidConditon = DbDialectFactory.get(recordSet.getDBType()).isNull("supsubcomid", 0);

        for (String companyName : subCompanyNames) {
            if (StringUtil.isNull(companyName)) {
                continue;
            }

            sql = "select id from HrmSubCompany where ltrim(rtrim(dbo.convToMultiLang(ltrim(rtrim(subcompanyname))," + userlanguage + ")))='"
                    + companyName.trim() + "' and " + supsubcomidConditon + "=" + parentId;
            if ("oracle".equalsIgnoreCase(recordSet.getDBType()) || DialectUtil.isMySql(recordSet.getDBType()) || "postgresql".equalsIgnoreCase(recordSet.getDBType())) {
                sql = "select id from HrmSubCompany where ltrim(rtrim(convToMultiLang(ltrim(rtrim(subcompanyname))," + userlanguage + ")))='"
                        + companyName.trim() + "' and " + supsubcomidConditon + "=" + parentId;
            }
            currentidsql = sql + " and (canceled is null or canceled != 1)";
            currentId = getResultSetId(currentidsql);

            //added by wcd 2015-02-06 [限制分部数]
            if (currentId == 0) {
                canceledsql = sql + " and canceled='1' ";
                iscanceled = getResultSetId(canceledsql);
                if (iscanceled != 0) {
                    currentId = -2;
                }
                break;
            }
            parentId = currentId;
            if (currentId != -1) {
                rtxService.addSubCompany(parentId);  //同步RTX
            }
        }
        return currentId;
    }

    /**
     * 获取部门id
     *
     * @param deptNames    部门名称
     * @param subCompanyId 所属分部id
     * @return
     */
    public int getDeptId(String deptNames, int subCompanyId) {

        String[] deptName = deptNames.split(">");
        int currentId = 0;
        int parentId = 0;
        int iscanceled;

        String currentidsql;
        String canceledsql;
        String sql;

        RecordSet recordSet = new RecordSet();

        String supdepidConditon = DbDialectFactory.get(recordSet.getDBType()).isNull("supdepid", 0);

        for (String s : deptName) {
            if (s == null || "".equals(s)) {
                continue;
            }

            sql = "select id from HrmDepartment where subcompanyid1=" + subCompanyId + " and ltrim(rtrim(dbo.convToMultiLang(ltrim(rtrim(departmentname))," + userlanguage + ")))='"
                    + s.trim() + "' and " + supdepidConditon + "=" + parentId;
            if ("oracle".equalsIgnoreCase(recordSet.getDBType()) || DialectUtil.isMySql(recordSet.getDBType()) || "postgresql".equalsIgnoreCase(recordSet.getDBType())) {
                sql = "select id from HrmDepartment where subcompanyid1=" + subCompanyId + " and ltrim(rtrim(convToMultiLang(ltrim(rtrim(departmentname))," + userlanguage + ")))='"
                        + s.trim() + "' and " + supdepidConditon + "=" + parentId;
            }
            currentidsql = sql + " and (canceled  !=1 or canceled is null)";
            currentId = getResultSetId(currentidsql);

            if (currentId == 0) {
                canceledsql = sql + " and canceled='1' ";
                iscanceled = getResultSetId(canceledsql);
                if (iscanceled != 0) {
                    currentId = -2;
                }
                break;
            }
            parentId = currentId;
        }
        return currentId;
    }

    /**
     * 获取岗位id
     *
     * @param jobtitlename    岗位名称
     * @param jobactivityname 职务
     * @param jobgroupname    职务类型
     * @return
     */
    public int getJobTitles(String jobtitlename, String jobactivityname,
                            String jobgroupname) {
        RecordSet rs = new RecordSet();
        RecordSet recordSet = new RecordSet();
        String sqlInsert = "";

        jobgroupname = Util.convertInput2DB4(jobgroupname);
        jobactivityname = Util.convertInput2DB4(jobactivityname);

        /* 获取jobgroupid 职务类别 */
        String selSql = "select id from HrmJobGroups where ltrim(rtrim(dbo.convToMultiLang(ltrim(rtrim(jobgroupname))," + userlanguage + ")))='" + jobgroupname + "'";
        if ("oracle".equalsIgnoreCase(recordSet.getDBType()) || DialectUtil.isMySql(recordSet.getDBType()) || "postgresql".equalsIgnoreCase(recordSet.getDBType())) {
            selSql = "select id from HrmJobGroups where ltrim(rtrim(convToMultiLang(ltrim(rtrim(jobgroupname))," + userlanguage + ")))='" + jobgroupname + "'";
        }

        int jobgroupid = getResultSetId(selSql);

        if (jobgroupid == 0) {
            if (jobgroupname.length() == 0) {
                selSql = "select max(id) as id from HrmJobGroups";
                jobgroupid = getResultSetId(selSql);
            } else {
                sqlInsert = "insert into HrmJobGroups (jobgroupname,jobgroupremark ," + DbFunctionUtil.getInsertColumnSql() + ") values('"
                        + jobgroupname + "','" + jobgroupname + "'," + DbFunctionUtil.getInsertColumnValueSql(recordSet.getDBType(), 1) + ")"; // 创建
                execSql(sqlInsert);
                jobgroupid = getResultSetId(selSql);
            }
        }

        /* 获取jobactivityid 职务 */
        selSql = "select id from HrmJobActivities where ltrim(rtrim(dbo.convToMultiLang(ltrim(rtrim(jobactivityname))," + userlanguage + ")))='" + jobactivityname + "' and jobgroupid=" + jobgroupid;
        if ("oracle".equalsIgnoreCase(recordSet.getDBType()) || DialectUtil.isMySql(recordSet.getDBType()) || "postgresql".equalsIgnoreCase(recordSet.getDBType())) {
            selSql = "select id from HrmJobActivities where ltrim(rtrim(convToMultiLang(ltrim(rtrim(jobactivityname))," + userlanguage + ")))='" + jobactivityname + "' and jobgroupid=" + jobgroupid;
        }

        int jobactivityid = getResultSetId(selSql);

        if (jobactivityid == 0) {
            sqlInsert = "insert into HrmJobActivities (jobactivityname,Jobactivitymark,jobgroupid ," + DbFunctionUtil.getInsertColumnSql() + ") values('"
                    + jobactivityname + "','" + jobactivityname + "'," + jobgroupid + " ," + DbFunctionUtil.getInsertColumnValueSql(recordSet.getDBType(), 1) + ")"; // 创建
            execSql(sqlInsert);
            jobactivityid = getResultSetId(selSql);
        }

        /*获取岗位id*/
        selSql = "select id from HrmJobTitles where ltrim(rtrim(dbo.convToMultiLang(ltrim(rtrim(jobtitlemark))," + userlanguage + ")))='" + jobtitlename + "' and jobactivityid=" + jobactivityid;
        if ("oracle".equalsIgnoreCase(recordSet.getDBType()) || DialectUtil.isMySql(recordSet.getDBType()) || "postgresql".equalsIgnoreCase(recordSet.getDBType())) {
            selSql = "select id from HrmJobTitles where ltrim(rtrim(convToMultiLang(ltrim(rtrim(jobtitlemark))," + userlanguage + ")))='" + jobtitlename + "' and jobactivityid=" + jobactivityid;
        }

        int jobtitle = getResultSetId(selSql);

        if (jobtitle == 0) {
            String jobtitlecode = "";
            try {
                jobtitlecode = CodeRuleManager.getCodeRuleManager().generateRuleCode(RuleCodeType.JOBTITLES, jobtitlecode);
            } catch (Exception e) {
                writeLog(e);
            }
            sqlInsert = "insert into HrmJobTitles (jobtitlename,Jobtitlemark,jobactivityid ," + DbFunctionUtil.getInsertColumnSql() + ", jobtitlecode) values('"
                    + jobtitlename + "','" + jobtitlename + "'," + jobactivityid + " ," + DbFunctionUtil.getInsertColumnValueSql(recordSet.getDBType(), 1) + ", '" + jobtitlecode + "')"; // 创建
            execSql(sqlInsert);
            HrmTriggerUtil.generateJobtitlesPinyin(jobtitlename, null);
            jobtitle = getResultSetId(selSql);

            HrmFaceCheckManager.sync(jobtitle + "", HrmFaceCheckManager.getOptInsert(), "hrm_e9_import_getJobtitles", HrmFaceCheckManager.getOaJobtitle());

        } else {
            selSql = "select * from HrmJobTitles where id = '" + jobtitle + "' and jobactivityid = '" + jobactivityid + "' ";
            recordSet.executeSql(selSql);
            if (!recordSet.next()) {//查询这个名称已存在的岗位，对应的职务是否存在。如果对应职务的岗位不存在，则说明岗位对应的职务和职务类别有更新
                sqlInsert = "update HrmJobTitles set jobactivityid = '" + jobactivityid + "'," + DbFunctionUtil.getUpdateSetSql(rs.getDBType(), 1) + " where id = '" + jobtitle + "' ";
                rs.executeSql(sqlInsert);
            }
        }
        return jobtitle;
    }


    public static boolean needCheckLicenseForUpdate(ResourceComInfo resourceComInfo, String hrmId, HrmResourceVo vo) {
        String statusOfHrmId = resourceComInfo.getStatus(hrmId);
        String loginidOfHrmId = resourceComInfo.getLoginID(hrmId);
        String accouttypeOfHrmId = resourceComInfo.getAccountType(hrmId);

        String statusOfExcel = vo.getStatus();
        String loginidOfExcel = vo.getLoginid();
        String accouttypeOfExcel = vo.getAccounttype();

        // 1. 历史状态算license 不检查
        if ("0,1,2,3".contains(statusOfHrmId) && StringUtils.isNotBlank(loginidOfHrmId) && !"1".equals(accouttypeOfHrmId)) {
            return false;
        }
        boolean isStatus;
        if (StringUtils.isBlank(statusOfExcel)) {
            isStatus = "0,1,2,3".contains(statusOfHrmId);
        } else {
            isStatus = "正式,试用,临时,试用延期".contains(statusOfExcel);
        }
        boolean isLoginid;
        if (StringUtils.isBlank(loginidOfExcel)) {
            isLoginid = StringUtils.isNotBlank(loginidOfHrmId);
        } else {
            isLoginid = StringUtils.isNotBlank(loginidOfExcel);
        }
        boolean isAccouttype;
        if (StringUtils.isBlank(accouttypeOfExcel)) {
            isAccouttype = !"1".equals(accouttypeOfHrmId);
        } else {
            isAccouttype = "主账号".equals(accouttypeOfExcel);
        }

        return isStatus && isLoginid && isAccouttype;

    }

    /**
     * 获取直接上级Id和所有上级
     *
     * @param keyFieldValue 上级标记值，eg:编号
     * @param keyField      关键字段
     * @return
     */
    public Map<String, Comparable> getManagerIdAndStr(String hrmid, String keyFieldValue, String keyField) {

        int managerId;
        String managerstr;
        RecordSet recordSet = new RecordSet();
        Map<String, Comparable> managerInfo = new HashMap<>();
        if (!"".equals(keyFieldValue)) {
//            String selSql = "select id,managerstr from hrmResource where " + keyField + "='" + keyFieldValue + "'";
            String selSql = "select id,managerstr from hrmResource where ltrim(rtrim(dbo.convToMultiLang(ltrim(rtrim(" + keyField + "))," + userlanguage + ")))=  '" + keyFieldValue + "'";
            if ("oracle".equalsIgnoreCase(recordSet.getDBType()) || DialectUtil.isMySql(recordSet.getDBType()) || "postgresql".equalsIgnoreCase(recordSet.getDBType())) {
                selSql = "select id,managerstr from hrmResource where ltrim(rtrim(convToMultiLang(ltrim(rtrim(" + keyField + "))," + userlanguage + ")))= '" + keyFieldValue + "'";
            }
            recordSet.execute(selSql);
            while (recordSet.next()) {
                managerId = recordSet.getInt("id");
                managerstr = recordSet.getString("managerstr");
                if (!hrmid.equals("" + managerId)) { //设置上级为自身的情况
                    managerstr = "," + managerId + managerstr;
                } else {
                    managerstr = "," + managerId + ",";
                }

                managerstr = managerstr.endsWith(",") ? managerstr : (managerstr + ",");
                managerInfo.put("managerid", managerId);
                managerInfo.put("managerstr", managerstr);
            }
        }
        return managerInfo;
    }

    /**
     * 获取助理id
     *
     * @param keyFieldValue 助理标记
     * @param keyField      关键字段
     * @return
     */
    public int getAssistantid(String keyFieldValue, String keyField) {

        int getAssistantid = 0;
        RecordSet recordSet = new RecordSet();
        if (!"".equals(keyFieldValue)) {
//            String selSql = "select id from hrmResource where " + keyField + "='" + keyFieldValue + "'";
            String selSql = "select id from hrmResource where ltrim(rtrim(dbo.convToMultiLang(ltrim(rtrim(" + keyField + "))," + userlanguage + ")))=  '" + keyFieldValue + "'";
            if ("oracle".equalsIgnoreCase(recordSet.getDBType()) || DialectUtil.isMySql(recordSet.getDBType()) || "postgresql".equalsIgnoreCase(recordSet.getDBType())) {
                selSql = "select id from hrmResource where ltrim(rtrim(convToMultiLang(ltrim(rtrim(" + keyField + "))," + userlanguage + ")))= '" + keyFieldValue + "'";
            }
            getAssistantid = getResultSetId(selSql);
        }
        return getAssistantid;
    }

    /**
     * 获取主账号id
     *
     * @param keyFieldValue 主账号标记
     * @param keyField      关键字段
     * @return
     */
    public int getBelongId(String keyFieldValue, String keyField) {
        int getAssistantid = -1;
        RecordSet recordSet = new RecordSet();
        if (!"".equals(keyFieldValue)) {
//            String selSql = "select id from hrmResource where " + keyField + "='" + keyFieldValue + "'";
            String selSql = "select id from hrmResource where ltrim(rtrim(dbo.convToMultiLang(ltrim(rtrim(" + keyField + "))," + userlanguage + ")))=  '" + keyFieldValue + "'";
            if ("oracle".equalsIgnoreCase(recordSet.getDBType()) || DialectUtil.isMySql(recordSet.getDBType()) || "postgresql".equalsIgnoreCase(recordSet.getDBType())) {
                selSql = "select id from hrmResource where ltrim(rtrim(convToMultiLang(ltrim(rtrim(" + keyField + "))," + userlanguage + ")))= '" + keyFieldValue + "'";
            }
            getAssistantid = getResultSetId(selSql);
        }
        return getAssistantid;
    }

    /**
     * 办公地点id
     *
     * @param locationname 办公地点名称
     * @return
     */
    public int getLocationid(String locationname) {
        int locationid = 0;
        if (!"".equals(locationname)) {
            locationid = locationMap.getOrDefault(locationname, 0);
            if (locationid == 0) {
                String insertSql = "insert into HrmLocations(locationname,locationdesc,countryid) values('" + locationname + "','" + locationname + "',1)";
                execSql(insertSql);
                String selSql = "select id from HrmLocations where countryid=1 and locationname='" + locationname + "'";
                locationid = getResultSetId(selSql);
                locationMap.put(locationname, locationid);
            }
        }
        return locationid;
    }

    /**
     * 用工性质id
     *
     * @param usekindname 用工性质名称
     * @return
     */
    public int getUseKind(String usekindname) {
        int usekindid = 0;
        if (!"".equals(usekindname)) {
            usekindid = usekindMap.getOrDefault(usekindname, 0);
            if (usekindid == 0) {
                String insertSql = "insert into HrmUseKind(name,description) values('" + usekindname + "','" + usekindname + "')";
                execSql(insertSql);
                String selSql = "select id from HrmUseKind where name='" + usekindname + "'";
                usekindid = getResultSetId(selSql);
                usekindMap.put(usekindname, usekindid);
            }
        }
        return usekindid;
    }

    /**
     * 职称
     *
     * @param jobcall 职称名称
     * @return
     */
    public int getJobcall(String jobcall) {

        int jobcalld = 0;
        if (!"".equals(jobcall)) {
            jobcalld = jobcallMap.getOrDefault(jobcall, 0);
            if (jobcalld == 0) {
                String insertSql = "insert into HrmJobCall(name) values('" + jobcall + "')";
                execSql(insertSql);
                String selSql = "select id from HrmJobCall where name='" + jobcall + "'";
                jobcalld = getResultSetId(selSql);
                jobcallMap.put(jobcall, jobcalld);
            }
        }
        return jobcalld;
    }

    /**
     * 系统语言
     *
     * @param language 语言 eg：简体中文,English,繁體中文
     * @return
     */
    public int getSystemlanguage(String language) {
        int systemlanguageid = 7;  //系统语言默认为中文

        //系统只支持三种语言，如果是其他语言，提示输入有误
        //if (!(language.equals("English") || language.equals("繁體中文") || language.equals("简体中文")) && language != "")
        //return -1;

        //如果系统不支持多语言，则返回0
        if (("English".equals(language) || "繁體中文".equals(language)) && !"y".equalsIgnoreCase(multilanguage)) {
            return 0;
        }

        if (!"".equals(language)) {
            if ("简体中文".equals(language)) {
                systemlanguageid = cnLanguageId;
            } else {
                systemlanguageid = sysLanguage.getOrDefault(language, -1);
            }
        }
        return systemlanguageid;
    }

    /**
     * 工资银行id
     *
     * @param bank1 办公地点名称
     * @return
     */
    public int getBankId(String bank1) {
        int id = 0;
        if (!"".equals(bank1)) {
            String insertSql = "insert into hrmbank(bankname,bankdesc) values('" + bank1 + "','" + bank1 + "')";
            execSql(insertSql);
            String selSql = "select id from hrmbank where bankname='" + bank1 + "'";
            id = getResultSetId(selSql);
        }
        return id;
    }

    /**
     * 获取员工状态
     *
     * @param status 员工状态值
     * @return
     */
    public int getStatus(String status) {

        int statusid;
        switch (status) {
            case "试用":
                statusid = 0;
                break;
            case "正式":
                statusid = 1;
                break;
            case "临时":
                statusid = 2;
                break;
            case "试用延期":
                statusid = 3;
                break;
            case "解聘":
                statusid = 4;
                break;
            case "离职":
                statusid = 5;
                break;
            case "退休":
                statusid = 6;
                break;
            case "无效":
                statusid = 7;
                break;
            default:
                statusid = 1;
                break;
        }
        return statusid;
    }


    public int getClassification(String classification) {

        int classificationid;
        switch (classification) {
            case "核心":
                classificationid = 0;
                break;
            case "重要":
                classificationid = 1;
                break;
            case "一般":
                classificationid = 2;
                break;
            default:
                classificationid = 3;
                break;
        }
        return classificationid;
    }

    /**
     * 获取学历Id
     *
     * @param educationlevel 学历值
     * @return
     */
    public int getEducationlevel(String educationlevel) {
        int educationlevelid = 0;
        if (!"".equals(educationlevel)) {
            educationlevelid = educationlevelMap.getOrDefault(educationlevel, 0);
            if (educationlevelid == 0) {
                String insertSql = "insert into HrmEducationLevel(name,description) values('" + educationlevel + "','" + educationlevel + "')";
                execSql(insertSql);
                String selSql = "select id from HrmEducationLevel where name='" + educationlevel + "'";
                educationlevelid = getResultSetId(selSql);
                educationlevelMap.put(educationlevel, educationlevelid);
            }
        }
        return educationlevelid;
    }

    /**
     * 获取身体状况
     *
     * @param healthinfo
     * @return
     */
    public String getHealthinfo(String healthinfo) {

        String healthinfoid;

        switch (healthinfo) {
            case "良好":
                healthinfoid = "1";
                break;
            case "一般":
                healthinfoid = "2";
                break;
            case "较差":
                healthinfoid = "3";
                break;
            default:
                healthinfoid = "0";
                break;
        }

        return healthinfoid;
    }

    /**
     * 获取id与workcode_lastname 键值对，用于对导入数据重复性判断
     *
     * @param keyField key值，重复性验证字段
     */
    public void getKeyMap(String keyField) {
        RecordSet recordSet = new RecordSet();
        String sql;
        sql = "select id, accounttype,isADAccount,certificatenum,loginid,workcode, ltrim(rtrim(convToMultiLang(ltrim(rtrim(" + keyField + "))," + userlanguage + "))) as " + keyField + " from hrmResource";
        if ("sqlserver".equalsIgnoreCase(recordSet.getDBType())) {
            sql = "select id, accounttype,isADAccount,certificatenum,loginid,workcode, ltrim(rtrim(dbo.convToMultiLang(ltrim(rtrim(" + keyField + "))," + userlanguage + "))) as " + keyField + " from hrmResource";
        }
        recordSet.execute(sql);
        String cerNum;
        while (recordSet.next()) {
            for (String key : checkKeys) {
                Map<String, String> checkInfo = checkInfos.get(key);
                if (checkInfo == null) {
                    checkInfo = new HashMap<>();
                    checkInfos.put(key, checkInfo);
                } else {
                    checkInfo = checkInfos.get(key);
                }
                String val = Util.null2String(recordSet.getString(key));
                checkInfo.put(val, recordSet.getString("id"));
                checkInfos.put(key, checkInfo);
            }

            cerNum = recordSet.getString("certificatenum");
            keyMap.put(recordSet.getString(keyField), recordSet.getInt("id"));
            isADAccountMap.put(Util.null2String(recordSet.getString("id")), Util.null2String(recordSet.getString("isADAccount")));
            String accounttype = recordSet.getString("accounttype");
            if (!"1".equalsIgnoreCase(accounttype)) {
                if (StringUtil.isNotNull(cerNum)) {
                    certificateNums.put(StringUtil.vString(cerNum), recordSet.getInt("id"));
                }
            }
        }

    }


    /**
     * 执行插入操作
     *
     * @param sql
     * @return
     */

    public boolean execSql(String sql) {
        RecordSet recordSet = new RecordSet();
        return recordSet.execute(sql);
    }

    /**
     * 获得查询结果Id
     *
     * @param sql 查询语句
     * @return
     */
    public int getResultSetId(String sql) {
        int currentId = 0;
        RecordSet recordSet = new RecordSet();
        recordSet.execute(sql);
        try {
            while (recordSet.next()) {
                currentId = recordSet.getInt("id");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return currentId;
    }

    /**
     * 创建日志对象
     *
     * @param vo        HrmResourceVo  人员信息对象
     * @param operation 操作类型  验证|创建|更新
     * @param status    状态 成功|失败
     * @param reason    失败原因
     * @return ImportLog对象
     */
    public ImportLog createLog(HrmResourceVo vo, String operation, String status, String reason) {
        ImportLog log = new ImportLog();

        log.setWorkCode(vo.getWorkcode());  //编号
        log.setLastname(vo.getLastname());  //用户名
        log.setLoginid(vo.getLoginid());    //登录名
        log.setOperation(operation);        //操作类型
        if (vo.getSubcompanyid1() != null && vo.getDepartmentid() != null) {
            log.setDepartment(vo.getSubcompanyid1() + ">" + vo.getDepartmentid()); //分部部门
        } else {
            log.setDepartment("");
        }
        log.setStatus(status);              //状态，成功、失败
        log.setReason(reason);              //原因

        try {
            String relatedName = "";
            switch (this.keyField) {
                case "workcode":
                    relatedName = log.getWorkCode();
                    break;
                case "loginid":
                    relatedName = log.getLoginid();
                    break;
                case "lastname":
                    relatedName = log.getLastname();
                    break;
            }
            MapperProxyFactory.getProxy(JclImportHistoryDetailMapper.class).insertHistoryDetail(JclImportHistoryDetailPO.builder().pid((long) this.pId).rowNums(this.rowNum + 1 + "").relatedName(relatedName).operateDetail("成功".equals(log.getStatus()) ? relatedName + "导入成功！" : log.getReason()).status("成功".equals(log.getStatus()) ? "1" : "0").build());
        } catch (Exception e) {
            writeLog(e);
        }
        return log;
    }

    //整数判断
    public static boolean isInteger(String str) {
        if (str == null) {
            return false;
        }
        Pattern pattern = Pattern.compile("[0-9]+");
        return pattern.matcher(str).matches();
    }


    private boolean checkInfo(HrmResourceVo hrmResourceVo, List<ImportLog> resultList) {
        //新增账号、工号唯一性校验
        new BaseBean().writeLog("checkKeys【" + Arrays.toString(checkKeys) + "】");
        for (String key : checkKeys) {
            Map<String, String> checkInfo = checkInfos.get(key);
            if (checkInfo != null && !checkInfo.isEmpty()) {
                String val = "";
                String errorMsg = "";
                switch (key) {
                    case "loginid":
                        val = Util.null2String(hrmResourceVo.getLoginid()).trim();
                        errorMsg = SystemEnv.getHtmlLabelName(522076, userlanguage);
                        break;
                    case "workcode":
                        val = Util.null2String(hrmResourceVo.getWorkcode()).trim();
                        errorMsg = SystemEnv.getHtmlLabelName(520197, userlanguage);
                        break;
                    case "certificatenum":
                        val = Util.null2String(hrmResourceVo.getCertificatenum()).trim();
                        errorMsg = SystemEnv.getHtmlLabelName(83521, userlanguage);
                        break;
                }
                int reosurceid = Util.getIntValue(checkInfo.get(val));
                if (hrmResourceVo.getId() != null && hrmResourceVo.getId() == reosurceid) {
                    //如果是当前记录，不需要校验
                    continue;
                }

                if (reosurceid > 0 && val.length() > 0) {
                    resultList.add(createLog(vo, "add".equals(this.operateType) ? "创建" : "更新", "失败", errorMsg));
                    return true;
                }
            }
        }
        return false;
    }


    public int getUserlanguage() {
        return userlanguage;
    }


    public void setUserlanguage(int userlanguage) {
        this.userlanguage = userlanguage;
    }
}
