package nckd.jimin.jyyy.hr.tsrsc.plugin.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.algo.DataSet;
import kd.bos.algo.Row;
import kd.bos.context.RequestContext;
import kd.bos.db.DB;
import kd.bos.db.DBRoute;
import kd.bos.exception.KDException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.schedule.executor.AbstractTask;
import kd.sdk.plugin.Plugin;
import nckd.base.helper.CommonHelperUtils;
import nckd.jimin.jyyy.hr.hrmp.hbpm.task.SyncUtil;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;


/**
 * 同步人员至Moka面试官
 */
public class MokaSyncUserTask extends AbstractTask implements Plugin {
    private static final Log log = LogFactory.getLog(MokaSyncUserTask.class);
    private static String startTime = "";
    private static String endTime = "";
    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        //初始化时间
        try {
            initDateRange(map);
            //获取Moka参数
            Map<String, String> params = CommonHelperUtils.getCommonParams("Moka");
            //1.查找变动人员
            StringBuilder sb = SyncUtil.getChangePersonForMoka();
            sb.append(" AND t1.fmodifytime >= '"+startTime+"' \n");
            sb.append(" AND t1.fmodifytime <= '"+endTime+"' \n");
            DataSet dataSet = DB.queryDataSet(this.getClass().getName(), DBRoute.of("hr"), sb.toString());
            //2.组装入参
            JSONObject ob = new JSONObject();
            buildJSON(ob, dataSet, params);
            if(ob.getJSONArray("usersInfo").size() == 0) {
                SyncUtil.createLog(SyncUtil.v_success, startTime, endTime, "未查询到变化人员", "未调用", SyncUtil.SyncPersonMoka);
                return;
            }
            //3.拆分调用接口，每次最多100条
            String url = params.get("syncUserUrl");
            SyncUtil.batchPost(100, url, ob, SyncUtil.SyncPersonMoka, startTime, endTime);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 组装入参
     * @param ob
     * @param dataSet
     */
    public static void buildJSON(JSONObject ob, DataSet dataSet, Map<String, String> params) {
        //        {
//            "usersInfo": [
//            {
//                "email": "huohuohou2@mokahr.com",   0
//                    "name": "liu大哥89",     1
//                    "phone": "15101069886", 0
//                    "number": "6661889",    1
//                    "roleId": 60,           0
//                    "departmentCode": [],
//                    "superiorEmail": "",
//                    "deactivated": 0,
//                    "thirdPartyId": "",
//                    "uniqueType": "number",
//                    "autoActivated": 1,
//                    "nickname": "花名",
//                    "locale": "zh-CN"
//            }
//            ]
//        }
        //招聘需求负责人工号，这些人变化时，角色ID不发生变化
        String HRBPNumbers = params.get("HRBP").toString();
        JSONArray arr = new JSONArray();
        int roleId = Integer.valueOf(params.get("roleId"));
        int HRRoleId = Integer.valueOf(params.get("HRRoleId"));
        while(dataSet.hasNext()) {
            JSONObject data = new JSONObject(true);
            Row rowData = dataSet.next();
            data.put("name", rowData.getString("personName"));
            data.put("email", rowData.getString("fbusemail"));
            data.put("phone", rowData.getString("fphone"));
            String personNumber = rowData.getString("personNumber");
            data.put("number", personNumber);
            if(HRBPNumbers.indexOf(personNumber) >= 0) {
                data.put("roleId", HRRoleId);
            }
            else {
                data.put("roleId", roleId);
            }
            JSONArray deptArr = new JSONArray();
            deptArr.add(rowData.getString("orgMokaNumber"));
            data.put("departmentCode", deptArr);
            data.put("deactivated", rowData.getInteger("deactivated"));
            data.put("uniqueType", "number");
            data.put("autoActivated", 1);
            arr.add(data);
        }
        ob.put("usersInfo", arr);
    }

    /**
     * 根据调度作业上配置的参数初始化时间范围
     * @param map
     */
    public void initDateRange(Map<String, Object> map) throws ParseException {
        boolean isAuto = Boolean.valueOf(map.get("isAuto").toString());
        if(!isAuto) {
            startTime = map.get("startTime").toString();
            endTime = map.get("endTime").toString();
        }
        //取最近一次日志的时间
        else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            startTime = sdf.format(SyncUtil.getLastSyncEndTime(SyncUtil.SyncPersonMoka));
            endTime = sdf.format(new Date());
        }
    }

}