package com.kingdee.eas.custom.beisen.utils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import com.kingdee.bos.Context;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.basedata.org.AdminOrgUnitInfo;
import com.kingdee.shr.base.syssetting.util.MetaDataUtil;
import com.kingdee.util.StringUtils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class BeiSenUtils {
//    /**
//     * 获取访问令牌的 URL
//     */
////    public static final String ACCESSTOKEN_URL = "https://openapi.italent.cn/token";
//
//    /**
//     * 创建部门 URL
//     */
////    public static final String DEPARTMENTSPOST = "https://openapi.italent.cn/UserFrameworkApiV3/api/v1/departments/Post";
//
//    /**
//     * 跟新部门 URL
//     */
//
////    public static final  String DEPARTMENTSPUT = "https://openapi.italent.cn/UserFrameworkApiV3/api/v1/departments/Put";
    /**
     * 构造函数，通过传入 APP_KEY 和 APP_SECRET 初始化对象
     *
     * @param app_key    北森应用的 APP_KEY
     * @param app_secret 北森应用的 APP_SECRET
     */
    // 北森应用的 APP_KEY
    public String APP_KEY = null;
    // 北森应用的 APP_SECRET
    public String APP_SECRET = null;
    public Properties propt = new Properties();

    public Context context=null;

    public Helper helper = null;

    public BeiSenUtils(String app_key, String app_secret, Context context) {
        this.context = context;
        helper = new Helper(context);
        // 加载配置文件
        try {
            propt.load(new FileInputStream(System.getProperty("EAS_HOME") + "/server/properties/beiSen/BeiSenConfig.properties"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        this.APP_KEY = app_key;
        this.APP_SECRET = app_secret;
    }
    /**
     * 构造函数，从配置文件中读取 APP_KEY 和 APP_SECRET 初始化对象
     */
    public BeiSenUtils(Context context) {
        this.context = context;
        helper = new Helper(context);
        try {
            // 创建 Properties 对象用于读取配置文件
            // 加载配置文件
            propt.load(new FileInputStream(System.getProperty("EAS_HOME") + "/server/properties/beiSen/BeiSenConfig.properties"));
            // 从配置文件中获取 APP_KEY
            this.APP_KEY = propt.getProperty("APP_KEY");
            // 从配置文件中获取 APP_SECRET
            this.APP_SECRET = propt.getProperty("APP_SECRET");
        } catch (FileNotFoundException e) {
            // 若文件未找到，抛出运行时异常
            throw new RuntimeException(e);
        } catch (IOException e) {
            // 若读取文件时发生 IO 异常，抛出运行时异常
            throw new RuntimeException(e);
        }
    }
    /**
     * 获取访问令牌
     *
     * @return 访问令牌字符串
     * @throws FileNotFoundException 文件未找到异常
     * @throws IOException           IO 异常
     * @throws URISyntaxException    URI 语法异常
     */
    public String getAccessToken() throws FileNotFoundException, IOException, URISyntaxException {
        String tenantAccessToken = null;
        // 创建请求头的 Map
        Map<String, String> header = new HashMap<String, String>();
        // 设置请求头的 Content-Type
        header.put("Content-Type", "application/x-www-form-urlencoded");
        // 创建请求体的 JSONObject
        JSONObject requestBody = new JSONObject();
        // 设置请求体的 grant_type
        requestBody.put("grant_type", "client_credentials");
        // 设置请求体的 app_key
        requestBody.put("app_key", APP_KEY);
        // 设置请求体的 app_secret
        requestBody.put("app_secret", APP_SECRET);
        // 调用 Helper 类的 getURLEncoded 方法发送请求并获取响应的 JSONObject
        JSONObject responseJson = helper.getURLEncoded(propt.getProperty("ACCESSTOKEN_URL"), header, requestBody, "POST");
        // 从响应的 JSONObject 中获取访问令牌
        tenantAccessToken = responseJson.getString("access_token");
        return tenantAccessToken;
    }
    public JSONObject createOrUpdateByOrg(JSONObject requestBody, AdminOrgUnitInfo adminOrgUnitInfo) throws FileNotFoundException, IOException
            , URISyntaxException {
        String originalId = adminOrgUnitInfo.getString("originalId");
        String orgid = adminOrgUnitInfo.getId().toString();
        // 用于存储响应数据的 JSONArray
        JSONArray responseData = new JSONArray();
        // 用于存储响应的 JSONObject
        JSONObject responseJson = null;
        // 获取访问令牌
        String token = getAccessToken();
        // 若访问令牌不为空且开始时间和结束时间不为空
        if (!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);
            if (originalId!=null&&!originalId.equals("")){
                // 调用 Helper 类的 getURL 方法发送请求并获取响应的 JSONObject
                header.put("originalId",orgid);
                String departmentsput = propt.getProperty("DEPARTMENTSPUT");
                departmentsput+="?originalId="+ URLEncoder.encode(orgid, "UTF-8");;
                responseJson = helper.getURL(departmentsput,header, requestBody, "PUT",orgid,"更新","北森");
                System.out.println("url："+departmentsput);
                System.out.println("requestBody："+requestBody);
            }else {
                String departmentspost = propt.getProperty("DEPARTMENTSPOST");
                responseJson = helper.getURL(departmentspost, header, requestBody, "POST",orgid,"创建","北森");
                System.out.println("url："+propt.getProperty("DEPARTMENTSPOST"));
                System.out.println("requestBody："+requestBody);

            }

        }
        return responseJson;
    }

    public JSONObject setDisableAndEnable(String businessId,String url,String method) throws IOException, URISyntaxException {
        // 获取访问令牌
        String token = getAccessToken();
        Map<String, String> header = new HashMap<String, String>();
        // 设置请求头的 Content-Type
        header.put("Content-Type", "application/json");
        // 设置请求头的 Authorization
        header.put("Authorization", "Bearer " + token);
        JSONObject responseJson = helper.getURL(url, header, new JSONObject(), method,businessId,"启用/禁用/删除","北森");
        return responseJson;
    }

    public static void main(String[] args) {
        MetaDataUtil.getEntityObjectByBosType(BOSUuid.read("/1aEqNuoTWaCOnKAj1sSTHSuYS4=").getType()).getAlias();
    }



}
