package weaver.interfaces.mfkj.job;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.mfkj.util.HttpUtils;
import weaver.interfaces.schedule.BaseCronJob;

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

/**
 * @Title 同步组织结构信息给第三方系统
 * @Author wangchaofa
 * @CreateDate 2023/8/7
 * @Version 1.0
 * @Description
 */
public class SynOrgInfoJob extends BaseCronJob {

    BaseBean bb = new BaseBean();

    @Override
    public void execute() {
        bb.writeLog("========== start to syn org info ==========");
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        RecordSet rst = new RecordSet();

        String subcompany_id = bb.getPropValue("syn_othersys_mfkj","subcompany_id");
        //企业编码
        String corpCode = bb.getPropValue("syn_othersys_mfkj","corpCode");
        //用户名称
        String userName = bb.getPropValue("syn_othersys_mfkj","userName");
        //加密密码
        String password = bb.getPropValue("syn_othersys_mfkj","password");
        //获取 token  url
        String token_url = bb.getPropValue("syn_othersys_mfkj","token_url");
        //组织结构 全量同步接口 url
        String orgAll_url = bb.getPropValue("syn_othersys_mfkj","orgAll_url");
        //uf_dy_token   modeuuid
        String token_uuid = bb.getPropValue("syn_othersys_mfkj","token_uuid");

        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("corpCode",corpCode);
        jsonObject.put("userName",userName);
        jsonObject.put("password",password);

        Map<String,Object> tokenMap = new HashMap<>();
        Map<String,String> headers = new HashMap<>();
        String encode = "utf-8";
        String token = "";
        String expire = "";

        Calendar cal1 = Calendar.getInstance();
        long now_time = cal1.getTimeInMillis();

        try{
            rst.executeQuery("select * from uf_dy_token where modeuuid='"+ token_uuid +"'");
            rst.next();
            expire = Util.null2o(rst.getString("expire"));
            token = Util.null2o(rst.getString("token"));

            long timestamp = Long.parseLong(expire)*1000;
            //token已过期，重新调用获取新的token
            if(now_time > timestamp){
                tokenMap = HttpUtils.getTokenInfo(token_url,headers,jsonObject.toString(),encode);
                if(tokenMap.size() > 0){
                    token = (String) tokenMap.get("token");
                    expire = (String) tokenMap.get("expire");
                    //更新token和有效时间戳
                    rs1.executeUpdate("update uf_dy_token set token='"+ token +"',expire='"+ expire +"' where modeuuid='"+ token_uuid +"'");
                }
            }

            rs.executeQuery("select * from  HrmSubCompany where id="+ subcompany_id +" and (canceled is null or canceled=0)");
            rs.next();
            JSONObject json = new JSONObject();
            String subcompanycode = Util.null2o(rs.getString("subcompanycode"));
            String subcompanyname = Util.null2o(rs.getString("subcompanyname"));
            json.put("externalOrgKey",subcompanycode);
            json.put("orgName",subcompanyname);
            json.put("order",1);
            jsonArray.add(json);

            rs.executeQuery("select  *  from  HrmDepartment where subcompanyid1="+ subcompany_id +" and supdepid=0 and canceled is null order by showOrderOfTree");
            while(rs.next()){
                JSONObject jsonn = new JSONObject();
                String supdeptid = Util.null2o(rs.getString("id"));

                String departmentcode = Util.null2o(rs.getString("departmentcode"));
                String departmentname = Util.null2o(rs.getString("departmentname"));
                String showOrderOfTree = Util.null2o(rs.getString("showOrderOfTree"));

                getChildDept(jsonArray,subcompany_id,supdeptid,departmentcode);

                jsonn.put("externalOrgKey",departmentcode);
                jsonn.put("orgName",departmentname);
                jsonn.put("externalParentOrgKey",subcompanycode);
                jsonn.put("order",showOrderOfTree);
                jsonArray.add(jsonn);
            }

            bb.writeLog("=================== jsonArray ========================  "+ jsonArray.toString());

            headers.put("Authorization", "Bearer "+token);

            boolean bool = HttpUtils.pushPostJsoninfo(orgAll_url,headers,jsonArray.toString(),"UTF-8");
            bb.writeLog("========== syn org info  result  ==========  "+ bool);
        }catch(Exception e){
            e.printStackTrace();
            bb.writeLog(e);
        }
        bb.writeLog("========== end to syn org info ==========");
    }

    public static void getChildDept(JSONArray jsonArray, String subcompanycode, String supdeptid, String supdeptcode){
        RecordSet rs = new RecordSet();
        rs.executeQuery("select  *  from  HrmDepartment where subcompanyid1="+subcompanycode+" and supdepid="+supdeptid+" and canceled is null  order by showOrderOfTree");
        while(rs.next()){
            JSONObject jsonn = new JSONObject();
            String deptid = Util.null2o(rs.getString("id"));

            String departmentcode = Util.null2o(rs.getString("departmentcode"));
            String departmentname = Util.null2o(rs.getString("departmentname"));
            String showOrderOfTree = Util.null2o(rs.getString("showOrderOfTree"));

            getChildDept(jsonArray,subcompanycode,deptid,departmentcode);

            jsonn.put("externalOrgKey",departmentcode);
            jsonn.put("orgName",departmentname);
            jsonn.put("externalParentOrgKey",supdeptcode);
            jsonn.put("order",showOrderOfTree);
            jsonArray.add(jsonn);
        }
    }
}
