package com.crm.rely.backend.util;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonParser;
import com.lark.oapi.Client;
import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.service.contact.v3.model.*;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

import com.lark.oapi.core.request.RequestOptions;
import okhttp3.*;

public class LarkDeveloperUtil {

    // SDK 使用文档：https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/server-side-sdk/java-sdk-guide/preparations
    // 复制该 Demo 后, 需要将 "YOUR_APP_ID", "YOUR_APP_SECRET" 替换为自己应用的 APP_ID, APP_SECRET.
    // 以下示例代码默认根据文档示例值填充，如果存在代码问题，请在 API 调试台填上相关必要参数后再复制代码使用
    public static void main(String arg[]) throws Exception {
        // 构建client
        Client client = Client.newBuilder("cli_a73161e9a378902d", "T2HteJddoO1vkr254GmCfdj2lDyLASMt").build();

        /*String clientToken = UUID.randomUUID().toString();
        // 创建请求对象
        CreateUserReq req = CreateUserReq.newBuilder()
                .userIdType("open_id")
                //.departmentIdType("open_department_id")
                //.clientToken(clientToken)
                .user(User.newBuilder()
                        .userId("3e3cf96b121233213123")
                        .name("张三")
                        .enName("San Zhang")
                        .nickname("Alex Zhang")
                        .email("john.doe.test@cwgmarkets.com")
                        .mobile("18326559131")
                        .mobileVisible(false)
                        .gender(1)
                        //.avatarKey("2500c7a9-5fff-4d9a-a2de-3d59614ae28g")
                        .departmentIds(new String[]{null})
                        //.leaderUserId("ou_7dab8a3d3cdcc9da365777c7ad535d62")
                        .city("杭州")
                        .country("CN")
                        .workStation("北楼-H34")
                        //.joinTime(2147483647)
                        .employeeNo("3301")
                        .employeeType(1)
                        *//*.orders(new UserOrder[]{
                                UserOrder.newBuilder()
                                        .departmentId("od-4e6ac4d14bcd5071a37a39de902c7141")
                                        .userOrder(100)
                                        .departmentOrder(100)
                                        .isPrimaryDept(true)
                                        .build()
                        })
                        .customAttrs(new UserCustomAttr[]{
                                UserCustomAttr.newBuilder()
                                        .type("TEXT")
                                        .id("DemoId")
                                        .value(UserCustomAttrValue.newBuilder()
                                                .text("DemoText")
                                                .url("http://www.fs.cn")
                                                .pcUrl("http://www.fs.cn")
                                                .optionId("edcvfrtg")
                                                .genericUser(CustomAttrGenericUser.newBuilder()
                                                        .id("9b2fabg5")
                                                        .type(1)
                                                        .build())
                                                .build())
                                        .build()
                        })*//*
                        //.enterpriseEmail("demo@mail.com")
                        //.jobTitle("xxxxx")
                        //.geo("cn")
                        //.jobLevelId("mga5oa8ayjlp9rb")
                        //.jobFamilyId("mga5oa8ayjlp9rb")
                        //.subscriptionIds(new String[]{"23213213213123123"})
                        //.dottedLineLeaderUserIds(new String[]{"ou_7dab8a3d3cdcc9da365777c7ad535d62"})
                        .build())
                .build();*/

        // 发起请求
        //CreateUserResp resp = client.contact().user().create(req);

        // 处理服务端错误
        /*if (!resp.success()) {
            System.out.println(String.format("code:%s,msg:%s,reqId:%s, resp:%s",
                    resp.getCode(), resp.getMsg(), resp.getRequestId(), Jsons.createGSON(true, false).toJson(JsonParser.parseString(new String(resp.getRawResponse().getBody(), StandardCharsets.UTF_8)))));
            return;
        }

        // 业务数据处理
        System.out.println(Jsons.DEFAULT.toJson(resp.getData()));*/



        // 创建请求对象
//        SearchDepartmentReq req = SearchDepartmentReq.newBuilder()
//                .userIdType("open_id")
//                .departmentIdType("open_department_id")
//                //.pageToken("AQD9/Rn9eij9Pm39ED40/RD/cIFmu77WxpxPB/2oHfQLZ+G8JG6tK7+ZnHiT7COhD2hMSICh/eBl7cpzU6JEC3J7COKNe4jrQ8ExwBCR")
//                //.pageSize(10)
//                .searchDepartmentReqBody(SearchDepartmentReqBody.newBuilder()
//                        .query("CWG")
//                        .build())
//                .build();
        // 创建请求对象
        SearchDepartmentReq req = SearchDepartmentReq.newBuilder()
                .pageSize(20)
                .searchDepartmentReqBody(SearchDepartmentReqBody.newBuilder()
                        .query("销售部门")
                        .build())
                .build();


        // 发起请求
        SearchDepartmentResp resp = client.contact().department().search(req);


        // 处理服务端错误
        if (!resp.success()) {
            System.out.println(String.format("code:%s,msg:%s,reqId:%s, resp:%s",
                    resp.getCode(), resp.getMsg(), resp.getRequestId(), Jsons.createGSON(true, false).toJson(JsonParser.parseString(new String(resp.getRawResponse().getBody(), StandardCharsets.UTF_8)))));
            return;
        }





      /*  // 创建请求对象
        CreateOidcAccessTokenReq req = CreateOidcAccessTokenReq.newBuilder()
                .createOidcAccessTokenReqBody(CreateOidcAccessTokenReqBody.newBuilder()
                        .grantType("authorization_code")
                        .code("xMSldislSkdK")
                        .build())
                .build();

        // 发起请求
        CreateOidcAccessTokenResp resp = client.authen().oidcAccessToken().create(req);

        // 处理服务端错误
        if (!resp.success()) {
            System.out.println(String.format("code:%s,msg:%s,reqId:%s, resp:%s",
                    resp.getCode(), resp.getMsg(), resp.getRequestId(), Jsons.createGSON(true, false).toJson(JsonParser.parseString(new String(resp.getRawResponse().getBody(), StandardCharsets.UTF_8)))));
            return;
        }

        // 业务数据处理
        System.out.println(Jsons.DEFAULT.toJson(resp.getData()));*/




        /*RequestBody requestBody = new FormBody.Builder()
                //.add("query", cuntomerUserId)
                .add("app_id","cli_a73161e9a378902d")
                .add("app_secret","T2HteJddoO1vkr254GmCfdj2lDyLASMt")
                .build();

        // 构建请求头
        Request.Builder requestBuilder = new Request.Builder()
                .url("https://open.larksuite.com/open-apis/authen/v1/authorize?app_id=cli_a73161e9a378902d&redirect_uri=http://192.168.0.20:8000/kyc/webhook&scope=bitable:app:readonly%20contact:contact&state=RANDOMSTATE")
                .get()
                //.addHeader("Authorization", "Bearer " + token) // 添加授权头
                //.addHeader("Content-Type", "application/json; charset=utf-8"); // 假设请求体是JSON格式
                ;

        // 如果需要，还可以添加其他请求头
        //requestBuilder.addHeader("...", "...");

        // 构建请求
        Request request = requestBuilder.build();

        // 发送请求
        Response response = new OkHttpClient().newCall(request).execute();
        System.out.println(response.body().string());*/


/*
        //获取 user_access_token
         RequestBody requestBody2 = new FormBody.Builder()
                .add("grant_type", "authorization_code")
                 .add("code", cuntomerUserId)
                .build();//
        // 构建请求头
        Request.Builder requestBuilder1 = new Request.Builder()
                .url("https://open.larksuite.com/open-apis/authen/v1/oidc/access_token?user_id_type=open_id&department_id_type=open_department_id")
                .post(requestBody2)
                .addHeader("Authorization", "Bearer " + "t-g2072q6a57P2CJPJXFGCK4ZQQWAJGPWBGSYJ443V") // 添加授权头
                .addHeader("Content-Type", "application/json; charset=utf-8"); // 假设请求体是JSON格式



        Request request = requestBuilder1.build();

        // 发送请求
        Response response = new OkHttpClient().newCall(request).execute();
        System.out.println(response.body().string());*/



        /*RequestBody requestBody1 = new FormBody.Builder()
                .add("query", "CWG")
                .build();//
        // 构建请求头
        Request.Builder requestBuilder1 = new Request.Builder()
                .url("https://open.larksuite.com/open-apis/contact/v3/departments/search?user_id_type=open_id&department_id_type=open_department_id")
                .post(requestBody1)
                .addHeader("Authorization", "Bearer " + "t-g2072q6a57P2CJPJXFGCK4ZQQWAJGPWBGSYJ443V") // 添加授权头
                .addHeader("Content-Type", "application/json; charset=utf-8"); // 假设请求体是JSON格式



        Request request = requestBuilder1.build();

        // 发送请求
        Response response = new OkHttpClient().newCall(request).execute();
        System.out.println(response.body().string());*/


    }


}
