package com.kingdee.eas.custom.beisen.synchronouspos.osf;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.bsf.service.app.IHRMsfService;
import com.kingdee.bos.rabbitmq.guava.Lists;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.beisen.utils.BeiSenUtils;
import com.kingdee.eas.custom.beisen.utils.BeisenParamByPropertiesUtil;
import com.kingdee.eas.custom.beisen.utils.Helper;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.sql.Date;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 岗位同步
 * description: SynchronousPosOSFService <br>
 * date: 2025/7/11 17:46 <br>
 * author: lhbj <br>
 * version: 1.0 <br>
 */
public class SynchronousPosOSFService implements IHRMsfService {

    @Override
    public Object process(Context context, Map<String, Object> map) throws EASBizException, BOSException {
        //例：/server/properties/beisen/posConfig.properties
        String path = (String) map.get("path");
        String posId = (String) map.get("posId");
        String syncStartTimeStr = (String) map.get("syncStartTimeStr");
        String syncEndTimeStr = (String) map.get("syncEndTimeStr");
        try {
            BeisenParamByPropertiesUtil util = new BeisenParamByPropertiesUtil(path);
            Map<String,String> keyMap = util.getConfig();
            return this._syncPosToBeiSen(context,keyMap,posId,syncStartTimeStr,syncEndTimeStr);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return null;
    }


    protected String _syncPosToBeiSen(Context ctx,Map<String,String> keyMap, String posId, String syncStartTimeStr, String syncEndTimeStr) throws BOSException, SQLException, IOException, URISyntaxException {
        List<JSONObject> responseList =Lists.newArrayList();
        List<JSONObject> addNewList = this._sendAddNewPosToBeisen(ctx,keyMap,posId,syncStartTimeStr,syncEndTimeStr);
        responseList.addAll(addNewList);
        List<JSONObject> editList = this._sendEditPosToBeisen(ctx,keyMap,posId,syncStartTimeStr,syncEndTimeStr);
        responseList.addAll(editList);
        return responseList.toString();
    }

    /**
     * shr系统数据组装北森请求参数
     *
     * @param ctx
     * @param keyMap
     * @param sql
     * @return
     * @throws BOSException
     * @throws SQLException
     */
    protected List<Map<String, Object>> getPostData(Context ctx,Map<String,String> keyMap,StringBuilder sql) throws BOSException, SQLException {

        IRowSet rowSet = DbUtil.executeQuery(ctx,sql.toString());
        List<Map<String, Object>> posList = Lists.newArrayList();
        while (rowSet.next()){
            Map<String, Object> pos = Maps.newHashMap();
            for(Map.Entry<String,String> entry : keyMap.entrySet()){
               String shrKey = entry.getKey();
               String beisenKey = entry.getValue();
               if(shrKey.indexOf(".")>0){
                   String[] keys=shrKey.split("\\.");
                   if(2==keys.length){
                      Map<String,Object> map1 = (Map<String, Object>) pos.get(keys[0]);
                      if(null==map1){
                          map1=Maps.newHashMap();
                          pos.put(keys[0],map1);
                      }
                       String valueStr = rowSet.getString(keys[1]);
                      if(beisenKey.indexOf(",")>0) {
                          String[] beisenKeys = beisenKey.split(",");
                          Object value = null;

                          if("integer".equals(beisenKeys[1])){
                              if(null!=valueStr){
                                  value=Integer.parseInt(valueStr);
                              }
                          }else {
                              value = valueStr;
                          }
                          if(null!=value) {
                              map1.put(beisenKeys[0], value);
                          }
                      }else {

                          if(null!=valueStr) {
                              map1.put(beisenKey, valueStr);
                          }
                      }
                   }else if (3==keys.length){
                       Map<String,Object> map1 = (Map<String, Object>) pos.get(keys[0]);
                       if(null==map1){
                           map1=Maps.newHashMap();
                           pos.put(keys[0],map1);
                       }
                       Map<String,Object> map2 = (Map<String, Object>) map1.get(keys[1]);
                       if(null==map2){
                           map2=Maps.newHashMap();
                           map1.put(keys[1],map1);
                       }
                       String valueStr = rowSet.getString(keys[2]);
                       if(beisenKey.indexOf(",")>0) {
                           String[] beisenKeys = beisenKey.split(",");
                           Object value = null;

                           if("integer".equals(beisenKeys[1])){
                               if(null!=valueStr){
                                   value=Integer.parseInt(valueStr);
                               }
                           }else {
                               value = valueStr;
                           }
                           if(null!=value) {
                               map2.put(beisenKeys[0], value);
                           }
                       }else {
                           if(null!=valueStr) {
                               map2.put(beisenKey,valueStr);
                           }
                       }
                   }
               }else {
                   String valueStr = rowSet.getString(shrKey);
                   if(beisenKey.indexOf(",")>0) {
                       String[] beisenKeys = beisenKey.split(",");
                       Object value = null;
                       if("integer".equals(beisenKeys[1])){
                           if(null!=valueStr){
                               value=Integer.parseInt(valueStr);
                           }
                       }else {
                           value = valueStr;
                       }
                       if(null!=value) {
                           pos.put(beisenKeys[0],value);
                       }
                   }else {
                       if(null!=valueStr) {
                           pos.put(beisenKey,valueStr);
                       }
                   }
               }
            }
            posList.add(pos);
        }
        return posList;
    }


    public StringBuilder getSql(String posId,String syncStartTimeStr, String syncEndTimeStr,Boolean isAddNew){
        StringBuilder sql = new StringBuilder();
        sql.append(" ");
        sql.append(" select ");
        sql.append(" pos.fid posId, ");
        sql.append(" pos.CFOriginalId posOriginalId, ");
        sql.append(" pos.fnumber posNumber, ");
        sql.append(" pos.fname_l2 posName, ");
        sql.append(" org.fid orgId, ");
        sql.append(" org.FreserveFieldFirst orgOriginalId, ");
        sql.append(" isnull(org.fnumber,'') orgNumber, ");
        sql.append(" isnull(org.fname_l2,'') orgName, ");
        sql.append("  (case when pos.FDELETEDSTATUS=2 then 0 else 1 end) posDeletedStatus, ");
        sql.append(" isnull(pos.cfzwjzygx,'') posZwjzygx, ");
        sql.append(" isnull(pos.cfzyzz,'')  posZyzz, ");
        sql.append(" isnull(pos.cfgwdwsccg,'') posGwdwsccg, ");
        sql.append(" isnull(pos.cfcgzb,'') posCgzb, ");
        sql.append(" isnull(pos.cfzlzb,'') posZlzb, ");
        sql.append(" isnull(jobf.fname_l2,'') hrJobFamily, ");
        sql.append(" isnull(jobc.fname_l2,'') hrJobCategory, ");
        sql.append(" isnull(jobsc.fname_l2,'') jobscHrJobSubCategory, ");
        sql.append(" isnull(job.fnumber,'') jobNumber, ");
        sql.append(" isnull(job.fname_l2,'') jobName, ");
        sql.append(" isnull(lowjg.fname_l2,'') lowJobGrade, ");
        sql.append(" isnull(highjg.fname_l2,'') highJobGrade, ");
        sql.append(" isnull(lowjl.fname_l2,'') lowJobLevel, ");
        sql.append(" isnull(highjl.fname_l2,'') highJobLevel, ");
        sql.append(" isnull(pos.cfeducation,'') education, ");
        sql.append(" isnull(pos.cfrequirement,'') requirement, ");
        sql.append(" isnull(pos.cfcertification,'') certification, ");
        sql.append(" isnull(pos.cfforeignLang,'') foreignLang, ");
        sql.append(" isnull(pos.cfknowledge,'') knowledge, ");
        sql.append(" isnull(pos.cfskills,'') skills, ");
        sql.append(" isnull(pos.cfexperience,'') experience, ");
        sql.append(" isnull(pos.cfcoreCompe,'') coreCompe, ");
        sql.append(" isnull(pos.cfposition1,'') position1, ");
        sql.append(" isnull(pos.cfptime1,'') ptime1, ");
        sql.append(" isnull(pos.cfposition2,'') position2, ");
        sql.append(" isnull(pos.cfptime2,'') ptime2, ");
        sql.append(" isnull(workAdd.fnumber,'') workAdd, ");
        sql.append(" isnull(pos.CFFrequency,'') frequency, ");
        sql.append(" isnull(pos.cfjobRespon,'') jobRespon, ");
        sql.append(" isnull(pos.cfqualifications,'') qualifications, ");
        sql.append(" isnull(pos.cfreserved1,'') reserved1, ");
        sql.append(" isnull(pos.cfreserved2,'') reserved2, ");
        sql.append(" isnull(pos.cfreserved3,'') reserved3, ");
        sql.append(" isnull(pos.cfreserved4,'') reserved4, ");
        sql.append(" isnull(redf.FNumber,'') reserved5, ");
        sql.append(" posp.CFOriginalId pospOriginalId1, ");
        sql.append(" posp.CFOriginalId pospOriginalId2, ");
        sql.append(" '' ");
        sql.append(" from ");
        sql.append(" t_org_position pos ");
        sql.append(" left join t_org_admin org on pos.FADMINORGUNITID = org.fid ");
        sql.append(" left join CT_CUS_WorkAdd workAdd on workAdd.fid=pos.CFWorkAddID ");
        sql.append(" left join T_ORG_Job orgjob on orgjob.fid=pos.fjobid ");
        sql.append(" left join T_HR_HRJob job on job.FjobID = orgjob.fid ");
        sql.append(" left join T_HR_POSITIONEXTEND posex on posex.FPositionID=pos.fid ");
        sql.append(" left join T_HR_HRJobFamily jobf on jobf.fid = job.FHRJobFamilyID ");
        sql.append(" left join T_HR_HRJobCategory jobc on jobc.fid = job.FHRJobCategoryID ");
        sql.append(" left join T_HR_HRJobSubCategory jobsc on jobsc.fid=job.FHRJobSubCategoryID ");
        sql.append(" left join T_HR_JobGrade lowjg on lowjg.fid = pos.FLowJobGradeID ");
        sql.append(" left join T_HR_JobGrade highjg on highjg.fid = pos.FHighJobGradeID ");
        sql.append(" left join T_HR_JobLevel lowjl on lowjl.fid=posex.FLowJobLevel ");
        sql.append(" left join T_HR_JobLevel highjl on highjl.fid=posex.FHighJobLevel ");
        sql.append(" left join t_org_position posp on posp.fid=pos.FPARENTID ");
        sql.append(" left join CT_CUS_ReservedField redf on redf.fid=pos.CFReserved5ID ");

        sql.append(" where 1=1 ");
        if(StringUtils.isNotBlank(posId)){
            String[] posIds=posId.split(",");
            sql.append(" and pos.fid in('' ");
            for(String id : posIds){
                sql.append(",'");
                sql.append(id);
                sql.append("'");
            }
            sql.append(") ");
        }
        if(StringUtils.isNotBlank(syncStartTimeStr)){
            sql.append(" and pos.FLastUpdateTime >='"+syncStartTimeStr+"'");
        }
        if(StringUtils.isNotBlank(syncEndTimeStr)){
            sql.append(" and pos.FLastUpdateTime <='"+syncEndTimeStr+"'");
        }
        if(isAddNew){
            sql.append(" and (pos.CFOriginalId is null or pos.CFOriginalId ='')");
        }else {
            sql.append(" and (pos.CFOriginalId is not null and pos.CFOriginalId !='')");
        }
        return sql;
    }


    protected  List<JSONObject> _sendAddNewPosToBeisen(Context ctx,Map<String,String> keyMap, String posId, String syncStartTimeStr, String syncEndTimeStr) throws BOSException, SQLException, IOException, URISyntaxException {
        BeiSenUtils b = new BeiSenUtils(ctx);
        Helper helper = b.helper;
        StringBuilder sql = this.getSql(posId, syncStartTimeStr, syncEndTimeStr, true);
        System.out.println("_sendAddNewPosToBeisen:"+sql);
        List<Map<String, Object>> list = this.getPostData(ctx, keyMap, sql);
        List<JSONObject> responseList = Lists.newArrayList();
        for (Map<String, Object> pos : list) {
            // 获取访问令牌
            String token = b.getAccessToken();
            // 若访问令牌不为空且开始时间和结束时间不为空
            if (!com.kingdee.util.StringUtils.isEmpty(token)) {
                // 创建请求头的 Map
                Map<String, String> header = new HashMap<String, String>();
                // 设置请求头的 Content-Type
                header.put("Content-Type", "application/json");
                // 设置请求头的 Authorization
                header.put("Authorization", "Bearer " + token);
                String url = "https://openapi.italent.cn/RecruitV6/api/v1/RecruitOnBoarding/CreatePost";
                JSONObject requestBody = new JSONObject(pos);
                System.out.println("url：" + url);
                System.out.println("requestBody：" + requestBody);
                JSONObject responseJson = helper.getURL(url, header, requestBody, "POST", requestBody.getString("posId"), "创建", "北森");
                System.out.println("responseJson：" + responseJson);
                Integer code = responseJson.getInteger("code");
                if(200==code){
                    String data = responseJson.getString("data");
                    String posId1 = requestBody.getString("posId");
                    DbUtil.execute(ctx,"update t_org_position set CFOriginalId = ? where fid=?",new String[]{data,posId1});
                }
                responseList.add(responseJson);
            }
        }
        return responseList;
    }
    protected List<JSONObject> _sendEditPosToBeisen(Context ctx,Map<String,String> keyMap, String posId, String syncStartTimeStr, String syncEndTimeStr) throws BOSException, SQLException, IOException, URISyntaxException {
        BeiSenUtils b = new BeiSenUtils(ctx);
        Helper helper = b.helper;
        StringBuilder sql1 = this.getSql(posId,syncStartTimeStr,syncEndTimeStr,false);
        System.out.println("_sendAddNewPosToBeisen:"+sql1);
        List<Map<String,Object>> list1 = this.getPostData(ctx,keyMap,sql1);
        List<JSONObject> responseList = Lists.newArrayList();
        // 获取访问令牌
        String token = b.getAccessToken();
        for(Map<String,Object> pos : list1){

            // 若访问令牌不为空且开始时间和结束时间不为空
            if (!com.kingdee.util.StringUtils.isEmpty(token)) {
                // 创建请求头的 Map
                Map<String, String> header = new HashMap<String, String>();
                // 设置请求头的 Content-Type
                header.put("Content-Type", "application/json");
                // 设置请求头的 Authorization
                header.put("Authorization", "Bearer " + token);
                String url = "https://openapi.italent.cn/RecruitV6/api/v1/RecruitOnBoarding/UpdatePost";
                JSONObject requestBody = new JSONObject(pos);
                System.out.println("url："+url);
                System.out.println("requestBody："+requestBody);
                JSONObject responseJson = helper.getURL(url,header, requestBody, "PUT",requestBody.getString("posId"),"更新","北森");
                System.out.println("responseJson："+responseJson);
                responseList.add(responseJson);
            }
        }
        return responseList;
    }
}
