package com.engine.organization.service.impl;

import com.engine.common.entity.EncryptFieldEntity;
import com.engine.common.util.ParamUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.core.impl.Service;
import com.engine.encrypt.biz.EncryptFieldConfigComInfo;
import com.engine.hrm.entity.RuleCodeType;
import com.engine.hrm.service.ImportLogService;
import com.engine.hrm.service.impl.ImportLogServiceImpl;
import com.engine.hrm.util.CodeRuleManager;
import com.engine.hrm.util.HrmWeakPasswordUtil;
import com.engine.hrm.util.face.HrmFaceCheckManager;
import com.engine.hrm.util.face.ValidateFieldManager;
import com.engine.hrm.util.face.bean.CheckItemBean;
import com.engine.organization.entity.company.po.CompPO;
import com.engine.organization.entity.department.po.DepartmentPO;
import com.engine.organization.entity.hrmresource.param.HrmResourceImportParam;
import com.engine.organization.entity.hrmresource.po.HrmResourcePO;
import com.engine.organization.entity.job.po.JobPO;
import com.engine.organization.entity.postion.po.PostInfoPO;
import com.engine.organization.entity.postion.po.PostPO;
import com.engine.organization.mapper.comp.CompMapper;
import com.engine.organization.mapper.department.DepartmentMapper;
import com.engine.organization.mapper.hrmresource.HrmResourceMapper;
import com.engine.organization.mapper.job.JobMapper;
import com.engine.organization.mapper.post.PostInfoMapper;
import com.engine.organization.mapper.post.PostMapper;
import com.engine.organization.service.HrmResourceImportProcessService;
import com.engine.organization.util.PageInfoSortUtil;
import com.engine.organization.util.db.MapperProxyFactory;
import ln.LN;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import weaver.common.DateUtil;
import weaver.common.StringUtil;
import weaver.conn.RecordSet;
import weaver.encrypt.EncryptUtil;
import weaver.general.BaseBean;
import weaver.general.PasswordUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.common.database.dialect.DbDialectFactory;
import weaver.hrm.common.database.dialect.DialectUtil;
import weaver.hrm.definedfield.HrmFieldManager;
import weaver.hrm.passwordprotection.manager.HrmResourceManager;
import weaver.hrm.resource.ResourceComInfo;
import weaver.hrm.settings.ChgPasswdReminder;
import weaver.hrm.settings.RemindSettings;
import weaver.join.hrm.in.ImportLog;
import weaver.join.hrm.in.processImpl.HrmTlevelManager;
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;

/**
 * @author:dxfeng
 * @createTime: 2022/06/27
 * @version: 1.0
 */
public class HrmResourceImportProcessServiceImpl extends Service implements HrmResourceImportProcessService {


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

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

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

    private final String[] checkKeys = new String[]{"login_id", "work_code"};

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

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

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

    LN license = new LN();           //license

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

    private int scCount = 0;

    private HrmResourceImportParam hrmResourceImportParam = 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;


    private HrmResourceMapper getResourceMapper() {
        return MapperProxyFactory.getProxy(HrmResourceMapper.class);
    }

    private CompMapper getCompMapper() {
        return MapperProxyFactory.getProxy(CompMapper.class);
    }

    private DepartmentMapper getDepartmentMapper() {
        return MapperProxyFactory.getProxy(DepartmentMapper.class);
    }

    private JobMapper getJobMapper() {
        return MapperProxyFactory.getProxy(JobMapper.class);
    }

    private PostInfoMapper getPostInfoMapper() {
        return MapperProxyFactory.getProxy(PostInfoMapper.class);
    }

    private PostMapper getPostMapper() {
        return MapperProxyFactory.getProxy(PostMapper.class);
    }

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

    @Override
    public Map<String, Object> init(HttpServletRequest request) {
        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"));

            ImportLogService importLogService = ServiceUtil.getService(ImportLogServiceImpl.class, user);
            Map<String, Object> params = ParamUtil.request2Map(request);
            params.put("operateType", this.operateType);
            retmap = importLogService.saveImportLog(params, request, user);
            if (Util.null2String(retmap.get("status")).equals("1")) {
                this.pId = Util.getIntValue(Util.null2String(retmap.get("pId")));
                request.getSession(true).setAttribute("hrmresourcePId", this.pId);
            }

            final int F_Y = 0;
            final int F_N = 1;
            LN license = new LN();
            license.InLicense();
            int type = StringUtil.parseToInt(license.getScType(), F_N);
            scCount = StringUtil.parseToInt(license.getScCount(), 0);
            scCount = type == F_Y ? (Math.max(scCount, 0)) : 0;
            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) {
            new BaseBean().writeLog(e);
        }
        return retmap;
    }

    /**
     * 对人员数据进行解析，并添加到数据库
     *
     * @param hrMap 人员数据Map集合
     */
    @Override
    public void processMap(Map<String, HrmResourceImportParam> hrMap) {//增加同步锁，防止同时多次调用
        List<ImportLog> resultList = new ArrayList<>();          //导入结果
        RecordSet recordSet = new RecordSet();
        ImportLogService importLogService = ServiceUtil.getService(ImportLogServiceImpl.class, user);
        try {
            String subCompanyName = "";      //分部名称
            String departmentName = "";      //部门名称
            long companyId = 0L;           // 分部Id
            long departmentId = 0L;            // 部门id
            String key;                   // workcode_lastname 组合
            getKeyMap(keyField);             //获取重复性验证字段Map
            Long id;

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

            Class<HrmResourcePO> resourcePOClass = HrmResourcePO.class;
            Class<HrmResourceImportParam> importParamClass = HrmResourceImportParam.class;

            String field = "id,work_code,login_id,last_name,sex,account_type,belong_to,company_id,department_id,job_activity,job_title,job_call,job_level,job_group_id,job_activity_desc,status,system_language,resource_image_id,messager_url,location_id,manager_id,assistant_id,mobile,telephone,mobile_call,fax,email,workroom,pass_word,sec_level,birthday,folk,native_place,reg_resident_place,certificate_num,marital_status,policy,be_member_date,be_party_date,islabouunion,degree,health_info,education_level,height,weight,use_kind,start_date,end_date,probation_end_date,resident_place,home_address,temp_resident_number,company_start_date,work_start_date,accum_fund_account,account_name,bank_id,account_id,show_order,classification,company_work_year,work_year";

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

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

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

            String obj;
            HrmResourcePO hrmResourcePO;
            for (Object o : keyArray) {
                obj = o.toString();
                hrmResourceImportParam = hrMap.get(obj);
                key = obj;
                hrmResourcePO = new HrmResourcePO();
                this.rowNum++;
                try {  // 异常处理

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

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

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

                        if (keyMap.get(key) == null && StringUtils.isNotBlank(hrmResourceImportParam.getLogin_id()) && ("主账号".equals(hrmResourceImportParam.getAccount_type()) || StringUtils.isBlank(hrmResourceImportParam.getAccount_type())) && "正式,试用,临时,试用延期".contains(Util.null2String(hrmResourceImportParam.getStatus()))) {
                            license.reloadLicenseInfo();
                            if (license.CkHrmnum() >= 0) {
                                resultList.add(createLog(hrmResourceImportParam, "创建", "失败", SystemEnv.getHtmlLabelName(83522, userlanguage)));
                                continue;
                            }
                        }
                        // 分部Id
                        String subCompanyNames = hrmResourceImportParam.getCompany_id() + "";
                        String tempSubCompanyName = "";
                        if (subCompanyNames != null) {
                            if (!subCompanyNames.equals(subCompanyName)) {
                                tempSubCompanyName = subCompanyName;
                                subCompanyName = subCompanyNames;
                                companyId = getSubCompanyId(subCompanyName);
                            }
                            if (companyId == -9) {
                                resultList.add(createLog(hrmResourceImportParam, "创建", "失败", SystemEnv.getErrorMsgName(56, userlanguage)));
                                continue;
                            }
                            if (companyId == -2) {
                                resultList.add(createLog(hrmResourceImportParam, "创建", "失败", SystemEnv.getHtmlLabelName(126274, userlanguage)));
                                continue;
                            }
                            if (companyId == -1) {
                                resultList.add(createLog(hrmResourceImportParam, "创建", "失败", SystemEnv.getHtmlLabelName(83524, userlanguage)));
                                continue;
                            }
                            if (StringUtil.parseToInt(license.getConcurrentFlag(), 0) != 1) {
                                if (new HrmResourceManager().noMore(String.valueOf(companyId))) {
                                    resultList.add(createLog(hrmResourceImportParam, "创建", "失败", SystemEnv.getHtmlLabelName(83525, userlanguage)));
                                    continue;
                                }
                            }
                            companyId = 0 == companyId ? null : companyId;
                            hrmResourcePO.setCompanyId(companyId);
                        } else {
                            resultList.add(createLog(hrmResourceImportParam, "创建", "失败", SystemEnv.getHtmlLabelName(83526, userlanguage)));
                            continue;
                        }

                        // 部门id
                        String departmentNames = hrmResourceImportParam.getDepartment_id();
                        if (departmentNames != null) {
                            if (!subCompanyNames.equals(tempSubCompanyName) || !departmentNames.equals(departmentName)) {
                                departmentName = departmentNames;
                                departmentId = getDeptId(departmentName, companyId);
                            }
                            if (departmentId == -2) {
                                resultList.add(createLog(hrmResourceImportParam, "创建", "失败", SystemEnv.getHtmlLabelName(126275, userlanguage)));
                                continue;
                            }
                            hrmResourcePO.setDepartmentId(departmentId);
                        } else {
                            resultList.add(createLog(hrmResourceImportParam, "创建", "失败", SystemEnv.getHtmlLabelName(83527, userlanguage)));
                            continue;
                        }

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

                        //主账号id-sunjsh
                        if (hrmResourceImportParam.getAccount_type() != null && !"".equals(hrmResourceImportParam.getAccount_type())) {
                            if ("主账号".equals(hrmResourceImportParam.getAccount_type())) {
                                hrmResourcePO.setBelongTo(-1L);
                                hrmResourcePO.setAccountType(0);
                            } else if ("次账号".equals(hrmResourceImportParam.getAccount_type())) {
                                if (hrmResourceImportParam.getBelong_to() != null && !"".equals(hrmResourceImportParam.getBelong_to().trim())) {
                                    long belongTo = getBelongId(hrmResourceImportParam.getBelong_to(), keyField);
                                    hrmResourcePO.setBelongTo(belongTo);
                                    if (!hrmResourceImportParam.getBelong_to().equals("") && belongTo == 0) {
                                        resultList.add(createLog(hrmResourceImportParam, "创建", "失败", SystemEnv.getHtmlLabelName(131279, userlanguage)));
                                        continue;
                                    } else {
                                        hrmResourcePO.setAccountType(1);
                                    }
                                } else {
                                    resultList.add(createLog(hrmResourceImportParam, "创建", "失败", SystemEnv.getHtmlLabelName(131279, userlanguage)));
                                    continue;
                                }
                            } else {
                                hrmResourcePO.setBelongTo(-1L);
                                hrmResourcePO.setAccountType(0);
                            }
                        } else if (hrmResourceImportParam.getBelong_to() != null && !"".equals(hrmResourceImportParam.getBelong_to().trim())) {
                            long belongTo = getBelongId(hrmResourceImportParam.getBelong_to(), keyField);
                            hrmResourcePO.setBelongTo(belongTo);
                            if (!hrmResourceImportParam.getBelong_to().equals("") && belongTo == 0) {
                                resultList.add(createLog(hrmResourceImportParam, "创建", "失败", SystemEnv.getHtmlLabelName(131279, userlanguage)));
                                continue;
                            } else {
                                hrmResourcePO.setAccountType(1);
                            }
                        } else {
                            hrmResourcePO.setBelongTo(-1L);
                            hrmResourcePO.setAccountType(0);
                        }

                        // 岗位id
                        if (hrmResourceImportParam.getJob_title() != null && hrmResourceImportParam.getJob_activity() != null && hrmResourceImportParam.getJob_group_id() != null) {
                            String jobNames = hrmResourceImportParam.getJob_title();
                            hrmResourcePO.setJobTitle(getJobTitles(companyId, departmentId, jobNames));
                        } else {
                            resultList.add(createLog(hrmResourceImportParam, "创建", "失败", SystemEnv.getHtmlLabelName(83531, userlanguage)));
                            continue;
                        }

                        //上级id
                        if (hrmResourceImportParam.getManager_id() != null) {
                            int managerid = getManagerId(hrmResourceImportParam.getManager_id(), keyField);
                            hrmResourcePO.setManagerId(0 == managerid ? null : managerid);
                            //如果vo.getManagerid()有值，但manageid未找到，说明填写有误
                            if (!hrmResourceImportParam.getManager_id().equals("") && managerid == 0) {
                                resultList.add(createLog(hrmResourceImportParam, "创建", "失败", SystemEnv.getHtmlLabelName(83532, userlanguage)));
                                continue;
                            }
                        } else {
                            hrmResourcePO.setManagerId(null);
                        }

                        // 助理id
                        if (hrmResourceImportParam.getAssistant_id() != null) {
                            int assistantId = getAssistantid(hrmResourceImportParam.getAssistant_id(), keyField);
                            hrmResourcePO.setAssistantId(assistantId);
                            if (!hrmResourceImportParam.getAssistant_id().equals("") && assistantId == 0) {
                                resultList.add(createLog(hrmResourceImportParam, "创建", "失败", SystemEnv.getHtmlLabelName(24678, userlanguage)));
                                continue;
                            }
                        }

                        // 办公地点
                        if (hrmResourceImportParam.getLocation_id() != null) {
                            hrmResourcePO.setLocationId(getLocationid(hrmResourceImportParam.getLocation_id()));
                        } else {
                            resultList.add(createLog(hrmResourceImportParam, "创建", "失败", SystemEnv.getHtmlLabelName(83533, userlanguage)));
                            continue;
                        }

                        //邮箱-sunjsh
                        if (hrmResourceImportParam.getEmail() != null) {
                            if (!"".equals(hrmResourceImportParam.getEmail().trim()) && hrmResourceImportParam.getEmail().contains("*")) {
                                hrmResourceImportParam.setEmail(null);
                            } else if ("".equals(hrmResourceImportParam.getEmail().trim())) {
                                hrmResourcePO.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(hrmResourceImportParam.getEmail());
                                if (!matcher.matches()) {
                                    resultList.add(createLog(hrmResourceImportParam, "创建", "失败", SystemEnv.getHtmlLabelName(24570, userlanguage)));
                                    continue;
                                } else {
                                    hrmResourcePO.setEmail(hrmResourceImportParam.getEmail());
                                }
                            }
                        }

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

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

                            String fieldvalue = HrmFieldManager.getReallyFieldvalue(jsonObject);
                            if (!"".equals(fieldvalue)) {
                                hrmResourcePO.setBankId(new Integer(fieldvalue));
                            } else {
                                hrmResourcePO.setBankId(this.getBankId(hrmResourceImportParam.getBank_id()));
                            }
                        }

                        //sunjsh-入职日期
                        if (hrmResourceImportParam.getCompany_start_date() != null && !"".equals(hrmResourceImportParam.getCompany_start_date())) {
                            hrmResourcePO.setCompanyStartDate(hrmResourceImportParam.getCompany_start_date());
                        }

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

                        // 职称
                        if (hrmResourceImportParam.getJob_call() != null) {
                            int jobcall = getJobcall(hrmResourceImportParam.getJob_call());
                            hrmResourcePO.setJobCall(jobcall);
                        }
                        // 系统语言，默认简体中文
                        if (hrmResourceImportParam.getSystem_language() != null) {
                            int systemlanguage = getSystemlanguage(hrmResourceImportParam.getSystem_language());

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

                        // 婚姻状况，如果不是以下选项，则默认为未婚
                        String maritalStatus = "已婚".equals(hrmResourceImportParam.getMarital_status()) ? "1" : "离异".equals(hrmResourceImportParam.getMarital_status()) ? "2" : "0";
                        hrmResourcePO.setMaritalStatus(maritalStatus);

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

                        // 人员密级
                        if (!"".equals(Util.null2String(hrmResourceImportParam.getClassification()))) {
                            int classification = getClassification(hrmResourceImportParam.getClassification());
                            hrmResourcePO.setClassification(classification);
                        }
                        // 学历
                        if (hrmResourceImportParam.getEducation_level() != null) {
                            int educationLevel = getEducationlevel(hrmResourceImportParam.getEducation_level());
                            hrmResourcePO.setEducationLevel(educationLevel);
                        }

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

                        // 健康状况
                        if (hrmResourceImportParam.getHealth_info() != null) {
                            String healthinfo = getHealthinfo(hrmResourceImportParam.getHealth_info());
                            hrmResourcePO.setHealthInfo(healthinfo);
                        } else {
                            hrmResourcePO.setHealthInfo("0");
                        }

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

                        //职级
                        if (isInteger(hrmResourceImportParam.getJob_level())) {
                            // TODO 职级
                            Long jobLevel = hrmResourceImportParam.getJob_level().equals("") ? 0 : Long.parseLong(hrmResourceImportParam.getJob_level());
                            hrmResourcePO.setJobLevel(jobLevel);
                        } else {
                            hrmResourcePO.setJobLevel(0L);
                        }
                        Long jobGroupId = null;
                        if (hrmResourceImportParam.getJob_group_id() != null) {
                            List<PostPO> postPOS = getPostMapper().listByName(hrmResourceImportParam.getJob_group_id());
                            if (CollectionUtils.isNotEmpty(postPOS)) {
                                jobGroupId = postPOS.get(0).getId();
                            } else {
                                PostPO postPO = PostPO.builder()
                                        .postName(hrmResourceImportParam.getJob_group_id())
                                        .creator((long) user.getUID())
                                        .deleteType(0)
                                        .createTime(new Date())
                                        .build();
                                getPostMapper().insertIgnoreNull(postPO);
                                jobGroupId = postPO.getId();
                            }
                            hrmResourcePO.setJobGroupId(jobGroupId);
                        }

                        // 职务
                        if (hrmResourceImportParam.getJob_activity() != null) {
                            if (null == jobGroupId) {
                                resultList.add(createLog(hrmResourceImportParam, "创建", "失败", "职务导入错误，未找到对应职务类别"));
                                continue;
                            }
                            PostInfoPO postInfoPO = getPostInfoMapper().getPostInfoByNameAndPostId(hrmResourceImportParam.getJob_activity(), jobGroupId);
                            if (null == postInfoPO) {
                                postInfoPO = PostInfoPO.builder()
                                        .postInfoNo(hrmResourceImportParam.getJob_activity())
                                        .postInfoName(hrmResourceImportParam.getJob_activity())
                                        .postId(jobGroupId)
                                        .creator((long) user.getUID())
                                        .deleteType(0)
                                        .createTime(new Date())
                                        .build();
                                getPostInfoMapper().insertIgnoreNull(postInfoPO);
                            }
                            hrmResourcePO.setJobActivity(postInfoPO.getId());
                        }

                        //用工性质
                        if (hrmResourceImportParam.getUse_kind() != null) {
                            int useKind = getUseKind(hrmResourceImportParam.getUse_kind());
                            hrmResourcePO.setUseKind(useKind);
                        } else {
                            hrmResourcePO.setUseKind(0);
                        }


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


                        ////id，非自动增长
                        id = getResourceMapper().getMaxId() + 1;
                        hrmResourcePO.setId(id);


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

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

                        String password = encrypts[0];
                        String salt = encrypts[1];
                        hrmResourcePO.setPassWord(password);

                        boolean flag = true;

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

                        String workCode = hrmResourceImportParam.getWork_code();
                        workCode = CodeRuleManager.getCodeRuleManager().generateRuleCode(RuleCodeType.USER, workCode);
                        hrmResourceImportParam.setWork_code(workCode);

                        for (String s : fields) {
                            Field resourcePOClassField = resourcePOClass.getDeclaredField(PageInfoSortUtil.underlineToHump(s));
                            Field paramClassDeclaredField = importParamClass.getDeclaredField(s);

                            String hrmFieldType = resourcePOClassField.getType().getName();
                            String voFieldType = paramClassDeclaredField.getType().getName();

                            resourcePOClassField.setAccessible(true);
                            paramClassDeclaredField.setAccessible(true);

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

                                }
                            }
                        }
                        insertStr = insertStr + insertFields + "creator,delete_type,create_time,update_time) values(" + insertValues + createrid + ",'" + 0 + "','" + date + "','" + date + "')";
                        boolean resourceInsertFlag = true;
                        if (!execSql(insertStr)) {//添加人员信息
                            flag = false;
                            resourceInsertFlag = false;
                        }
                        if (resourceInsertFlag) {// 仅当人员插入成功后才进行自定义字段操作
                            PasswordUtil.updateResourceSalt(id + "", salt);
                            // TODO  更新自定义字段
                            //if (!updateBaseData(hrmResourceImportParam.getBaseFields(), hrmResourceImportParam.getBaseFieldsValue(), id.intValue())) {
                            //    flag = false;
                            //}
                        }

                        /*写日志*/
                        if (flag) {
                            resultList.add(createLog(hrmResourceImportParam, "创建", "成功", ""));
                        } else {
                            resultList.add(createLog(hrmResourceImportParam, "创建", "失败", "系统错误，请联系管理员"));
                        }

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

                        hrmResourceImportParam.setId(Long.parseLong(keyMap.get(key).toString()));//设置id
                        if (this.checkInfo(hrmResourceImportParam, resultList)) {
                            continue;
                        }

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

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

                        //分部id
                        String subCompanyNames = hrmResourceImportParam.getCompany_id();
                        boolean issameSub = true;
                        if (!"".equals(Util.null2String(subCompanyNames))) {
                            if (!subCompanyNames.equals(subCompanyName)) {
                                subCompanyName = subCompanyNames;
                                companyId = getSubCompanyId(subCompanyName);
                                issameSub = false;
                            }
                            if (companyId == -9) {
                                resultList.add(createLog(hrmResourceImportParam, "更新", "失败", SystemEnv.getErrorMsgName(56, userlanguage)));
                                continue;
                            }
                            if (companyId == -2) {
                                resultList.add(createLog(hrmResourceImportParam, "更新", "失败", SystemEnv.getHtmlLabelName(126274, userlanguage)));
                                continue;
                            }
                            if (companyId == 0 || companyId == -1) {
                                resultList.add(createLog(hrmResourceImportParam, "更新", "失败", companyId == 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(companyId))) {
                                    resultList.add(createLog(hrmResourceImportParam, "更新", "失败", SystemEnv.getHtmlLabelName(83525, userlanguage)));
                                    continue;
                                }
                            }
                            companyId = 0 == companyId ? null : companyId;
                            hrmResourcePO.setCompanyId(companyId);
                        }

                        // 部门id
                        String departmentNames = hrmResourceImportParam.getDepartment_id();
                        if (!"".equals(Util.null2String(departmentNames))) {  //部门存在时
                            if (!issameSub || !departmentNames.equals(departmentName)) {
                                departmentName = departmentNames;
                            }
                            departmentId = getDeptId(departmentName, companyId);
                            if (departmentId == 0) {
                                resultList.add(createLog(hrmResourceImportParam, "更新", "失败", SystemEnv.getHtmlLabelName(83537, userlanguage)));
                                continue;
                            }
                            if (departmentId == -2) {
                                resultList.add(createLog(hrmResourceImportParam, "更新", "失败", SystemEnv.getHtmlLabelName(126275, userlanguage)));
                                continue;
                            }
                            hrmResourcePO.setDepartmentId(departmentId);
                        }

                        //主账号id-sunjsh
                        if (hrmResourceImportParam.getAccount_type() != null && !"".equals(hrmResourceImportParam.getAccount_type())) {
                            if ("主账号".equals(hrmResourceImportParam.getAccount_type())) {
                                hrmResourcePO.setBelongTo(-1L);
                                hrmResourcePO.setAccountType(0);
                            } else if ("次账号".equals(hrmResourceImportParam.getAccount_type())) {
                                if (hrmResourceImportParam.getBelong_to() != null && !"".equals(hrmResourceImportParam.getBelong_to().trim())) {
                                    long belongto = getBelongId(hrmResourceImportParam.getBelong_to(), keyField);
                                    hrmResourcePO.setBelongTo(belongto);
                                    if (!hrmResourceImportParam.getBelong_to().equals("") && belongto == 0) {
                                        resultList.add(createLog(hrmResourceImportParam, "更新", "失败", SystemEnv.getHtmlLabelName(131279, userlanguage)));
                                        continue;
                                    } else {
                                        hrmResourcePO.setAccountType(1);
                                    }
                                } else {
                                    resultList.add(createLog(hrmResourceImportParam, "更新", "失败", SystemEnv.getHtmlLabelName(131279, userlanguage)));
                                    continue;
                                }
                            } else {
                                hrmResourcePO.setBelongTo(-1L);
                                hrmResourcePO.setAccountType(0);
                            }
                        } else if (hrmResourceImportParam.getBelong_to() != null && !"".equals(hrmResourceImportParam.getBelong_to().trim())) {
                            long belongto = getBelongId(hrmResourceImportParam.getBelong_to(), keyField);
                            hrmResourcePO.setBelongTo(belongto);
                            if (!hrmResourceImportParam.getBelong_to().equals("") && belongto == 0) {
                                resultList.add(createLog(hrmResourceImportParam, "更新", "失败", SystemEnv.getHtmlLabelName(131279, userlanguage)));
                                continue;
                            } else {
                                hrmResourcePO.setAccountType(1);
                            }
                        }

                        // TODO 岗位id
                        if ("".equals(Util.null2String(hrmResourceImportParam.getJob_title())) && (!"".equals(Util.null2String(hrmResourceImportParam.getJob_activity())) || !"".equals(Util.null2String(hrmResourceImportParam.getJob_group_id())))) {
                            resultList.add(createLog(hrmResourceImportParam, "更新", "失败", SystemEnv.getHtmlLabelName(83544, userlanguage)));
                            continue;
                        }
                        if (!"".equals(Util.null2String(hrmResourceImportParam.getJob_title()))) {
                            String jobNames = hrmResourceImportParam.getJob_title();
                            hrmResourcePO.setJobTitle(getJobTitles(companyId, departmentId, jobNames));
                        }
                        if (Util.getIntValue(hrmId) < 0) continue;


                        // 级序列
                        if (!"".equals(Util.null2String(hrmResourceImportParam.getManager_id()))) {
                            int managerid = getManagerId(hrmResourceImportParam.getManager_id(), keyField);
                            //如果vo.getManagerid()有值，但manageid未找到，说明填写有误
                            if (hrmResourceImportParam.getManager_id() != null && !hrmResourceImportParam.getManager_id().equals("") && managerid == 0) {
                                resultList.add(createLog(hrmResourceImportParam, "更新", "失败", SystemEnv.getHtmlLabelName(83532, userlanguage)));
                                continue;
                            }
                            hrmResourcePO.setManagerId(0 == managerid ? null : managerid);
                        } else {
                            hrmResourcePO.setManagerId(null);
                        }
                        // 助理id
                        if (!"".equals(Util.null2String(hrmResourceImportParam.getAssistant_id()))) {
                            int assistantId;
                            assistantId = getAssistantid(hrmResourceImportParam.getAssistant_id(), keyField);
                            if (hrmResourceImportParam.getAssistant_id() != null && !hrmResourceImportParam.getAssistant_id().equals("") && assistantId == 0) {
                                resultList.add(createLog(hrmResourceImportParam, "更新", "失败", SystemEnv.getHtmlLabelName(24678, userlanguage)));
                                continue;
                            }
                            hrmResourcePO.setAssistantId(assistantId);
                        }
                        // 办公地点
                        if (!"".equals(Util.null2String(hrmResourceImportParam.getLocation_id()))) {
                            int locationid = getLocationid(hrmResourceImportParam.getLocation_id());
                            hrmResourcePO.setLocationId(locationid);
                        }

                        //邮箱-sunjsh
                        if (hrmResourceImportParam.getEmail() != null) {
                            if (!"".equals(hrmResourceImportParam.getEmail().trim()) && hrmResourceImportParam.getEmail().contains("*")) {
                                hrmResourceImportParam.setEmail(null);
                            } else if ("".equals(hrmResourceImportParam.getEmail().trim())) {
                                hrmResourcePO.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(hrmResourceImportParam.getEmail());
                                if (!matcher.matches()) {
                                    resultList.add(createLog(hrmResourceImportParam, "更新", "失败", SystemEnv.getHtmlLabelName(24570, userlanguage)));
                                    continue;
                                } else {
                                    hrmResourcePO.setEmail(hrmResourceImportParam.getEmail());
                                }
                            }
                        }

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

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

                            String fieldvalue = HrmFieldManager.getReallyFieldvalue(jsonObject);
                            if (!"".equals(fieldvalue)) {
                                hrmResourcePO.setBankId(new Integer(fieldvalue));
                            } else {
                                hrmResourcePO.setBankId(this.getBankId(hrmResourceImportParam.getBank_id()));
                            }
                        }

                        //sunjsh-入职日期
                        if (hrmResourceImportParam.getCompany_start_date() != null && !"".equals(hrmResourceImportParam.getCompany_start_date())) {
                            hrmResourcePO.setCompanyStartDate(hrmResourceImportParam.getCompany_start_date());
                        } else {
                            hrmResourceImportParam.setCompany_start_date(null);
                        }

                        //sunjsh-参加工作日期
                        if (hrmResourceImportParam.getWork_start_date() != null && !"".equals(hrmResourceImportParam.getWork_start_date())) {
                            hrmResourcePO.setWorkStartDate(hrmResourceImportParam.getWork_start_date());
                        } else {
                            hrmResourceImportParam.setWork_start_date(null);
                        }
                        // 职称
                        if (!"".equals(Util.null2String(hrmResourceImportParam.getJob_call()))) {
                            hrmResourcePO.setJobCall(getJobcall(hrmResourceImportParam.getJob_call()));
                        }
                        // 系统语言，默认简体中文
                        if (!"".equals(Util.null2String(hrmResourceImportParam.getSystem_language()))) {
                            int systemlanguage = getSystemlanguage(hrmResourceImportParam.getSystem_language());

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

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

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

                        // 员工状态
                        if (!"".equals(Util.null2String(hrmResourceImportParam.getStatus()))) {
                            int status = getStatus(hrmResourceImportParam.getStatus());
                            hrmResourcePO.setStatus(status);
                        } else {
                            hrmResourcePO.setStatus(0);
                        }

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

                        // 学历
                        if (!"".equals(Util.null2String(hrmResourceImportParam.getEducation_level()))) {
                            int educationlevel = getEducationlevel(hrmResourceImportParam.getEducation_level());
                            hrmResourcePO.setEducationLevel(educationlevel);
                        }

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

                        // 健康状况
                        if (!"".equals(Util.null2String(hrmResourceImportParam.getHealth_info()))) {
                            String healthinfo = getHealthinfo(hrmResourceImportParam.getHealth_info());
                            hrmResourcePO.setHealthInfo(healthinfo);
                        }

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

                        //职级
                        if (isInteger(hrmResourceImportParam.getJob_level())) {
                            int joblevel = hrmResourceImportParam.getJob_level().equals("") ? 0 : Integer.parseInt(hrmResourceImportParam.getJob_level());
                            hrmResourcePO.setJobLevel((long) joblevel);
                        }

                        // 职务分类
                        Long jobGroupId = null;
                        if (hrmResourceImportParam.getJob_group_id() != null) {
                            List<PostPO> postPOS = getPostMapper().listByName(hrmResourceImportParam.getJob_group_id());
                            if (CollectionUtils.isNotEmpty(postPOS)) {
                                jobGroupId = postPOS.get(0).getId();
                            } else {
                                PostPO postPO = PostPO.builder()
                                        .postName(hrmResourceImportParam.getJob_group_id())
                                        .creator((long) user.getUID())
                                        .deleteType(0)
                                        .createTime(new Date())
                                        .build();
                                getPostMapper().insertIgnoreNull(postPO);
                                jobGroupId = postPO.getId();
                            }
                            hrmResourcePO.setJobGroupId(jobGroupId);
                        }

                        // 职务
                        if (hrmResourceImportParam.getJob_activity() != null) {
                            if (null == jobGroupId) {
                                resultList.add(createLog(hrmResourceImportParam, "创建", "失败", "职务导入错误，未找到对应职务类别"));
                                continue;
                            }
                            PostInfoPO postInfoPO = getPostInfoMapper().getPostInfoByNameAndPostId(hrmResourceImportParam.getJob_activity(), jobGroupId);
                            if (null == postInfoPO) {
                                postInfoPO = PostInfoPO.builder()
                                        .postInfoNo(hrmResourceImportParam.getJob_activity())
                                        .postInfoName(hrmResourceImportParam.getJob_activity())
                                        .postId(jobGroupId)
                                        .creator((long) user.getUID())
                                        .deleteType(0)
                                        .createTime(new Date())
                                        .build();
                                getPostInfoMapper().insertIgnoreNull(postInfoPO);
                            }
                            hrmResourcePO.setJobActivity(postInfoPO.getId());
                        }

                        //用工性质
                        if (hrmResourceImportParam.getUse_kind() != null) {
                            int usekind = getUseKind(hrmResourceImportParam.getUse_kind());
                            hrmResourcePO.setUseKind(usekind);
                        }

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


                        //密码 加密
                        if (!"".equals(Util.null2String(hrmResourceImportParam.getPass_word()))) {

                            String orgPwd = "1";
                            if (!"".equals(hrmResourceImportParam.getPass_word()))
                                orgPwd = hrmResourceImportParam.getPass_word();
                            String[] pwdArr = PasswordUtil.encrypt(orgPwd);
                            String salt = pwdArr[1];
                            hrmResourcePO.setPassWord(pwdArr[0]);

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

                        }
                        StringBuilder updateStr = new StringBuilder("update jcl_org_hrmresource set ");

                        for (int k = 1; k < fields.length; k++) {
                            Field hrmField = resourcePOClass.getDeclaredField(PageInfoSortUtil.underlineToHump(fields[k]));
                            Field paramClassDeclaredField = importParamClass.getDeclaredField(fields[k]);

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

                            hrmField.setAccessible(true);
                            paramClassDeclaredField.setAccessible(true);

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

                        // TODO
                        updateStr.append(" update_time ='").append(DateUtil.getCurrentDate()).append("'  where id=").append(keyMap.get(key));

                        execSql(updateStr.toString());
                        // TODO  更新自定义字段
                        // updateBaseData(hrmResourceImportParam.getBaseFields(), hrmResourceImportParam.getBaseFieldsValue().trim(), keyMap.get(key));
                    }
                } catch (Exception e) {
                    //数据异常
                    new BaseBean().writeLog(e);
                }
            }
            try {
                HrmTlevelManager.setUpdate();
            } catch (Exception e) {
                new BaseBean().writeLog(e);
            }

            Map<String, Object> params = new HashMap<>();
            params.put("pId", this.pId);
            params.put("status", "over");
            importLogService.saveImportLogStatus(params, user);

        } catch (Exception e) {
            new BaseBean().writeLog(e);
            Map<String, Object> params = new HashMap<>();
            params.put("pId", this.pId);
            params.put("status", "error");
            importLogService.saveImportLogStatus(params, user);
        }
    }

    /**
     * 插入基础自定义字段信息
     *
     * @param baseFild  存储人员自定义数据的字段
     * @param baseValue 自定义数据值
     * @param id        需要添加自定义信息的人员id
     * @return
     */
    public boolean addBaseData(String baseFild, String baseValue, int id) {
        if (baseFild == null || baseFild.equals("")) return true;
        String[] baseValues = baseValue.split(";");
        String[] baseFields = baseFild.split(",");
        String fielddbType;
        String sql = "";
        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++) {
                JSONObject jsonObject = baseTypeMap.get(baseFields[i]);
                fielddbType = jsonObject.getString("fielddbtype");
                jsonObject.put("fieldvalue", baseValues[i]);
                String fieldvalue = HrmFieldManager.getReallyFieldvalue(jsonObject);

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

        //检查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 && encryptFieldEntity.getIsEncrypt().equals("1")) {
                    //是否需要加密
                    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 (!fieldvalue.equals("")) {
                    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) {
            new BaseBean().writeLog(e);
        }
        recordSet.setNoAutoEncrypt(true);
        return (!flag || recordSet.execute(sql));
    }

    /**
     * 根据分部名称获取分部Id，不存在就创建
     *
     * @param subCompanyName 分部名称 eg：泛微广东>泛微深圳
     * @return
     */
    public Long getSubCompanyId(String subCompanyName) {

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

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

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

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

            sql = "select id from jcl_org_comp where ltrim(rtrim(dbo.convToMultiLang(ltrim(rtrim(comp_name))," + userlanguage + ")))='" + companyName.trim() + "' and " + supsubcomidConditon + "=" + parentId;
            if (recordSet.getDBType().equalsIgnoreCase("oracle") || DialectUtil.isMySql(recordSet.getDBType()) || recordSet.getDBType().equalsIgnoreCase("postgresql")) {
                sql = "select id from jcl_org_comp where ltrim(rtrim(convToMultiLang(ltrim(rtrim(comp_name))," + userlanguage + ")))='" + companyName.trim() + "' and " + supsubcomidConditon + "=" + parentId;
            }
            currentidsql = sql + " and (delete_type = 0)";
            currentId = getResultSetId(currentidsql);

            if (parentId == 0 && currentId == 0) {
                recordSet.execute("select COUNT(id) from jcl_org_comp where " + supsubcomidConditon + " = 0  ");
                if (recordSet.next()) {
                    curCount = recordSet.getInt(1);
                }
            }

            //added by wcd 2015-02-06 [限制分部数]
            if (currentId == 0) {
                if (scCount == 0 || curCount < scCount) {
                    // 如果编码为空 自动生成编码
                    String compNo = "";
                    try {
                        compNo = CodeRuleManager.getCodeRuleManager().generateRuleCode(RuleCodeType.SUBCOMPANY, compNo);
                    } catch (Exception e) {
                        new BaseBean().writeLog(e);
                    }
                    CompPO compPO = CompPO.builder()
                            .compNo(compNo)
                            .compName(companyName.trim())
                            .compNameShort(companyName.trim())
                            .parentCompany(0 == parentId ? null : parentId)
                            .creator((long) user.getUID())
                            .deleteType(0)
                            .createTime(new Date())
                            .build();
                    getCompMapper().insertIgnoreNull(compPO);
                    currentId = compPO.getId().intValue();

                } else {
                    currentId = -1;
                }
            }
            parentId = currentId;
        }
        return currentId;
    }

    /**
     * 获取部门id，不存在就创建
     *
     * @param deptNames 部门名称
     * @param companyId 所属分部id
     * @return
     */
    public Long getDeptId(String deptNames, long companyId) {

        String[] deptNameArray = deptNames.split(">");
        long currentId = 0L;
        long parentId = 0L;

        String currentIdSql;
        String sql;

        RecordSet recordSet = new RecordSet();

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

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

            sql = "select id from jcl_org_dept where parent_comp=" + companyId + " and ltrim(rtrim(dbo.convToMultiLang(ltrim(rtrim(dept_name))," + userlanguage + ")))='" + deptName.trim() + "' and " + supdepidConditon + "=" + parentId;
            if (recordSet.getDBType().equalsIgnoreCase("oracle") || DialectUtil.isMySql(recordSet.getDBType()) || recordSet.getDBType().equalsIgnoreCase("postgresql")) {
                sql = "select id from jcl_org_dept where parent_comp=" + companyId + " and ltrim(rtrim(convToMultiLang(ltrim(rtrim(dept_name))," + userlanguage + ")))='" + deptName.trim() + "' and " + supdepidConditon + "=" + parentId;
            }
            currentIdSql = sql + " and delete_type = 0";
            currentId = getResultSetId(currentIdSql);

            if (currentId == 0) {
                // 如果编码为空 自动生成编码
                String deptNo = "";
                try {
                    deptNo = CodeRuleManager.getCodeRuleManager().generateRuleCode(RuleCodeType.DEPARTMENT, deptNo);
                } catch (Exception e) {
                    new BaseBean().writeLog(e);
                }
                DepartmentPO departmentPO = DepartmentPO.builder()
                        .deptNo(deptNo)
                        .deptName(deptName.trim())
                        .deptNameShort(deptName.trim())
                        .parentComp(0 == companyId ? null : companyId)
                        .parentDept(0 == parentId ? null : parentId)
                        .forbiddenTag(0)
                        .creator((long) user.getUID())
                        .deleteType(0)
                        .createTime(new Date())
                        .build();
                getDepartmentMapper().insertIgnoreNull(departmentPO);
                currentId = departmentPO.getId().intValue();
            }
            parentId = currentId;
        }
        return currentId;
    }

    public Long getJobTitles(Long companyId, Long departmentId, String jobNames) {


        String[] jobNameArray = jobNames.split(">");
        long currentId = 0L;
        long parentId = 0L;
        String currentIdSql;
        String sql;
        RecordSet recordSet = new RecordSet();
        String parentJobConditon = DbDialectFactory.get(recordSet.getDBType()).isNull("parent_job", 0);

        for (String jobName : jobNameArray) {
            if (jobName == null || jobName.equals("")) {
                continue;
            }
            sql = "select id from jcl_org_job where parent_comp=" + companyId + " and parent_dept = " + departmentId + " and ltrim(rtrim(dbo.convToMultiLang(ltrim(rtrim(job_name))," + userlanguage + ")))='" + jobName.trim() + "' and " + parentJobConditon + "=" + parentId;
            if (recordSet.getDBType().equalsIgnoreCase("oracle") || DialectUtil.isMySql(recordSet.getDBType()) || recordSet.getDBType().equalsIgnoreCase("postgresql")) {
                sql = "select id from jcl_org_job where parent_comp=" + companyId + " and parent_dept = " + departmentId + " and ltrim(rtrim(convToMultiLang(ltrim(rtrim(job_name))," + userlanguage + ")))='" + jobName.trim() + "' and " + parentJobConditon + "=" + parentId;
            }
            currentIdSql = sql + " and delete_type = 0";
            currentId = getResultSetId(currentIdSql);

            if (currentId == 0) {
                // 如果编码为空 自动生成编码
                String jobNo = "";
                try {
                    jobNo = CodeRuleManager.getCodeRuleManager().generateRuleCode(RuleCodeType.JOBTITLES, jobNo);
                } catch (Exception e) {
                    new BaseBean().writeLog(e);
                }
                JobPO jobPO = JobPO.builder()
                        .jobNo(jobNo)
                        .jobName(jobName)
                        .parentComp(0 == companyId ? null : companyId)
                        .parentDept(0 == departmentId ? null : departmentId)
                        .parentJob(0 == parentId ? null : parentId)
                        .forbiddenTag(0)
                        .creator((long) user.getUID())
                        .deleteType(0)
                        .createTime(new Date())
                        .build();
                getJobMapper().insertIgnoreNull(jobPO);
                currentId = jobPO.getId();
            }
            parentId = currentId;
        }
        return currentId;
    }


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

        String statusOfExcel = importParam.getStatus();
        String loginidOfExcel = importParam.getLogin_id();
        String accouttypeOfExcel = importParam.getAccount_type();

        // 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 int getManagerId(String keyFieldValue, String keyField) {

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

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

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

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

    /**
     * 办公地点id
     *
     * @param locationname 办公地点名称
     * @return
     */
    public int getLocationid(String locationname) {
        int locationid = 0;
        if (!locationname.equals("")) {
            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 (!usekindname.equals("")) {
            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 (!jobcall.equals("")) {
            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;  //系统语言默认为中文


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

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

    /**
     * 工资银行id
     *
     * @param bank1 办公地点名称
     * @return
     */
    public int getBankId(String bank1) {
        int id = 0;
        if (!bank1.equals("")) {
            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 = 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;
    }

    /**
     * 获取人员密级
     *
     * @return
     */
    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 (!educationlevel.equals("")) {
            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) {
        // TODO
        RecordSet recordSet = new RecordSet();
        String sql = "select  id, account_type, certificate_num, login_id, work_code,  ltrim(rtrim(convToMultiLang(ltrim(rtrim(" + keyField + "))," + userlanguage + "))) as " + keyField + " from jcl_org_hrmresource";
        if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) {
            sql = "select  id, account_type, certificate_num, login_id, work_code,  ltrim(rtrim(dbo.convToMultiLang(ltrim(rtrim(" + keyField + "))," + userlanguage + "))) as " + keyField + " from jcl_org_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("certificate_num");
            keyMap.put(recordSet.getString(keyField), recordSet.getInt("id"));
            // TODO
            String accounttype = recordSet.getString("account_type");
            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 importParam HrmResourceVo  人员信息对象
     * @param operation   操作类型  验证|创建|更新
     * @param status      状态 成功|失败
     * @param reason      失败原因
     * @return ImportLog对象
     */
    public ImportLog createLog(HrmResourceImportParam importParam, String operation, String status, String reason) {
        ImportLog log = new ImportLog();

        log.setWorkCode(importParam.getWork_code());  //编号
        log.setLastname(importParam.getLast_name());  //用户名
        log.setLoginid(importParam.getLogin_id());    //登录名
        log.setOperation(operation);        //操作类型
        if (importParam.getCompany_id() != null && importParam.getDepartment_id() != null)
            log.setDepartment(importParam.getCompany_id() + ">" + importParam.getDepartment_id()); //分部部门
        else log.setDepartment("");
        log.setStatus(status);              //状态，成功、失败
        log.setReason(reason);              //原因

        try {
            ImportLogService importLogService = ServiceUtil.getService(ImportLogServiceImpl.class, user);
            String relatedName = "";
            switch (this.keyField) {
                case "work_code":
                    relatedName = log.getWorkCode();
                    break;
                case "login_id":
                    relatedName = log.getLoginid();
                    break;
                case "last_name":
                    relatedName = log.getLastname();
                    break;
            }

            Map<String, Object> params = new HashMap<>();
            params.put("pId", this.pId);
            params.put("lineNum", this.rowNum + 2);//修正偏移量错误
            params.put("relatedName", relatedName);
            params.put("msg", log.getStatus().equals("成功") ? relatedName + "导入成功！" : log.getReason());
            params.put("status", log.getStatus().equals("成功") ? "1" : "0");
            importLogService.saveImportDeitalLog(params, user);
        } catch (Exception e) {
            new BaseBean().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(HrmResourceImportParam importParam, List<ImportLog> resultList) {
        //新增账号、工号唯一性校验
        for (String key : checkKeys) {
            Map<String, String> checkInfo = checkInfos.get(key);
            if (checkInfo != null && !checkInfo.isEmpty()) {
                String val = "";
                String errorMsg = "";
                switch (key) {
                    case "login_id":
                        val = Util.null2String(importParam.getLogin_id()).trim();
                        errorMsg = SystemEnv.getHtmlLabelName(522076, userlanguage);
                        break;
                    case "work_code":
                        val = Util.null2String(importParam.getWork_code()).trim();
                        errorMsg = SystemEnv.getHtmlLabelName(520197, userlanguage);
                        break;
                    case "certificate_num":
                        val = Util.null2String(importParam.getCertificate_num()).trim();
                        errorMsg = SystemEnv.getHtmlLabelName(83521, userlanguage);
                        break;
                }
                int reosurceid = Util.getIntValue(checkInfo.get(val));
                if (importParam.getId() != null && importParam.getId() == reosurceid) {
                    //如果是当前记录，不需要校验
                    continue;
                }

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

}
