FeiShuApiService.java 31.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
package com.pipihelper.project.feishu.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.pipihelper.project.core.ServiceException;
import com.pipihelper.project.feishu.dto.FeiShuConfig;
import com.pipihelper.project.feishu.dto.FeiShuCreateTaskDTO;
import com.pipihelper.project.feishu.dto.FeiShuResultDTO;
import com.pipihelper.project.feishu.dto.chat.FeiShuChatDTO;
import com.pipihelper.project.feishu.dto.department.FeiShuDepartmentDTO;
import com.pipihelper.project.feishu.dto.doc.DocDTO;
import com.pipihelper.project.feishu.dto.doc.FieldsDTO;
import com.pipihelper.project.feishu.dto.employee.FeiShuEmployeeDTO;
import com.pipihelper.project.feishu.dto.msg.FeiShuBatchMsgDTO;
import com.pipihelper.project.feishu.dto.msg.FeiShuMsgDTO;
import com.pipihelper.project.feishu.entity.ChatMessage;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.lang.reflect.Type;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @author: charles
 * @date: 2022年05月19日 15:40
 */
@Service
@Transactional
@Slf4j
public class FeiShuApiService {
    @Resource
    private FeiShuConfig feiShuConfig;

    @Autowired
    private ChatMessageService chatMessageService;

    private static ObjectMapper objectMapper = new ObjectMapper();


    private final Cache<Object, String> FEISHU_CACHE = Caffeine.newBuilder()
            .maximumSize(100)
            .expireAfterWrite(Duration.ofHours(2))
            .build();

/*    private final Cache<String, List<FeiShuEmployeeDTO>> EMPLOYEE_LIST_CACHE = Caffeine.newBuilder()
            .maximumSize(100)
            .expireAfterWrite(Duration.ofHours(2))
            .build();*/

    public String getTenantToken() {
        return FEISHU_CACHE.get("tenantAccessToken", key -> setTenantAccessToken());
    }

    public String setTenantAccessToken() {
        String api = "/auth/v3/tenant_access_token/internal";
        RestTemplate restTemplate = new RestTemplate();
        JSONObject params = new JSONObject();
        params.put("app_id", feiShuConfig.getAppId());
        params.put("app_secret", feiShuConfig.getAppSecret());
        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(feiShuConfig.getFeiShuOpenApiHost() + api, params, JSONObject.class);
        System.out.println(responseEntity.getBody().get("tenant_access_token").toString());
        return responseEntity.getBody().get("tenant_access_token").toString();
    }

//    /**
//     * @param /https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/message/create
//     * @param sendMsg
//     * @return
//     */
//    public JSONObject sendMsg(String receive_id_type, JSONObject sendMsg) {
//        System.out.println(sendMsg.toString());
//
//        //发送消息
//        String api = "/im/v1/messages?receive_id_type={receive_id_type}";
//        RestTemplate restTemplate = new RestTemplate();
//        HttpHeaders headers = new HttpHeaders();
//        headers.set("Authorization", "Bearer " + getTenantToken());
//        headers.set("Content-Type", "application/json; charset=utf-8");
//        HttpEntity<String> requestEntity = new HttpEntity<>(sendMsg.toString(), headers);
//        String url = feiShuConfig.getFeiShuOpenApiHost() + api;
//        try {
//            ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, requestEntity, JSONObject.class, receive_id_type);
//            if (responseEntity.getBody().getJSONObject("data") == null) {
//                return null;
//            }
//            log.info("消息发送成功,接收人: {}", sendMsg.getString("receive_id"));
//            return responseEntity.getBody();
//        } catch (Exception e) {
//            log.error("飞书:" + api + "接口调用失败" + "\n" + e);
//            throw new ServiceException("飞书:" + api + "接口调用失败" + "\n" + e);
//        }
//    }


    @Async
    public JSONObject replyMsg(String message_id, JSONObject replyMsg) {
        System.out.println(replyMsg.toString());
        String api = "/im/v1/messages/{message_id}/reply";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + getTenantToken());
        headers.set("Content-Type", "application/json; charset=utf-8");
        HttpEntity<String> requestEntity = new HttpEntity<>(replyMsg.toString(), headers);
        String url = feiShuConfig.getFeiShuOpenApiHost() + api;
        try {
            ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, requestEntity, JSONObject.class, message_id);
            log.info("飞书接口 {} 调用成功,返回值:{}", api, responseEntity.getBody());
            return responseEntity.getBody();
        } catch (Exception e) {
            throw new ServiceException("飞书:" + api + "接口调用失败" + "\n" + e);
        }
    }

    public JSONObject patchMsg(String message_id, JSONObject content) {
        String api = "/im/v1/messages/";
        OkHttpClient client = new OkHttpClient();
        String url = feiShuConfig.getFeiShuOpenApiHost() + api;
        RequestBody requestBody = RequestBody.create(content.toString(), MediaType.parse("application/json"));
        Request request = new Request.Builder()
                .patch(requestBody)
                .url(url + message_id)
                .addHeader("Authorization", "Bearer " + getTenantToken())
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .build();
        try {
            Response response = client.newCall(request).execute();
            String responseString = response.body().string();
            log.info("飞书接口 {} 调用成功,返回值:{}", api, responseString);
            return JSONObject.parseObject(responseString);
        } catch (Exception e) {
            throw new ServiceException("飞书:" + api + "接口调用失败" + "\n" + e);
        }
    }

    @Async
    public JSONObject patchUrgentApp(String message_id, JSONObject content) {
        String api = "/im/v1/messages/" + message_id + "/urgent_app?user_id_type=open_id";
        OkHttpClient client = new OkHttpClient();
        String url = feiShuConfig.getFeiShuOpenApiHost() + api;
        RequestBody requestBody = RequestBody.create(content.toString(), MediaType.parse("application/json"));
        Request request = new Request.Builder()
                .patch(requestBody)
                .url(url)
                .addHeader("Authorization", "Bearer " + getTenantToken())
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .build();
        try {
            Response response = client.newCall(request).execute();
            String responseString = response.body().string();
            System.out.println(responseString);
            return JSONObject.parseObject(responseString);
        } catch (Exception e) {
            System.out.println("飞书:" + api + "接口调用失败" + "\n" + e);
            return null;
        }
    }


    @Async
    public JSONObject patchUrgentSms(String message_id, JSONObject content) {
        String api = "/im/v1/messages/" + message_id + "/urgent_sms?user_id_type=user_id";
        OkHttpClient client = new OkHttpClient();
        String url = feiShuConfig.getFeiShuOpenApiHost() + api;
        RequestBody requestBody = RequestBody.create(content.toString(), MediaType.parse("application/json"));
        Request request = new Request.Builder()
                .patch(requestBody)
                .url(url)
                .addHeader("Authorization", "Bearer " + getTenantToken())
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .build();
        try {
            Response response = client.newCall(request).execute();
            String responseString = response.body().string();
            System.out.println(responseString);
            return JSONObject.parseObject(responseString);
        } catch (Exception e) {
            System.out.println("飞书:" + api + "接口调用失败" + "\n" + e);
            return null;
        }
    }


    //    @Async
    public String createTask(FeiShuCreateTaskDTO taskMsg, String openId) {
        log.info("调用创建任务接口,task: {}", taskMsg.toString());
        String api = "/task/v1/tasks";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + getTenantToken());
//        headers.set("Authorization", "Bearer " + "t-d3db00058d854b3c004ffdf6453fd3e169c82043");

        headers.set("Content-Type", "application/json; charset=utf-8");
        HttpEntity<String> requestEntity = new HttpEntity<>(JSON.toJSONString(taskMsg), headers);
        String url = feiShuConfig.getFeiShuOpenApiHost() + api;
//        String url = "https://open.feishu.cn/open-apis" + api;
        try {
            ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, requestEntity, JSONObject.class);
            String taskId = responseEntity.getBody().getJSONObject("data").getJSONObject("task").getString("id");
            collaborators(taskId, openId);
            return taskId;
        } catch (Exception e) {
            throw new ServiceException("飞书:" + api + "接口调用失败" + "\n" + e);
        }
    }


    public JSONObject collaborators(String taskId, String openId) {
        if (StringUtils.isBlank(openId)) {
            return null;
        }
        String api = "/task/v1/tasks/{taskId}/collaborators";
        RestTemplate restTemplate = new RestTemplate();
        JSONObject param = new JSONObject();
        param.put("id", openId);
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + getTenantToken());
        headers.set("Content-Type", "application/json; charset=utf-8");
        HttpEntity<String> requestEntity = new HttpEntity<>(param.toString(), headers);
        String url = feiShuConfig.getFeiShuOpenApiHost() + api;
        try {
            ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, requestEntity, JSONObject.class, taskId);
            return responseEntity.getBody();
        } catch (Exception e) {
            throw new ServiceException("飞书:" + api + "接口调用失败" + "\n" + e);
        }
    }


    public byte[] getMessageFile(String messageId, String fileKey, String type) {
        String api = "/im/v1/messages/{messageId}/resources/{fileKey}/?type={type}";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + getTenantToken());
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(headers);
        String url = feiShuConfig.getFeiShuOpenApiHost() + api;
        try {
            ResponseEntity<byte[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, byte[].class, messageId, fileKey, type);
            return responseEntity.getBody();
        } catch (Exception e) {
            throw new ServiceException("飞书:" + api + "接口调用失败");
        }
    }

    //获取指定部门下的员工信息
    public JSONObject getUser(String department_id) {
        String api = "/contact/v3/users/find_by_department?department_id={department_id}";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + getTenantToken());
        headers.set("Content-Type", "application/json; charset=utf-8");
        HttpEntity<String> requestEntity = new HttpEntity<>(headers);
        String url = feiShuConfig.getFeiShuOpenApiHost() + api;
        try {
            ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, JSONObject.class, department_id);
            return responseEntity.getBody();
        } catch (Exception e) {
            throw new ServiceException("飞书:" + api + "接口调用失败" + "\n" + e);
        }
    }

    public JSONObject getUserInfo(String openId) {
        String api = "/contact/v3/users/:{userId}?department_id_type=open_department_id&user_id_type=open_id";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + getTenantToken());
        headers.set("Content-Type", "application/json; charset=utf-8");
        HttpEntity<String> requestEntity = new HttpEntity<>(headers);
        String url = feiShuConfig.getFeiShuOpenApiHost() + api;
        try {
            ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, JSONObject.class, openId);
            JSONObject user = responseEntity.getBody().getJSONObject("user");
            return user;
        } catch (Exception e) {
            throw new ServiceException("飞书:" + api + "接口调用失败" + "\n" + e);
        }
    }

    //下载文件
    public byte[] downloadFile(String filePath) {
        String api = "/im/v1/files/{filePath}";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + getTenantToken());
        HttpEntity<String> requestEntity = new HttpEntity<>(headers);
        String url = feiShuConfig.getFeiShuOpenApiHost() + api;
        try {
            ResponseEntity<byte[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, byte[].class, filePath);
            return responseEntity.getBody();
        } catch (Exception e) {
            throw new ServiceException("飞书:" + api + "接口调用失败" + "\n" + e);
        }
    }

    //上传文件
    public String uploadFile(String file_type, String file_name, Integer duration, byte[] file) {
        String api = "/im/v1/files";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + getTenantToken());
        headers.setContentType(org.springframework.http.MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("file_type", file_type);
        param.add("file_name", file_name);
        param.add("duration", duration);
        param.add("file", file);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(param, headers);
        String url = feiShuConfig.getFeiShuOpenApiHost() + api;
        try {
            ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, requestEntity, JSONObject.class);
            return responseEntity.getBody().getJSONObject("data").getString("file_key");
        } catch (Exception e) {
            throw new ServiceException("飞书:" + api + "接口调用失败" + "\n" + e);
        }
    }


    //上传图片
    public String uploadImage(String image_type, byte[] file) {
        String api = "/im/v1/images";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + getTenantToken());
        headers.setContentType(org.springframework.http.MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("image_type", image_type);
        param.add("image", file);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(param, headers);
        String url = feiShuConfig.getFeiShuOpenApiHost() + api;
        try {
            ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, requestEntity, JSONObject.class);
            return responseEntity.getBody().getJSONObject("data").getString("image_key");
        } catch (Exception e) {
            throw new ServiceException("飞书:" + api + "接口调用失败" + "\n" + e);
        }
    }

    //获取应用有权限的所有部门
    public JSONObject getDepartment() {
        String api = "/contact/v3/departments?fetch_child=true";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + getTenantToken());
        headers.set("Content-Type", "application/json; charset=utf-8");
        HttpEntity<String> requestEntity = new HttpEntity<>(headers);
        String url = feiShuConfig.getFeiShuOpenApiHost() + api;
        try {
            ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, JSONObject.class);
            return responseEntity.getBody();
        } catch (Exception e) {
            throw new ServiceException("飞书:" + api + "接口调用失败" + "\n" + e);
        }
    }


    /**
     * 获取飞书人事花名单信息
     * 文档:https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/ehr/ehr-v1/employee/list
     *
     * @return
     */
    public List<FeiShuEmployeeDTO> getEmployeeList() {
        String api = "/ehr/v1/employees?view=full&status=2&status=4&page_size=100&user_id_type=open_id";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + getTenantToken());
        headers.set("Content-Type", "application/json; charset=utf-8");
        HttpEntity<String> requestEntity = new HttpEntity<>(headers);
        String url = feiShuConfig.getFeiShuOpenApiHost() + api;
        try {
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
            Type type = new TypeReference<FeiShuResultDTO<FeiShuEmployeeDTO>>() {
            }.getType();
            FeiShuResultDTO feiShuResultDTO = JSONObject.parseObject(responseEntity.getBody(), type);
            List<FeiShuEmployeeDTO> feiShuEmployeeDTOList = new ArrayList<>();
            feiShuEmployeeDTOList.addAll(feiShuResultDTO.getData().getItems());
            while (feiShuResultDTO.getData().getItems().size() >= 100) {
                ResponseEntity<String> next = restTemplate.exchange(url + "&page_token=" + feiShuResultDTO.getData().getPageToken(), HttpMethod.GET, requestEntity, String.class);
                feiShuResultDTO = JSONObject.parseObject(next.getBody(), type);
                feiShuEmployeeDTOList.addAll(feiShuResultDTO.getData().getItems());
            }
            log.info("花名册获取完成,总计 {} 人", feiShuEmployeeDTOList.size());
            return feiShuEmployeeDTOList;
        } catch (Exception e) {
            throw new ServiceException("飞书:" + api + "接口调用失败" + "\n" + e);
        }
    }

    /**
     * 获取机器人所在群信息
     * https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/chat/list
     *
     * @return
     */
    public String createChatList(FeiShuChatDTO feiShuChatDTO) {
        String api = "/im/v1/chats?user_id_type=open_id";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + getTenantToken());
        headers.set("Content-Type", "application/json; charset=utf-8");
        String url = feiShuConfig.getFeiShuOpenApiHost() + api;
        try {
            HttpEntity<String> requestEntity = new HttpEntity<>(objectMapper.writeValueAsString(feiShuChatDTO), headers);
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
            System.out.println(responseEntity.getBody());
            Type type = new TypeReference<FeiShuResultDTO>() {
            }.getType();
            FeiShuResultDTO feiShuResultDTO = JSONObject.parseObject(responseEntity.getBody(), type);
            saveChatId(feiShuResultDTO.getData().getChatId());
            return feiShuResultDTO.getData().getChatId();
        } catch (Exception e) {
            throw new ServiceException("飞书:" + api + "接口调用失败" + "\n" + e);
        }
    }


    public void saveChatId(String chatId) {
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setChatId(chatId);
        chatMessage.setType(11);
        chatMessageService.create(chatMessage);
    }

    public String queryChatId() {
        List<ChatMessage> list = chatMessageService.findAll();
        if (CollectionUtil.isEmpty(list)) {
            return null;
        }
        List<ChatMessage> remainList = list.stream().filter(chatMessage1 -> ObjectUtil.equal(chatMessage1.getType(), 11)
                && chatMessage1.getMessageId() == null).collect(Collectors.toList());
        return CollectionUtil.getFirst(remainList).getChatId();
    }


    @Async
    public String joinChatList(FeiShuChatDTO feiShuChatDTO) {
        String api = "/im/v1/chats/{chat_id}/members";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + getTenantToken());
        headers.set("Content-Type", "application/json; charset=utf-8");
        String url = feiShuConfig.getFeiShuOpenApiHost() + api;
        try {
            HttpEntity<String> requestEntity = new HttpEntity<>(objectMapper.writeValueAsString(feiShuChatDTO), headers);
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class, feiShuChatDTO.getChatId());
            System.out.println(responseEntity.getBody());
            Type type = new TypeReference<FeiShuResultDTO>() {
            }.getType();
            FeiShuResultDTO feiShuResultDTO = JSONObject.parseObject(responseEntity.getBody(), type);
            return feiShuResultDTO.getData().getChatId();
        } catch (Exception e) {
            throw new ServiceException("飞书:" + api + "接口调用失败" + "\n" + e);
        }
    }

    public String deleteChatList(String chatId) {
        String api = "/im/v1/chats/{chat_id}";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + getTenantToken());
        headers.set("Content-Type", "application/json; charset=utf-8");
        String url = feiShuConfig.getFeiShuOpenApiHost() + api;
        try {
            HttpEntity<String> requestEntity = new HttpEntity<>(headers);
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, String.class, chatId);
            System.out.println(responseEntity.getBody());
            Type type = new TypeReference<FeiShuResultDTO>() {
            }.getType();
            FeiShuResultDTO feiShuResultDTO = JSONObject.parseObject(responseEntity.getBody(), type);
            return feiShuResultDTO.getData().getChatId();
        } catch (Exception e) {
            throw new ServiceException("飞书:" + api + "接口调用失败" + "\n" + e);
        }
    }

    /**
     * 群发消息
     * https://open.feishu.cn/document/ukTMukTMukTM/ucDO1EjL3gTNx4yN4UTM
     */
    public void sendBatchMsg(FeiShuBatchMsgDTO feiShuBatchMsgDTO) {
        String api = "/message/v4/batch_send/";
        RestTemplate restTemplate = new RestTemplate();
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + getTenantToken());
            headers.set("Content-Type", "application/json; charset=utf-8");
            HttpEntity<String> requestEntity = new HttpEntity<>(objectMapper.writeValueAsString(feiShuBatchMsgDTO), headers);
            String url = feiShuConfig.getFeiShuOpenApiHost() + api;

            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
            log.info("批量发送消息返回:{}", responseEntity);
        } catch (Exception e) {
            throw new ServiceException("飞书:" + api + "接口调用失败" + "\n" + e);
        }
    }

    /**
     * 单发消息
     * https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/message/create
     *
     * @param feiShuMsgDTO
     */
    public JSONObject sendMsg(FeiShuMsgDTO feiShuMsgDTO, String receiveIdType) {
        String api = "/im/v1/messages?receive_id_type={receiveIdType}";
        RestTemplate restTemplate = new RestTemplate();
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + getTenantToken());
            headers.set("Content-Type", "application/json; charset=utf-8");
            HttpEntity<String> requestEntity = new HttpEntity<>(objectMapper.writeValueAsString(feiShuMsgDTO), headers);
            String url = feiShuConfig.getFeiShuOpenApiHost() + api;
            log.info(requestEntity.toString());
            ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, requestEntity, JSONObject.class, receiveIdType);
            if (responseEntity.getBody().getJSONObject("data") == null) {
                return null;
            }
            log.info("消息发送成功,接收人: {}", feiShuMsgDTO.getReceiveId());
            return responseEntity.getBody();
        } catch (Exception e) {
            log.error("单发消息失败", e);
            throw new ServiceException("飞书:" + api + "接口调用失败" + "\n" + e);
        }
    }

    /**
     * 根据部门id查询部门信息
     * https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/contact-v3/department/get
     *
     * @param departmentId
     * @return
     */
    public FeiShuDepartmentDTO getDepartment(String departmentId) {
        String api = "/contact/v3/departments/{departmentId}";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + getTenantToken());
        headers.set("Content-Type", "application/json; charset=utf-8");
        HttpEntity<String> requestEntity = new HttpEntity<>(headers);
        String url = feiShuConfig.getFeiShuOpenApiHost() + api;
        try {
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class, departmentId);
            Type type = new TypeReference<FeiShuResultDTO>() {
            }.getType();
            FeiShuResultDTO feiShuResultDTO = JSONObject.parseObject(responseEntity.getBody(), type);
            return feiShuResultDTO.getData().getDepartment();
        } catch (Exception e) {
            throw new ServiceException("飞书:" + api + "接口调用失败" + "\n" + e);
        }
    }

    /**
     * 列出文档记录
     * https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/bitable-v1/app-table-record/list
     *
     * @param appToken
     * @param tableId
     * @return
     */
    public List getTableRecords(String appToken, String tableId) {
        String api = "/bitable/v1/apps/{app_token}/tables/{table_id}/records";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + getTenantToken());
        headers.set("Content-Type", "application/json; charset=utf-8");
        HttpEntity<String> requestEntity = new HttpEntity<>(headers);
        String url = feiShuConfig.getFeiShuOpenApiHost() + api;
        List list = new ArrayList();
        try {
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class, appToken, tableId);
            Type type = new TypeReference<FeiShuResultDTO<DocDTO<FieldsDTO>>>() {
            }.getType();
            FeiShuResultDTO feiShuResultDTO = JSONObject.parseObject(responseEntity.getBody(), type);
            list = feiShuResultDTO.getData().getItems();
            while (feiShuResultDTO.getData().getItems().size() >= 100) {
                ResponseEntity<String> next = restTemplate.exchange(url + "&page_token=" + feiShuResultDTO.getData().getPageToken(), HttpMethod.GET, requestEntity, String.class, appToken, tableId);
                feiShuResultDTO = JSONObject.parseObject(next.getBody(), type);
                list.addAll(feiShuResultDTO.getData().getItems());
            }
            return list;
        } catch (Exception e) {
            throw new ServiceException("飞书:" + api + "接口调用失败" + "\n" + e);
        }

    }


    /**
     * 更新记录
     *
     * @param appToken
     * @param tableId
     * @param recordId
     * @param docDTO
     * @return
     */
    public FeiShuResultDTO updateTableRecords(String appToken, String tableId, String recordId, DocDTO docDTO) {
        String api = "/bitable/v1/apps/{app_token}/tables/{table_id}/records/{record_id}";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + getTenantToken());
        headers.set("Content-Type", "application/json; charset=utf-8");

        HttpEntity<String> requestEntity = new HttpEntity<>(JSONObject.toJSONString(docDTO), headers);
        String url = feiShuConfig.getFeiShuOpenApiHost() + api;
        try {
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, requestEntity, String.class, appToken, tableId, recordId);
            FeiShuResultDTO feiShuResultDTO = JSONObject.parseObject(responseEntity.getBody(), FeiShuResultDTO.class);
            return feiShuResultDTO;
        } catch (Exception e) {
            throw new ServiceException("飞书:" + api + "接口调用失败" + "\n" + e);
        }

    }

    //获取主日历
    public JSONObject calendars() {
        //查询主日历,获取日历id
        String api = "/calendar/v4/calendars/primary?user_id_type=open_id";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + getTenantToken());
        headers.set("Content-Type", "application/json; charset=utf-8");
        HttpEntity<String> requestEntity = new HttpEntity<>(headers);
        String url = feiShuConfig.getFeiShuOpenApiHost() + api;
        try {
            ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, requestEntity, JSONObject.class);
            return responseEntity.getBody();
        } catch (Exception e) {
            log.error("飞书:" + api + "接口调用失败" + "\n" + e);
            throw new ServiceException("飞书:" + api + "接口调用失败" + "\n" + e);
        }
    }

}