package weaver.interfaces.htsc.hrm;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.PasswordUtil;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.interfaces.htsc.comInfo.PropBean;

import java.util.HashMap;
import java.util.Map;

public class OrganizationSynHrm {

    /***
     *
     * @param url
     */
    public Map<String,String> doHrmSyn(String url,Map<String,String> headMap)
    {
        BaseBean bb = new BaseBean();
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();
        OrganizationSynUtil organizationSynUtil = new OrganizationSynUtil();

        int updatesuccesscount = 0;
        int updateerrorcount = 0;
        int insertsuccesscount = 0;
        int inserterrorcount = 0;
        int exceptioncount = 0;
        int dataerrorcount = 0;
        int allcount = 0;
        int updatedefinesuccesscount = 0;
        int updatedefineerrorcount = 0;
        int insertdefinesuccesscount = 0;
        int insertdefineerrorcount = 0;
        int dataiderroecount = 0;

//        try{
//            SimpleDateFormat dsdf = new SimpleDateFormat("yyyyMMdd");
//            String nowdate = dsdf.format(new Date());
//            String cou = "";
//            String tabsql = "select count(*) as cou from user_tables where table_name =upper('hrmresource_bak"+nowdate+"')";
//            rs.execute(tabsql);
//            if(rs.next()){
//                cou = Util.null2String(rs.getString("cou"));
//            }
//            if("0".equals(cou))
//            {
//                String tablesql = " create table hrmresource_bak"+nowdate+" as select * from hrmresource ";
//                rs.execute(tablesql);
//            }
//        }catch (Exception e){
//
//        }

        Map<String,String> map = new HashMap<String,String>();
        String HT0001 = pb.getPropName("HT0001");
        String subcompanyid1 = organizationSynUtil.getSubcomIdByCode(HT0001);

        int page = 0;
        int pageSize = 300;

        boolean hasNextPage = true;
        while(hasNextPage)
        {
            String response = "" ;
            try{
                String urlnew = url+"?page="+page+"&size="+pageSize;
                bb.writeLog("page:"+page+" size:"+pageSize);
                response = organizationSynUtil.sendPost(urlnew,"",headMap);
            }catch (Exception e){
                bb.writeLog("OrganizationSyn-e:"+e);
            }

            if(response !="" && !"".equals(response))
            {
                try{
                    JSONArray userArray = JSONArray.parseArray(response);
                    bb.writeLog("page:"+page+"  userArray:"+userArray.size());
                    allcount = allcount + userArray.size() ;
                    for(int i=0;i<userArray.size();i++)
                    {
                        JSONObject userJson = userArray.getJSONObject(i);
                        String empCode = Util.null2String(userJson.getString("empCode"));//员工编号
                        try{
                            String empName = Util.null2String(userJson.getString("empName"));//员工姓名
                            String empGender = Util.null2String(userJson.getString("empGender"));//员工性别
                            if("女".equals(empGender)){
                                empGender = "1";
                            }else{
                                empGender = "0";
                            }
                            String field1 = "";//微信大头像
                            String field2 = "";//微信小头像
                            String field0 = Util.null2String(userJson.getString("city"));//工作城市
                            String field8 = Util.null2String(userJson.getString("empEngName"));//员工英文名

                            String creator = Util.null2String(userJson.getString("creator"));//创建者工号
                            creator = organizationSynUtil.getUserIdByCode(creator);  //主账号
                            if("".equals(creator)){
                                creator = "1";
                            }

                            String accentEmail = Util.null2String(userJson.getString("accentEmail"));//主要邮箱
                            String accentMobile = Util.null2String(userJson.getString("accentMobile"));//主要手机
                            String accentPhone = Util.null2String(userJson.getString("accentPhone"));//主要座机

                            String field3 = Util.null2String(userJson.getString("empEmails"));//员工EMAIL
                            if(!"".equals(field3)){
                                field3 = field3.replace("[","").replace("]","").replace("\"","");
                            }

                            String field4 = Util.null2String(userJson.getString("empMobiles"));//员工手机号
                            if(!"".equals(field4)){
                                field4 = field4.replace("[","").replace("]","").replace("\"","");
                            }

                            String field5 = Util.null2String(userJson.getString("empPhones"));//员工固话
                            if(!"".equals(field5)){
                                field5 = field5.replace("[","").replace("]","").replace("\"","");
                            }

                            String userState = Util.null2String(userJson.getString("userState"));//用户状态
                            int empSortNum = (0- Util.getIntValue(userJson.getString("empSortNum"),0));//员工排序号
                            String field6 =  Util.null2String(userJson.getString("state"));//是否是外部联系人
                            String field7 =  Util.null2String(userJson.getString("comment"));//备注

                            String field9 = Util.null2String(userJson.getString("empJobGrade"));//员工职级
                            String field11 = Util.null2String(userJson.getString("empRealWorkCity"));//员工职级

                            String currentDate = TimeUtil.getCurrentDateString();//当前日期
                            String deptId = "";
                            String jobTitleId = "";
                            String textfield2 = "" ;
                            //同步主岗数据
                            JSONObject primaryPosition = userJson.getJSONObject("primaryPosition");//主岗信息
                            String empPositionNum = "" ;
                            if(primaryPosition!=null)
                            {
                                organizationSynUtil.doJobTitleSyn(primaryPosition);
                                String deptCode = primaryPosition.getString("deptCode");
                                empPositionNum = primaryPosition.getString("empPositionNum");
                                if(!"".equals(deptCode))
                                {
                                    deptId = organizationSynUtil.getDeptIdByCode(deptCode);
                                }
                                String positionCode = primaryPosition.getString("positionCode");
                                if(!"".equals(deptId) && !"".equals(positionCode)){
                                    jobTitleId = organizationSynUtil.getJobTitleIdByCode(positionCode,deptId);
                                }
                                textfield2 = deptCode+";"+positionCode+";"+empCode;
                            }

                            if("ACTIVE".equalsIgnoreCase(userState)){
                                userState = "1";
                            }else{
                                userState = "5";
                            }

                            int intresourceNum = 0;
                            try{
                                if(!"".equals(empPositionNum) && !"null".equals(empPositionNum) && empPositionNum !=null){
                                    intresourceNum = Integer.parseInt(empPositionNum);
                                }else{
                                    intresourceNum = -1;
                                }
                            }catch (Exception e){
                                bb.writeLog("OrganizationSyn-e:"+e);
                                intresourceNum = -2;
                            }

                            bb.writeLog("textfield2:"+textfield2+" & intresourceNum:"+intresourceNum+"&userState:"+userState);
                            if(intresourceNum >0)
                            {
                                if(!"".equals(deptId) && !"".equals(jobTitleId))
                                {
                                    String userIdNum = organizationSynUtil.getUserIdByIntresourceNum(intresourceNum+"");
                                    String userId = organizationSynUtil.getUserIdByCode(empCode);  //主账号
                                    if(!"".equals(userId))
                                    {
                                        //人员已存在，更新操作
                                        String userUpdateSql1 = " update hrmresource set lastname='"+empName+"',departmentid='"+deptId+"',subcompanyid1='"+subcompanyid1+"',sex='"+empGender+"'," +
                                                                " creater='"+creator+"',email='"+accentEmail+"',mobile='"+accentMobile+"',telephone='"+accentPhone+"',jobtitle='"+jobTitleId+"',status='"+userState+"',dsporder='"+empSortNum+"',lastmoddate='"+currentDate+"',modified=systimestamp,textfield2='"+textfield2+"',belongto=null,accounttype=0,loginid='"+empCode+"',workcode='"+empCode+"',textfield3='"+intresourceNum+"' where id = '"+userId+"' ";
                                        boolean flag = rs.executeUpdate(userUpdateSql1);

                                        bb.writeLog("update & empCode:"+empCode+" & flag:"+flag);
                                        if(flag)
                                        {
                                            try{
                                                int cusFielddataId = organizationSynUtil.getCusFielddataId(userId+"",1);
                                                if(cusFielddataId > 0){
                                                    String userUpdateSql2 = " update cus_fielddata set field0=?,field1=?,field2=?,field3=?,field4=?," +
                                                                            " field5=?,field6=?,field7=?,field8=?,field9=?,field11=? where scope='HrmCustomFieldByInfoType' and scopeid=1 and id=?";
                                                    rs.executeUpdate(userUpdateSql2,new Object[]{field0,field1,field2,field3,field4,field5,field6,field7,field8,field9,field11,userId});
                                                }else{
                                                    String userInsertSql2 = " insert into cus_fielddata(scope,scopeid,id,field0,field1,field2,field3," +
                                                            " field4,field5,field6,field7,field8,field9,field11) values('HrmCustomFieldByInfoType',1,?,?,?,?,?,?,?,?,?,?,?,?)";
                                                    rs.executeUpdate(userInsertSql2,new Object[]{userId,field0,field1,field2,field3,field4,field5,field6,field7,field8,field9,field11});
                                                }
                                            }catch (Exception e){
                                                bb.writeLog("OrganizationSyn-e:"+e);
                                            }
                                            updatesuccesscount++;

                                        }else{
                                            updateerrorcount++;
                                        }

                                        if(!userIdNum.equals(userId)){
                                            dataiderroecount++;

                                            if("1".equalsIgnoreCase(userState)){
                                                bb.writeLog("dataiderroecountACTIVE--empCode:"+empCode+" deptId:"+deptId+" jobTitleId:"+jobTitleId);
                                            }else{
                                                bb.writeLog("dataiderroecountDELETE--empCode:"+empCode+" deptId:"+deptId+" jobTitleId:"+jobTitleId);
                                            }
                                        }
                                    }else{
                                        //人员不存在，插入操作

                                        String dynapass = Util.null2String(pb.getPropName( "PASSWORD"),"Ht123456!");
                                        String[] pwdArr = PasswordUtil.encrypt(dynapass);
                                        String newPWD= pwdArr[0];

                                        rs.executeProc("HrmResourceMaxId_Get","");
                                        rs.next();
                                        userId = rs.getInt(1)+"";

                                        String userInsertSql1 = " insert into hrmresource(id,loginid,password,workcode,lastname,departmentid,subcompanyid1,sex," +
                                                                " creater,email,mobile,telephone,jobtitle,status,dsporder,systemlanguage,createdate,lastmoddate," +
                                                                " created,modified,textfield2,belongto,accounttype,textfield3) " +
                                                                " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,systimestamp,systimestamp,?,?,?,?)";

                                        boolean flag = rs.executeUpdate(userInsertSql1,new Object[]{userId,empCode,newPWD,empCode,empName,deptId,subcompanyid1,empGender,
                                                                        creator,accentEmail,accentMobile,accentPhone,jobTitleId,userState,empSortNum,7,currentDate,currentDate,textfield2,"null","0",intresourceNum});

                                        bb.writeLog("insert & empCode:"+empCode+" & flag:"+flag);
                                        if(flag)
                                        {
                                            insertsuccesscount++;
                                            try{
                                                String sql = " update hrmresource set id="+intresourceNum+" where id="+userId ;
                                                boolean isup = rs.executeUpdate(sql);
                                                if(isup)
                                                {
                                                    int cusFielddataId = organizationSynUtil.getCusFielddataId(intresourceNum+"",1);
                                                    if(cusFielddataId>0){
                                                        String userUpdateSql2 = " update cus_fielddata set field0=?,field1=?,field2=?,field3=?,field4=?," +
                                                                                " field5=?,field6=?,field7=?,field8=?,field9=?,field11=? where scope='HrmCustomFieldByInfoType' and scopeid=1 and id=?";
                                                        bb.writeLog(userUpdateSql2);
                                                        boolean isok = rs.executeUpdate(userUpdateSql2,new Object[]{field0,field1,field2,field3,field4,field5,field6,field7,field8,field9,field11,intresourceNum});
                                                        if(isok){
                                                            updatedefinesuccesscount++;
                                                        }else{
                                                            updatedefineerrorcount++;
                                                        }
                                                    }else{
                                                        String userInsertSql2 = " insert into cus_fielddata(scope,scopeid,id,field0,field1,field2,field3," +
                                                                                " field4,field5,field6,field7,field8,field9,field11) values('HrmCustomFieldByInfoType',1,?,?,?,?,?,?,?,?,?,?,?,?)";
                                                        boolean isok = rs.executeUpdate(userInsertSql2,new Object[]{intresourceNum,field0,field1,field2,field3,field4,field5,field6,field7,field8,field9,field11});

                                                        if(isok){
                                                            insertdefinesuccesscount++;
                                                        }else{
                                                            insertdefineerrorcount++;
                                                        }
                                                    }
                                                }
                                            }catch (Exception e){
                                                bb.writeLog("OrganizationSyn-e:"+e);
                                                bb.writeLog("dataiderrorcount--empCode:"+empCode+" deptId:"+deptId+" jobTitleId:"+jobTitleId);
                                            }
                                        }else{
                                            inserterrorcount++;
                                        }
                                    }

                                    if("1".equalsIgnoreCase(userState))
                                    {
                                        String photo = Util.null2String(userJson.getString("photo"));
                                        organizationSynUtil.synHrmPhoto(empCode,photo,userId);
                                    }

                                }else{
                                    if("1".equalsIgnoreCase(userState)){
                                        bb.writeLog("dataerrorcountACTIVE--empCode:"+empCode+" deptId:"+deptId+" jobTitleId:"+jobTitleId);
                                    }else{
                                        bb.writeLog("dataerrorcountDELETE--empCode:"+empCode+" deptId:"+deptId+" jobTitleId:"+jobTitleId);
                                    }
                                    dataerrorcount++;
                                }
                            }else{
                                if("1".equalsIgnoreCase(userState)){
                                    bb.writeLog("dataerrorcountACTIVE--empCode:"+empCode+" intresourceNum:"+empPositionNum);
                                }else{
                                    bb.writeLog("dataerrorcountDELETE--empCode:"+empCode+" intresourceNum:"+empPositionNum);
                                }
                                dataerrorcount++;
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                            bb.writeLog("OrganizationSyn-e:"+e);
                            rs.writeLog("人员编号"+empCode+"的数据同步失败，data:"+userJson.toJSONString());
                            exceptioncount ++ ;
                        }
                    }
                    if(userArray.size()<pageSize)
                    {
                        hasNextPage = false;
                        bb.writeLog("hasNextPage:"+hasNextPage);
                    }
                }catch (Exception e){
                    bb.writeLog("OrganizationSyn-e:"+e);
                }
                page++;
            }else{
                bb.writeLog("777777777777777");
                hasNextPage = false;
            }
        }

        bb.writeLog("##################allcount:"+allcount);
        map.put("updatesuccesscount",updatesuccesscount+"");
        map.put("updateerrorcount",updateerrorcount+"");
        map.put("insertsuccesscount",insertsuccesscount+"");
        map.put("inserterrorcount",inserterrorcount+"");
        map.put("exceptioncount",exceptioncount+"");
        map.put("dataerrorcount",dataerrorcount+"");
        map.put("dataiderroecount",dataiderroecount+"");

        map.put("updatedefinesuccesscount",updatedefinesuccesscount+"");
        map.put("updatedefineerrorcount",updatedefineerrorcount+"");
        map.put("insertdefinesuccesscount",insertdefinesuccesscount+"");
        map.put("insertdefineerrorcount",insertdefineerrorcount+"");

        map.put("allcount",allcount+"");
        return map;
    }



    /***
     * 同步岗位数据及此账号
     */
    public Map<String,String> doPositionSyn(String url,Map<String,String> headMap)
    {
        Map<String,String> map = new HashMap<String,String>();

        OrganizationSynUtil organizationSynUtil = new OrganizationSynUtil();
        BaseBean bb = new BaseBean();
        bb.writeLog("------doPositionSyn-------");
        int updatesuccesscount = 0;
        int updateerrorcount = 0;
        int insertsuccesscount = 0;
        int inserterrorcount = 0;
        int exceptioncount = 0;
        int dataerrorcount = 0;
        int allcount = 0;
        int updatedefinesuccesscount = 0;
        int updatedefineerrorcount = 0;
        int insertdefinesuccesscount = 0;
        int insertdefineerrorcount = 0;

        int nullcount = 0;
        try{
            int page = 0;
            int pageSize = 300;
            boolean hasNextPage = true;
            while (hasNextPage) {
                try{
                    String urlnew = url+"?page=" + page + "&size=" + pageSize;
                    bb.writeLog("page:"+page+" size:"+pageSize);
                    String response = organizationSynUtil.sendPost(urlnew, "", headMap);
                    JSONArray positionArray = JSONArray.parseArray(response);
                    allcount = allcount + positionArray.size();

                    for (int i = 0; i < positionArray.size(); i++)
                    {
                        try{
                            JSONObject positionJson = positionArray.getJSONObject(i);
                            String positionType = Util.null2String(positionJson.get("positionType"));
                            organizationSynUtil.doJobTitleSyn(positionJson);
                            if("0".equals(positionType))
                            {
                                //住账号的岗位数据同步
                                int count = doMainAccountSynTime(positionJson);
                                if(count == 1){
                                    updatesuccesscount++;
                                }else if(count == -1){
                                    updateerrorcount++;
                                }else if(count == -3){
                                    dataerrorcount++;
                                }else if(count == -2){
                                    exceptioncount++;
                                }
                            }else{
                                allcount++;
                                //次账号的岗位数据同步
                                int count = doSecAccountSynTime(positionJson);
                                if(count == -10){
                                    updateerrorcount++;
                                }else if(count == -11){
                                    inserterrorcount++;
                                }else if(count == -3){
                                    dataerrorcount++;
                                }else if(count == -2){
                                    exceptioncount++;
                                }else if(count == -100){
                                    nullcount++;
                                }else if(count == -12){
                                    updatedefinesuccesscount++;
                                    updatesuccesscount++;
                                }else if(count == -13){
                                    updatedefineerrorcount++;
                                    updateerrorcount++;
                                }else if(count == -14){
                                    insertdefinesuccesscount++;
                                    insertsuccesscount++;
                                }else if(count == -15){
                                    insertdefineerrorcount++;
                                    inserterrorcount++;
                                }
                            }
                        }catch (Exception e){
                            bb.writeLog("OrganizationSyn-e:"+e);
                        }
                    }
                    if (positionArray.size() < pageSize) {
                        hasNextPage = false;
                    }
                }catch (Exception e){
                    bb.writeLog("OrganizationSyn-e:"+e);
                    hasNextPage = false;
                }
                page++;
            }
            bb.writeLog("###############allcount:"+allcount);
        }catch (Exception e){
            bb.writeLog("OrganizationSyn-e:"+e);
        }

        map.put("updatesuccesscount",updatesuccesscount+"");
        map.put("updateerrorcount",updateerrorcount+"");
        map.put("insertsuccesscount",insertsuccesscount+"");
        map.put("inserterrorcount",inserterrorcount+"");
        map.put("exceptioncount",exceptioncount+"");
        map.put("dataerrorcount",dataerrorcount+"");
        map.put("updatedefinesuccesscount",updatedefinesuccesscount+"");
        map.put("updatedefineerrorcount",updatedefineerrorcount+"");
        map.put("insertdefinesuccesscount",insertdefinesuccesscount+"");
        map.put("insertdefineerrorcount",insertdefineerrorcount+"");
        map.put("nullcount",nullcount+"");

        return map;
    }


    /****
     *
     * @param url
     * @return
     */
    public Map<String,String> doAbsPositionSyn(String url,Map<String,String> headMap)
    {
        Map<String,String> map = new HashMap<String,String>();
        BaseBean bb = new BaseBean();
        OrganizationSynUtil organizationSynUtil = new OrganizationSynUtil();
        bb.writeLog("------doAbsPositionSyn-------");

        int updatesuccesscount = 0;
        int updateerrorcount = 0;
        int insertsuccesscount = 0;
        int inserterrorcount = 0;
        int exceptioncount = 0;
        int dataerrorcount = 0;
        int nullcount = 0;

        int updatedefinesuccesscount = 0;
        int updatedefineerrorcount = 0;
        int insertdefinesuccesscount = 0;
        int insertdefineerrorcount = 0;

        int databelongtoerrorcount = 0;
        int dataiderrorcount = 0;

        try{
            String response = organizationSynUtil.sendPost(url, "", headMap);
            JSONArray positionArray = JSONArray.parseArray(response);
            for (int i = 0; i < positionArray.size(); i++)
            {
                try{
                    JSONObject positionJson = positionArray.getJSONObject(i);
                    String positionType = Util.null2String(positionJson.get("positionType"));
                    organizationSynUtil.doJobTitleSyn(positionJson);

                    if("0".equals(positionType))
                    {
                        //住账号的岗位数据同步
                        int count = doMainAccountSynTime(positionJson);
                        if(count == 1){
                            updatesuccesscount++;
                        }else if(count == -1){
                            updateerrorcount++;
                        }else if(count == -3){
                            dataerrorcount++;
                        }else if(count == -2){
                            exceptioncount++;
                        }
                    }else{
                        //次账号的岗位数据同步
                        int count = doSecAccountSynTime(positionJson);
                        if(count == -10){
                            updateerrorcount++;
                        }else if(count == -11){
                            inserterrorcount++;
                        }else if(count == -3){
                            dataerrorcount++;
                        }else if(count == -2){
                            exceptioncount++;
                        }else if(count == -100){
                            nullcount++;
                        }else if(count == -12){
                            updatedefinesuccesscount++;
                            updatesuccesscount++;
                        }else if(count == -13){
                            updatedefineerrorcount++;
                            updateerrorcount++;
                        }else if(count == -14){
                            insertdefinesuccesscount++;
                            insertsuccesscount++;
                        }else if(count == -15){
                            insertdefineerrorcount++;
                            inserterrorcount++;
                        }else if(count == -20){
                            databelongtoerrorcount++;
                        }else if(count == -20){
                            dataiderrorcount++;
                        }
                    }
                }catch (Exception e){

                    bb.writeLog("OrganizationSyn-e:"+e);
                }
            }
        }catch (Exception e){

            bb.writeLog("OrganizationSyn-e:"+e);
        }

        map.put("updatesuccesscount",updatesuccesscount+"");
        map.put("updateerrorcount",updateerrorcount+"");
        map.put("insertsuccesscount",insertsuccesscount+"");
        map.put("inserterrorcount",inserterrorcount+"");
        map.put("exceptioncount",exceptioncount+"");
        map.put("dataerrorcount",dataerrorcount+"");
        map.put("updatedefinesuccesscount",updatedefinesuccesscount+"");
        map.put("updatedefineerrorcount",updatedefineerrorcount+"");
        map.put("insertdefinesuccesscount",insertdefinesuccesscount+"");
        map.put("insertdefineerrorcount",insertdefineerrorcount+"");

        map.put("databelongtoerrorcount",databelongtoerrorcount+"");
        map.put("dataiderrorcount",dataiderrorcount+"");
        map.put("nullcount",nullcount+"");

        return map;
    }


    /**
     *
     * @param userJson
     */
    public int doMainAccountSynTime(JSONObject userJson)
    {
        int count = 0;
        BaseBean bb = new BaseBean();
        PropBean pb = new PropBean();
        OrganizationSynUtil organizationSynUtil = new OrganizationSynUtil();
        RecordSet rs = new RecordSet();
        String HT0001 = pb.getPropName("HT0001");

        try{
            String subcompanyid1 = organizationSynUtil.getSubcomIdByCode(HT0001);

            if(userJson !=null)
            {
                String empCode = Util.null2String(userJson.getString("empCode"));//员工编号
                String positionCode = Util.null2String(userJson.getString("positionCode"));//员工编号
                String deptCode = Util.null2String(userJson.getString("deptCode"));//员工编号
                String strsafeLevel = Util.null2String(userJson.getString("safeLevel"));
                int safeLevel = 0;
                if(!"".equals(strsafeLevel)){
                    safeLevel = Util.getIntValue(strsafeLevel);//安全级别
                }

                String empRealWorkCity = Util.null2String(userJson.getString("empRealWorkCity"));
//                bb.writeLog("empRealWorkCity:"+empRealWorkCity);
                String empPositionNum = "";
                long intresourceNum = 0;
                try{
                    empPositionNum = Util.null2String(userJson.getString("empPositionNum"));
                    if(!"".equals(empPositionNum) && !"null".equals(empPositionNum) && empPositionNum !=null){
                        intresourceNum = Long.parseLong(empPositionNum);
                    }else{
                        intresourceNum = -1;
                    }
                }catch (Exception e){
                    bb.writeLog("OrganizationSyn-e:"+e);
                    intresourceNum = -2;
                }

                if(!"".equals(positionCode) && !"".equals(deptCode))
                {
                    String deptId = organizationSynUtil.getDeptIdByCode(deptCode);
                    String jobTitleId = organizationSynUtil.getJobTitleIdByCode(positionCode,deptId);
                    String jobState = Util.null2String(userJson.getString("jobState"));//员工编号
                    String empJobLevel = Util.null2String(userJson.getString("empJobLevel"));//员工编号
//                    if("ACTIVE".equalsIgnoreCase(jobState))
//                    {
//                        jobState = "1";
//                    }else{
//                        jobState = "5";
//                    }
                    String textfield2 = deptCode+";"+positionCode+";"+empCode;

                    String userId = organizationSynUtil.getUserIdByCode(empCode);
                    bb.writeLog("doMainAccountSynTime & empCode:"+empCode+" deptCode:"+deptCode+" positionCode:"+positionCode+"&strsafeLevel:"+strsafeLevel+"&jobState="+jobState +" userId="+userId+" intresourceNum="+intresourceNum +" empPositionNum="+empPositionNum);
                    if(!"".equals(userId) && userId.equals(intresourceNum+"") && "ACTIVE".equalsIgnoreCase(jobState))
                    {
                        //人员已存在，更新操作
                        String userUpdateSql1 = " update hrmresource set seclevel='"+safeLevel+"' where id="+userId+"";
                        boolean flag = rs.executeUpdate(userUpdateSql1);
                        if(flag)
                        {
                            String userDataSql = " update cus_fielddata set field11='"+empRealWorkCity+"',field12='"+empJobLevel+"' where id in(select id from hrmresource where workcode='"+empCode+"' and status=1) and scopeid=1 and scope='HrmCustomFieldByInfoType'";
                            boolean defflag = rs.executeUpdate(userDataSql);
                            if(defflag){
                                count = 1;
                            }
                        }else{
                            count = -1;
                        }
                    }
                }else
                {
                    count = -3;
                    bb.writeLog("dataerrorcount--empCode:"+empCode);
                }
            }
        }catch (Exception e){
            bb.writeLog("OrganizationSyn-e:"+e);
            count = -2;
        }
        return count;
    }

    /**
     * 次账号同步
     * @param positionJson
     */
    public int doSecAccountSynTime(JSONObject positionJson){
        int count = 0;
        BaseBean bb = new BaseBean();
        PropBean pb = new PropBean();
        OrganizationSynUtil organizationSynUtil = new OrganizationSynUtil();
        String HT0001 = pb.getPropName("HT0001");

        try{
            if(positionJson!=null)
            {
                RecordSet rs = new RecordSet();
                String subcompanyid1 = organizationSynUtil.getSubcomIdByCode(HT0001);
                String uuid = Util.null2String(positionJson.getString("uuid"));
                String empCode = Util.null2String(positionJson.getString("empCode"));
                String empName = Util.null2String(positionJson.getString("empName"));
                String deptCode = Util.null2String(positionJson.getString("deptCode"));
                String positionCode = Util.null2String(positionJson.getString("positionCode"));

                int safeLevel = 0;
                String strsafeLevel = Util.null2String(positionJson.getString("safeLevel"));
                if(!"".equals(strsafeLevel)){
                    safeLevel = Util.getIntValue(positionJson.getString("safeLevel"));//安全级别
                }
                String empPositionNum = Util.null2String(positionJson.getString("empPositionNum"));
                long intresourceNum = 0;
                try{
                    if(!"".equals(empPositionNum) && !"null".equals(empPositionNum) && empPositionNum !=null){
                        intresourceNum = Long.parseLong(empPositionNum);
                    }else{
                        intresourceNum = -1;
                    }
                }catch (Exception e){
                    bb.writeLog("OrganizationSyn-e:"+e);
                    intresourceNum = -2;
                }
                bb.writeLog("doSecAccountSynTime-empCode:"+empCode+" deptCode:"+deptCode+" positionCode:"+positionCode+" strsafeLevel："+strsafeLevel+"& intresourceNum:"+intresourceNum);
                if(intresourceNum >0)
                {
                    if(!"".equals(empCode))
                    {
                        String deptId = organizationSynUtil.getDeptIdByCode(deptCode);
                        if (!"".equals(deptId) && !"".equals(positionCode))
                        {
                            String jobTitleId = organizationSynUtil.getJobTitleIdByCode(positionCode, deptId);
                            String jobState = Util.null2String(positionJson.getString("jobState"));
                            String empJobLevel = Util.null2String(positionJson.getString("empJobLevel"));//员工编号
                            if ("ACTIVE".equalsIgnoreCase(jobState)) {
                                jobState = "1";
                            } else {
                                jobState = "5";
                            }

                            String currentDate = TimeUtil.getCurrentDateString();//当前日期
                            String textfield2 = deptCode + ";" + positionCode + ";" + empCode;

                            String sex = "";
                            String seclevel = safeLevel + "";
                            int dsporder = 0;
                            String password = "";
                            String messagerurl = "";
                            String resourceimageid = "";
                            String email = "";
                            String telephone = "" ;
                            String mobile = "";

                            //查询主账号的信息
                            String mainUserId = "";
                            rs.executeQuery(" select * from hrmresource where workcode='" + empCode + "' and belongto is null ");
                            if (rs.next()) {
                                mainUserId = Util.null2String(rs.getString("id"));
                                sex = Util.null2String(rs.getString("sex"));
                                dsporder = Util.getIntValue(Util.null2String(rs.getString("dsporder")), 0);

                                messagerurl = Util.null2String(rs.getString("messagerurl"));
                                resourceimageid = Util.null2String(rs.getString("resourceimageid"));
                                password = Util.null2String(rs.getString("password"));

                                email = Util.null2String(rs.getString("email"));
                                telephone = Util.null2String(rs.getString("telephone"));
                                mobile = Util.null2String(rs.getString("mobile"));
                            }

                            String field1 = "";//微信大头像
                            String field2 = "";//微信小头像
                            String field0 = "";//工作城市
                            String field3 = ""; //员工EMAIL
                            String field4 = ""; //员工手机号
                            String field5 = ""; //员工固话
                            String field6 = ""; //是否是外部联系人
                            String field7 = "";//备注
                            String field8 = "";//员工英文名
                            String field9 = ""; //员工职级
                            String field11 = "";//真实工作地
                            String field13 = "";//真实工作地
                            if(!"".equals(mainUserId))
                            {
                                rs.executeQuery(" select * from cus_fielddata where scopeid=1 and id= " + mainUserId);
                                if (rs.next()) {
                                    field0 = Util.null2String(rs.getString("field0"));
                                    field3 = Util.null2String(rs.getString("field3"));
                                    field4 = Util.null2String(rs.getString("field4"));
                                    field5 = Util.null2String(rs.getString("field5"));
                                    field6 = Util.null2String(rs.getString("field6"));
                                    field7 = Util.null2String(rs.getString("field7"));
                                    field8 = Util.null2String(rs.getString("field8"));
                                    field9 = Util.null2String(rs.getString("field9"));
                                    field11 = Util.null2String(rs.getString("field11"));
                                    field13 = Util.null2String(rs.getString("field0"));
                                }
                            }
                            String userId = organizationSynUtil.getSecAccountIdByIntresourceNum(intresourceNum+"");
                            String userIdNum = organizationSynUtil.getSecAccountIdByTextfield2(textfield2);
                            bb.writeLog("doSecAccountSynTime-empCode:"+empCode+"userId:"+userId+" --userIdNum:"+userIdNum );
                            if (!"".equals(userId))
                            {
                                if(!"".equals(mainUserId))
                                {
                                    String userUpdateSql =  " update hrmresource set lastname='"+empName+"',departmentid='"+deptId+"',subcompanyid1='"+subcompanyid1+"',sex='"+sex+"'," +
                                                            " jobtitle='"+jobTitleId+"',status='"+jobState+"',lastmoddate='"+currentDate+"',modified=systimestamp,dsporder='"+dsporder+
                                                            "',textfield1='"+uuid+"',textfield2='"+textfield2+"',workcode='"+empCode+
                                                            "',seclevel='"+seclevel+"',messagerurl='"+messagerurl+"',resourceimageid='"+resourceimageid+"',belongto="+mainUserId+
                                                            ",accounttype=1,textfield3='"+intresourceNum+"',email='"+email+"',telephone='"+telephone+"',mobile='"+mobile+"' where id='"+userId+"' ";
                                    boolean flag = rs.executeUpdate(userUpdateSql);
                                    bb.writeLog("update-doSecAccountSynTime-empCode:"+empCode+"----mainUserId:"+mainUserId+"---flag："+flag);
                                    if(flag)
                                    {
                                        if("5".equals(jobState))
                                        {
                                            bb.writeLog("com.api.customization.workflow.biz.ResignAgentBiz().agentOutRequest---userId:"+userId);
                                            new com.api.customization.workflow.biz.ResignAgentBiz().agentOutRequest(Util.getIntValue(userId));
                                        }

                                        int cusFielddataId = organizationSynUtil.getCusFielddataId(intresourceNum+"",1);
                                        if(cusFielddataId>0){
                                            String userUpdateSql2 = " update cus_fielddata set field0=?,field1=?,field2=?,field3=?,field4=?," +
                                                                    " field5=?,field6=?,field7=?,field8=?,field9=?,field11=?,field12=?,field13=? where scope='HrmCustomFieldByInfoType' and scopeid=1 and id=?";
                                            boolean bool = rs.executeUpdate(userUpdateSql2,new Object[]{field0,field1,field2,field3,field4,field5,field6,field7,field8,field9,field11,empJobLevel,field13,intresourceNum});
                                            if(bool){
                                                count = -12;
                                            }else{
                                                count = -13;
                                                bb.writeLog("updatedefineerrorcount--empCode:"+empCode+"--intresourceNum:"+empPositionNum+"--count:"+count);
                                            }
                                        }else{
                                            String userInsertSql2 = " insert into cus_fielddata(scope,scopeid,id,field0,field1,field2,field3," +
                                                                    " field4,field5,field6,field7,field8,field9,field11,field12,field13) values('HrmCustomFieldByInfoType',1,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                                            boolean bool = rs.executeUpdate(userInsertSql2,new Object[]{intresourceNum,field0,field1,field2,field3,field4,field5,field6,field7,field8,field9,field11,empJobLevel,field13});
                                            if(bool){
                                                count = -14;
                                            }else{
                                                count = -15;
                                                bb.writeLog("insertdefineerrorcount--empCode:"+empCode+"--intresourceNum:"+empPositionNum+"--count:"+count);
                                            }
                                        }
                                    }else{
                                        count = -10;
                                        bb.writeLog("updateerrorcount--empCode:"+empCode+" count:"+count);
                                    }
                                }else{
                                    count = -20;
                                    bb.writeLog("databelongtoerrorcount--empCode:"+empCode+" count:"+count);
                                }
                            } else {
                                if(!"".equals(mainUserId))
                                {
                                    rs.executeProc("HrmResourceMaxId_Get", "");
                                    rs.next();
                                    userId = rs.getInt(1) + "";

                                    int num = 0 ;
                                    rs.executeQuery(" select count(1) num from hrmresource where belongto=? ", new Object[]{mainUserId});
                                    if(rs.next()){
                                        num = Util.getIntValue(rs.getString("num"));
                                    }
                                    bb.writeLog("insert-doSecAccountSynTime-empCode:"+empCode+"----num:"+num+"---mainUserId:"+mainUserId+"--intresourceNum:"+intresourceNum);

                                    String loginid = empCode + "czh" + (num+1);

                                    String userInsertSql =  " insert into hrmresource(id,loginid,password,lastname,departmentid,subcompanyid1,sex," +
                                                            " status,systemlanguage,belongto,accounttype,textfield1,createdate,lastmoddate," +
                                                            " created,modified,dsporder,textfield2,workcode,seclevel,messagerurl,resourceimageid,textfield3,email,telephone,mobile) " +
                                                            " values("+userId+",'"+loginid+"','"+password+"','"+empName+"','"+deptId+"','"+subcompanyid1+"','"+sex+
                                                            "','"+jobState+"',7,'"+mainUserId+"',1,'"+uuid+"','"+currentDate+"','"+currentDate+"',systimestamp,systimestamp,'"+
                                                            dsporder+"','"+textfield2+"','"+empCode+"','"+seclevel+"','"+messagerurl+"','"+resourceimageid+"','"+intresourceNum+"','"+email+"','"+telephone+"','"+mobile+"')";
                                    boolean flag = rs.execute(userInsertSql);
                                    if(flag)
                                    {
                                        try{
                                            String sql = " update hrmresource set id="+intresourceNum+" where id="+userId ;
                                            bb.writeLog("sql:"+sql);
                                            rs.execute(sql);
                                        }catch (Exception e){
                                            bb.writeLog("OrganizationSyn-e:"+e);
                                            count = -22;
                                            bb.writeLog("updateiderror--empCode:"+empCode+"--intresourceNum:"+empPositionNum+"--count="+count);

                                        }

                                        int cusFielddataId = organizationSynUtil.getCusFielddataId(intresourceNum+"",1);
                                        if(cusFielddataId>0){
                                            String userUpdateSql2 = " update cus_fielddata set field0=?,field1=?,field2=?,field3=?,field4=?," +
                                                                    " field5=?,field6=?,field7=?,field8=?,field9=?,field11=?,field12=?,field13=? where scope='HrmCustomFieldByInfoType' and scopeid=1 and id=?";
                                            boolean bool = rs.executeUpdate(userUpdateSql2,new Object[]{field0,field1,field2,field3,field4,field5,field6,field7,field8,field9,field11,empJobLevel,field13,intresourceNum});
                                            if(bool){
                                                count = -12;
                                            }else{
                                                count = -13;
                                                bb.writeLog("updatedefineerrorcount--empCode:"+empCode+"--intresourceNum:"+empPositionNum+"--count="+count);
                                            }
                                        }else{
                                            String userInsertSql2 = " insert into cus_fielddata(scope,scopeid,id,field0,field1,field2,field3," +
                                                                    " field4,field5,field6,field7,field8,field9,field11,field12,field13) values('HrmCustomFieldByInfoType',1,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                                            boolean bool = rs.executeUpdate(userInsertSql2,new Object[]{intresourceNum,field0,field1,field2,field3,field4,field5,field6,field7,field8,field9,field11,empJobLevel,field13});
                                            if(bool){
                                                count = -14;
                                            }else{
                                                count = -15;
                                                bb.writeLog("insertdefinesuccesscount--empCode:"+empCode+"--intresourceNum:"+empPositionNum+"--count="+count);
                                            }
                                        }
                                    }else{
                                        count = -11;
                                        bb.writeLog("inserterrorcount--empCode:"+empCode+"--intresourceNum:"+empPositionNum+"--count="+count);
                                    }
                                }else{
                                    count = -20;
                                    bb.writeLog("databelongtoerrorcount--empCode:"+empCode+"--intresourceNum:"+empPositionNum+"--belongto:"+mainUserId+"--count="+count);
                                }
                            }

                            if(!userIdNum.equals(userId)){
                                count = -21;
                                bb.writeLog("doSecAccountSynTime--dataiderrorcount--empCode:"+empCode+"--deptId:"+deptId+" positionCode:"+positionCode+"&count="+count+"--intresourceNum"+empPositionNum+"---userIdNum:"+userIdNum+"--userid:"+userId);
                            }
                        }else{
                            count = -3;
                            bb.writeLog("doSecAccountSynTime--dataerrorcount--empCode:"+empCode+"--deptId:"+deptId+" positionCode:"+positionCode+"&count="+count+"--intresourceNum"+empPositionNum);
                        }
                    }else{
                        count = -3;
                        bb.writeLog("doSecAccountSynTime--dataerrorcount--empCode:"+empCode+"--count="+count+"--intresourceNum"+empPositionNum);
                    }
                }else{
                    count = -100;
                    bb.writeLog("dataerrorcount--empCode:"+empCode+"--intresourceNum:"+empPositionNum+"--count="+count);
                }
            }
        }catch (Exception e){
            bb.writeLog("OrganizationSyn-e:"+e);
            count = -2;
        }
        return count;
    }


}
