package com.ads.common.dingTalk.service.impl;

import com.ads.business.service.TokenService;
import com.ads.common.dingTalk.config.AppConfig;
import com.ads.common.dingTalk.config.UrlConstant;
import com.ads.common.dingTalk.domain.DepartmentDTO;
import com.ads.common.dingTalk.domain.ServiceResult;
import com.ads.common.dingTalk.domain.UserDTO;
import com.ads.common.dingTalk.service.DingTalkService;
import com.ads.common.redis.RedisKeyConstant;
import com.ads.common.redis.RedisManager;
import com.ads.common.util.UtilConst;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.DingTalkConstants;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Return
 * @Author hou
 * @Date 2021/9/2 17:04
 * @Destription
 */

@Service
@Slf4j
public class DingTalkServiceImpl implements DingTalkService {


    @Autowired
    private AppConfig appConfig;

    @Resource
    private RedisManager redisManager;

    @Resource
    private TokenService tokenService;

    @Override
    public ServiceResult<String> getAccessToken() {
        log.info("调用钉钉api接口获取AccessToken");
        DefaultDingTalkClient client = new DefaultDingTalkClient(UrlConstant.URL_GET_TOKEN);
        OapiGettokenRequest request = new OapiGettokenRequest();
        OapiGettokenResponse response;

        request.setAppkey(appConfig.getAppKey());
        request.setAppsecret(appConfig.getAppSecret());
        request.setHttpMethod(DingTalkConstants.HTTP_METHOD_GET);

        try {
            response = client.execute(request);
            log.info("调用钉钉api接口获取AccessToken--response:{}", JSON.toJSONString(response));
        } catch (ApiException e) {
            log.error("getAccessToken failed", e);
            return ServiceResult.failure(e.getErrCode(), e.getErrMsg());
        }
        if (!response.isSuccess()) {
            return ServiceResult.failure(response.getErrorCode(), response.getErrmsg());
        }

        String accessToken = response.getAccessToken();
        redisManager.set(RedisKeyConstant.ACCESS_TOKEN, accessToken, UtilConst.ACCESS_TOKEN_EXPIRE);
        log.info("AccessToken:{}", accessToken);
        return ServiceResult.success(accessToken);
    }

    @Override
    public ServiceResult<String> getJsTicket(String accessToken) {
        log.info("调用钉钉api接口获取JSTicket,accessToken:{}", accessToken);
        DefaultDingTalkClient client = new DefaultDingTalkClient(UrlConstant.URL_GET_JSTICKET);
        OapiGetJsapiTicketRequest request = new OapiGetJsapiTicketRequest();
        OapiGetJsapiTicketResponse response;
        request.setHttpMethod(DingTalkConstants.HTTP_METHOD_GET);
        try {
            response = client.execute(request, accessToken);
            log.info("调用钉钉api接口获取JSTicket--response:{}", JSON.toJSONString(response));
        } catch (ApiException e) {
            log.error("getJsTicket failed", e);
            return ServiceResult.failure(e.getErrCode(), e.getErrMsg());
        }
        if (!response.isSuccess()) {
            return ServiceResult.failure(response.getErrorCode(), response.getErrmsg());
        }
        String ticket = response.getTicket();
        redisManager.set(RedisKeyConstant.JS_TICKET, ticket, UtilConst.ACCESS_TOKEN_EXPIRE);
        log.info("获取JSTicket:{}", ticket);
        return ServiceResult.success(ticket);
    }

    @Override
    public ServiceResult<String> getUserInfo(String accessToken, String authCode) {
        log.info("根据临时授权码调用钉钉api接口获取用户userId,accessToken:{},authCode:{}", accessToken, authCode);
        DingTalkClient client = new DefaultDingTalkClient(UrlConstant.URL_GET_USER_INFO);
        OapiUserGetuserinfoRequest request = new OapiUserGetuserinfoRequest();
        request.setCode(authCode);
        request.setHttpMethod(DingTalkConstants.HTTP_METHOD_GET);
        OapiUserGetuserinfoResponse response;
        try {
            response = client.execute(request, accessToken);
            log.info("调用钉钉api接口获取用户userId--response:{}", JSON.toJSONString(response));
        } catch (ApiException e) {
            log.error("Failed to getUserInfo", e);
            return ServiceResult.failure(e.getErrCode(), "Failed to getUserInfo: " + e.getErrMsg());
        }
        if (!response.isSuccess()) {
            return ServiceResult.failure(response.getErrorCode(), response.getErrmsg());
        }
        return ServiceResult.success(response.getUserid());
    }

    @Override
    public ServiceResult<UserDTO> getUser(String accessToken, String userId) {
        Object jsonUser = redisManager.get(RedisKeyConstant.PREFIX + userId);
        if (jsonUser != null){
            UserDTO user = JSON.parseObject(jsonUser.toString(), UserDTO.class);
            return ServiceResult.success(user);
        }

        log.info("根据userId调用钉钉api接口获用户信息，accessToken:{},userId:{}", accessToken, userId);

        DefaultDingTalkClient client = new DefaultDingTalkClient(UrlConstant.URL_USER_GET);
        OapiUserGetRequest request = new OapiUserGetRequest();
        request.setUserid(userId);
        request.setHttpMethod(DingTalkConstants.HTTP_METHOD_GET);
        OapiUserGetResponse response;
        try {
            response = client.execute(request, accessToken);
            log.info("调用钉钉api接口获用户信息--response:{}", JSON.toJSONString(response));
        } catch (ApiException e) {
            log.error("Failed to getUser", e);
            return ServiceResult.failure(e.getErrCode(), "Failed to getUser: " + e.getErrMsg());
        }
        if (!response.isSuccess()) {
            return ServiceResult.failure(response.getErrorCode(), response.getErrmsg());
        }
        UserDTO user = new UserDTO();
        user.setName(response.getName());
        user.setUserid(response.getUserid());
        user.setAvatar(response.getAvatar());
        user.setMobile(response.getMobile());
        user.setManagerUserid(StringUtils.isNotBlank(response.getManagerUserId()) ? response.getManagerUserId() : response.getUserid());
        if (CollectionUtils.isNotEmpty(response.getRoles())) {
            user.setRoleId(response.getRoles().get(0).getId());
            user.setRoleName(response.getRoles().get(0).getName());
        }
        if (CollectionUtils.isNotEmpty(response.getDepartment())) {
            ServiceResult<OapiDepartmentGetResponse> deptDetail = getDeptDetail(accessToken, response.getDepartment().get(0));
            if (deptDetail.isSuccess()) {
                user.setDeptName(deptDetail.getResult().getName());
            }
        }
        redisManager.set(RedisKeyConstant.PREFIX + user.getUserid(), JSONObject.toJSONString(user), 60 * 60L);
        return ServiceResult.success(user);
    }

    @Override
    public ServiceResult<List<DepartmentDTO>> getDepartmentList(String accessToken, String id) {
        log.info("根据上级部门id调用钉钉api查询部门列表，accessToken:{},id:{}", accessToken, id);
        DefaultDingTalkClient client = new DefaultDingTalkClient(UrlConstant.URL_DEPARTMENT_LIST);
        OapiDepartmentListRequest request = new OapiDepartmentListRequest();
        request.setId(id);
        request.setHttpMethod(DingTalkConstants.HTTP_METHOD_GET);
        OapiDepartmentListResponse response;
        try {
            response = client.execute(request, accessToken);
            log.info("调用钉钉api查询部门列表--response:{}", JSON.toJSONString(response));
        } catch (ApiException e) {
            log.error("Failed to getDepartmentList", e);
            return ServiceResult.failure(e.getErrCode(), "Failed to listDepartment: " + e.getErrMsg());
        }
        if (!response.isSuccess()) {
            return ServiceResult.failure(response.getErrorCode(), response.getErrmsg());
        }
        if (CollectionUtils.isNotEmpty(response.getDepartment())) {
            List<DepartmentDTO> results = new ArrayList<>(response.getDepartment().size());
            for (OapiDepartmentListResponse.Department department : response.getDepartment()) {
                DepartmentDTO departmentDTO = new DepartmentDTO();
                departmentDTO.setId(department.getId());
                departmentDTO.setName(department.getName());
                departmentDTO.setCreateDeptGroup(department.getCreateDeptGroup());
                departmentDTO.setAutoAddUser(department.getAutoAddUser());
                departmentDTO.setParentid(department.getParentid());
                results.add(departmentDTO);
            }
            return ServiceResult.success(results);
        }
        return ServiceResult.success(Collections.emptyList());
    }

    @Override
    public ServiceResult<List<UserDTO>> getDepartmentUsers(String accessToken, Long id, Long offset, Long size) {
        log.info("根据上级部门id调用钉钉api查询部门下用户列表，accessToken:{},id:{}", accessToken, id);
        DefaultDingTalkClient client = new DefaultDingTalkClient(UrlConstant.URL_USER_SIMPLELIST);
        OapiUserSimplelistRequest request = new OapiUserSimplelistRequest();
        request.setDepartmentId(id);
        request.setHttpMethod(DingTalkConstants.HTTP_METHOD_GET);
        if (offset > 0 & size > 0) {
            request.setOffset(offset);
            request.setSize(size);
        }
        OapiUserSimplelistResponse response;

        try {
            response = client.execute(request, accessToken);
            log.info("调用钉钉api查询部门下用户列表--response:{}", JSON.toJSONString(response));
        } catch (ApiException e) {
            log.error("Failed to getDepartmentUsers", e);
            return ServiceResult.failure(e.getErrCode(), "Failed to getDepartmentUsers: " + e.getErrMsg());
        }
        if (!response.isSuccess()) {
            return ServiceResult.failure(response.getErrorCode(), response.getErrmsg());
        }
        if (CollectionUtils.isNotEmpty(response.getUserlist())) {
            List<UserDTO> results = new ArrayList<>(response
                    .getUserlist().size());
            for (OapiUserSimplelistResponse.Userlist userlist : response.getUserlist()) {
                UserDTO user = new UserDTO();
                user.setUserid(userlist.getUserid());
                user.setName(userlist.getName());
                ServiceResult<UserDTO> user1 = getUser(accessToken, userlist.getUserid());
                if (user1.isSuccess() && !Objects.isNull(user1.getResult())) {
                    user.setMobile(user1.getResult().getMobile());
                }
                results.add(user);
            }
            return ServiceResult.success(results);
        }
        return ServiceResult.success(Collections.emptyList());
    }

    @Override
    public ServiceResult<List<OapiRoleListResponse.OpenRoleGroup>> getRoleList(String accessToken) {
        log.info("调用钉钉api查询角色列表，accessToken:{}", accessToken);
        DefaultDingTalkClient client = new DefaultDingTalkClient(UrlConstant.URL_USER_ROLE_LIST);
        OapiRoleListRequest request = new OapiRoleListRequest();
        request.setHttpMethod(DingTalkConstants.HTTP_METHOD_GET);
        OapiRoleListResponse response;
        try {
            response = client.execute(request, accessToken);
            log.info("调用钉钉api查询角色列表--response:{}", JSON.toJSONString(response));
        } catch (ApiException e) {
            log.error("Failed to getRoleList", e);
            return ServiceResult.failure(e.getErrCode(), "Failed to getRoleList: " + e.getErrMsg());
        }
        if (!response.isSuccess()) {
            return ServiceResult.failure(response.getErrorCode(), response.getErrmsg());
        }
        return ServiceResult.success(response.getResult().getList());
    }

    @Override
    public ServiceResult<List<OapiRoleSimplelistResponse.OpenEmpSimple>> getRoleUsers(String accessToken, Long roleId) {
        log.info("根据角色id调用钉钉api查询角色用户列表，accessToken:{}，roleId:{}", accessToken, roleId);
        DefaultDingTalkClient client = new DefaultDingTalkClient(UrlConstant.URL_USER_ROLE_SIMPLELIST);
        OapiRoleSimplelistRequest request = new OapiRoleSimplelistRequest();
        request.setRoleId(roleId);
        request.setHttpMethod(DingTalkConstants.HTTP_METHOD_GET);
        OapiRoleSimplelistResponse response;
        try {
            response = client.execute(request, accessToken);
            log.info("根据角色id调用钉钉api查询角色用户列表，response:{}", JSON.toJSONString(response));
        } catch (ApiException e) {
            log.error("Failed to getRoleUsers", e);
            return ServiceResult.failure(e.getErrCode(), "Failed to getRoleUsers: " + e.getErrMsg());
        }
        if (!response.isSuccess()) {
            return ServiceResult.failure(response.getErrorCode(), response.getErrmsg());
        }
        return ServiceResult.success(response.getResult().getList());
    }

    @Override
    public ServiceResult<OapiProcessSaveResponse.ProcessTopVo> saveProcess(String accessToken, OapiProcessSaveRequest.SaveProcessRequest request) {
        log.info("调用钉钉api创建审批模板,accessToken:{},request:{}", accessToken, JSON.toJSONString(request));
        request.setAgentid(appConfig.getAgentId());
        DefaultDingTalkClient client = new DefaultDingTalkClient(UrlConstant.URL_PROCESS_SAVE);
        OapiProcessSaveRequest saveRequest = new OapiProcessSaveRequest();
        saveRequest.setHttpMethod(DingTalkConstants.HTTP_METHOD_POST);
        saveRequest.setSaveProcessRequest(request);
        OapiProcessSaveResponse response;
        try {
            response = client.execute(saveRequest, accessToken);
            log.info("调用钉钉api创建审批模板,response:{}", JSON.toJSONString(response));
        } catch (ApiException e) {
            log.error("Failed to saveProcess", e);
            return ServiceResult.failure(e.getErrCode(), "Failed to saveProcess: " + e.getErrMsg());
        }
        if (!response.isSuccess()) {
            return ServiceResult.failure(response.getErrorCode(), response.getErrmsg());
        }
        return ServiceResult.success(response.getResult());
    }

    @Override
    public ServiceResult deleteProcess(String accessToken, OapiProcessDeleteRequest.DeleteProcessRequest request) {
        log.info("调用钉钉api删除审批模板,accessToken:{},request:{}", accessToken, JSON.toJSONString(request));
        DefaultDingTalkClient client = new DefaultDingTalkClient(UrlConstant.URL_PROCESS_DELETE);
        OapiProcessDeleteRequest deleteRequest = new OapiProcessDeleteRequest();
        deleteRequest.setRequest(JSON.toJSONString(request));
        deleteRequest.setHttpMethod(DingTalkConstants.HTTP_METHOD_POST);
        OapiProcessDeleteResponse response;
        try {
            response = client.execute(deleteRequest, accessToken);
            log.info("调用钉钉api删除审批模板,response:{}", JSON.toJSONString(response));
        } catch (ApiException e) {
            log.error("Failed to deleteProcess", e);
            return ServiceResult.failure(e.getErrCode(), "Failed to deleteProcess: " + e.getErrMsg());
        }
        if (!response.isSuccess()) {
            return ServiceResult.failure(response.getErrorCode(), response.getErrmsg());
        }
        return ServiceResult.success();
    }

    @Override
    public ServiceResult<OapiProcessWorkrecordCreateResponse.SaveFaceProcessInstanceResponse> createWorkRecord(String accessToken, OapiProcessWorkrecordCreateRequest.SaveFakeProcessInstanceRequest request) {
        log.info("根据模板code调用钉钉api创建审批实例,accessToken:{},request:{}", accessToken, JSON.toJSONString(request));
        request.setAgentid(appConfig.getAgentId());
        DefaultDingTalkClient client = new DefaultDingTalkClient(UrlConstant.URL_PROCESS_WORKRECORD_CREATE);
        OapiProcessWorkrecordCreateRequest createRequest = new OapiProcessWorkrecordCreateRequest();
        createRequest.setRequest(JSON.toJSONString(request));
        createRequest.setHttpMethod(DingTalkConstants.HTTP_METHOD_POST);
        OapiProcessWorkrecordCreateResponse response;
        try {
            response = client.execute(createRequest, accessToken);
            log.info("根据模板code调用钉钉api创建审批实例,response:{}", JSON.toJSONString(response));
        } catch (ApiException e) {
            log.error("Failed to createWorkRecord", e);
            return ServiceResult.failure(e.getErrCode(), "Failed to createWorkRecord: " + e.getErrMsg());
        }
        if (!response.isSuccess()) {
            return ServiceResult.failure(response.getErrorCode(), response.getErrmsg());
        }
        return ServiceResult.success(response.getResult());
    }

    @Override
    public ServiceResult updateWorkRecord(String accessToken, OapiProcessWorkrecordUpdateRequest.UpdateProcessInstanceRequest request) {
        log.info("调用钉钉api更新审批实例状态,accessToken:{},request:{}", accessToken, JSON.toJSONString(request));
        DefaultDingTalkClient client = new DefaultDingTalkClient(UrlConstant.URL_PROCESS_WORKRECORD_UPDATE);
        OapiProcessWorkrecordUpdateRequest updateRequest = new OapiProcessWorkrecordUpdateRequest();
        updateRequest.setRequest(JSON.toJSONString(request));
        updateRequest.setHttpMethod(DingTalkConstants.HTTP_METHOD_POST);
        OapiProcessWorkrecordUpdateResponse response;
        try {
            response = client.execute(updateRequest, accessToken);
            log.info("调用钉钉api更新审批实例状态,response:{}", JSON.toJSONString(response));
        } catch (ApiException e) {
            log.error("Failed to updateWorkRecord", e);
            return ServiceResult.failure(e.getErrCode(), "Failed to updateWorkRecord: " + e.getErrMsg());
        }
        if (!response.isSuccess()) {
            return ServiceResult.failure(response.getErrorCode(), response.getErrmsg());
        }
        return ServiceResult.success();
    }

    @Override
    public ServiceResult batchUpdateWorkRecord(String accessToken, OapiProcessWorkrecordBatchupdateRequest.BatchUpdateProcessInstanceRequest request) {
        log.info("调用钉钉api批量更新审批实例状态,accessToken:{},request:{}", accessToken, JSON.toJSONString(request));
        DefaultDingTalkClient client = new DefaultDingTalkClient(UrlConstant.URL_PROCESS_WORKRECORD_BATCH_UPDATE);
        OapiProcessWorkrecordBatchupdateRequest updateRequest = new OapiProcessWorkrecordBatchupdateRequest();
        updateRequest.setRequest(JSON.toJSONString(request));
        updateRequest.setHttpMethod(DingTalkConstants.HTTP_METHOD_POST);
        OapiProcessWorkrecordBatchupdateResponse response;
        try {
            response = client.execute(updateRequest, accessToken);
            log.info("调用钉钉api批量更新审批实例状态,response:{}", JSON.toJSONString(response));
        } catch (ApiException e) {
            log.error("Failed to batchUpdateWorkRecord", e);
            return ServiceResult.failure(e.getErrCode(), "Failed to batchUpdateWorkRecord: " + e.getErrMsg());
        }
        if (!response.isSuccess()) {
            return ServiceResult.failure(response.getErrorCode(), response.getErrmsg());
        }
        return ServiceResult.success();
    }

    @Override
    public ServiceResult<OapiDepartmentGetResponse> getDeptDetail(String accessToken, Long deptId) {
        log.info("调用钉钉api查询部门详情,accessToken:{},id:{}", accessToken, deptId);
        DefaultDingTalkClient client = new DefaultDingTalkClient(UrlConstant.URL_DEPT_DETAIL);
        OapiDepartmentGetRequest request = new OapiDepartmentGetRequest();
        request.setHttpMethod(DingTalkConstants.HTTP_METHOD_GET);
        request.setId(deptId.toString());
        OapiDepartmentGetResponse response = new OapiDepartmentGetResponse();

        try {
            response = client.execute(request, accessToken);
            log.info("调用钉钉api查询部门详情,response:{}", JSON.toJSONString(response));
        } catch (ApiException e) {
            log.error("Failed to getDeptDetail", e);
            return ServiceResult.failure(e.getErrCode(), "Failed to getDeptDetail: " + e.getErrMsg());
        }
        if (!response.isSuccess()) {
            return ServiceResult.failure(response.getErrorCode(), response.getErrmsg());
        }
        return ServiceResult.success(response);
    }

    @Override
    public ServiceResult sendDingMessage(String accessToken, OapiMessageCorpconversationAsyncsendV2Request request) {
        log.info("发送钉钉工作消息通知 request:{}", JSON.toJSONString(request));
        DefaultDingTalkClient client = new DefaultDingTalkClient(UrlConstant.URL_SEND_MESSAGE);
        request.setHttpMethod(DingTalkConstants.HTTP_METHOD_POST);
        request.setAgentId(appConfig.getAgentId());
        OapiMessageCorpconversationAsyncsendV2Response response;
        try {
            response = client.execute(request, accessToken);
            log.info("发送钉钉工作消息通知 response:{}", JSON.toJSONString(response));
        } catch (ApiException e) {
            log.error("Failed to sendDingMessage", e);
            return ServiceResult.failure(e.getErrCode(), "Failed to sendDingMessage: " + e.getErrMsg());
        }
        return ServiceResult.success(response);
    }

    @Override
    public ServiceResult<OapiWorkrecordAddResponse> addWorkRecord(String accessToken, OapiWorkrecordAddRequest request) {
        log.info("发送钉钉待办消息 request:{}", JSON.toJSONString(request));
        DefaultDingTalkClient client = new DefaultDingTalkClient(UrlConstant.WORK_RECORD_ADD);
        request.setHttpMethod(DingTalkConstants.HTTP_METHOD_POST);
        OapiWorkrecordAddResponse response;
        try {
            response = client.execute(request, accessToken);
            log.info("发送钉钉待办消息 response:{}", JSON.toJSONString(response));
        } catch (ApiException e) {
            log.error("Failed to addWorkRecord", e);
            return ServiceResult.failure(e.getErrCode(), "Failed to addWorkRecord: " + e.getErrMsg());
        }
        return ServiceResult.success(response);
    }

    @Override
    public ServiceResult workRecordUpdate(String accessToken, OapiWorkrecordUpdateRequest request) {
        log.info("更新钉钉待办消息状态 request:{}", JSON.toJSONString(request));
        DefaultDingTalkClient client = new DefaultDingTalkClient(UrlConstant.WORK_RECORD_UPDATE);
        request.setHttpMethod(DingTalkConstants.HTTP_METHOD_POST);
        OapiWorkrecordUpdateResponse response;
        try {
            response = client.execute(request, accessToken);
            log.info("更新钉钉待办消息状态 response:{}", JSON.toJSONString(response));
        } catch (ApiException e) {
            log.error("Failed to updateWorkRecord", e);
            return ServiceResult.failure(e.getErrCode(), "Failed to updateWorkRecord: " + e.getErrMsg());
        }
        return ServiceResult.success();
    }

    @Override
    public ServiceResult<OapiWorkrecordGetbyuseridResponse.PageResult> getWorkRecordByUserId(String accessToken, OapiWorkrecordGetbyuseridRequest request) {
        log.info("查询钉钉用户待办任务列表 request:{}", JSON.toJSONString(request));
        DefaultDingTalkClient client = new DefaultDingTalkClient(UrlConstant.WORK_RECORD_GET_INFO);
        request.setHttpMethod(DingTalkConstants.HTTP_METHOD_POST);
        OapiWorkrecordGetbyuseridResponse response;
        try {
            response = client.execute(request, accessToken);
            log.info("查询钉钉用户待办任务列表 response:{}", JSON.toJSONString(response));
        } catch (ApiException e) {
            log.error("Failed to getWorkRecordByUserId", e);
            return ServiceResult.failure(e.getErrCode(), "Failed to getWorkRecordByUserId: " + e.getErrMsg());
        }
        return ServiceResult.success(response.getRecords());
    }

    @Override
    public ServiceResult<OapiChatCreateResponse> create(OapiChatCreateRequest request) {
        String accessToken = tokenService.getAccessToken();
        log.info("调用钉钉api创建群会话，accessToken:{},request:{}", accessToken, JSON.toJSONString(request));
        DefaultDingTalkClient client = new DefaultDingTalkClient(UrlConstant.CREATE_CHAT);
        OapiChatCreateResponse response;
        try {
            response = client.execute(request, accessToken);
        } catch (ApiException e) {
            log.error("Failed to create chat", e);
            return ServiceResult.failure(e.getErrCode(), "Failed to create chat: " + e.getErrMsg());
        }
        if (!response.isSuccess()) {
            return ServiceResult.failure(response.getErrorCode(), response.getErrmsg());
        }
        return ServiceResult.success(response);
    }

    @Override
    public ServiceResult<OapiV2UserGetbymobileResponse> getbymobile(String mobile) {
        String accessToken = tokenService.getAccessToken();
        log.info("调用钉钉api获取userid，accessToken:{},mobile:{}", accessToken, mobile);
        DefaultDingTalkClient client = new DefaultDingTalkClient(UrlConstant.GET_USERID);
        OapiV2UserGetbymobileRequest request = new OapiV2UserGetbymobileRequest();
        request.setMobile(mobile);
        OapiV2UserGetbymobileResponse response;
        try {
            response = client.execute(request, accessToken);
        } catch (ApiException e) {
            log.error("Failed to get userid by mobile", e);
            return ServiceResult.failure(e.getErrCode(), "Failed to get userid by mobile: " + e.getErrMsg());
        }
        if (!response.isSuccess()) {
            return ServiceResult.failure(response.getErrorCode(), response.getErrmsg());
        }
        return ServiceResult.success(response);
    }

    @Override
    public ServiceResult<OapiChatGetResponse> getChatInfo(String chatId) {
        String accessToken = tokenService.getAccessToken();
        log.info("调用钉钉api获取群会话信息，accessToken:{},chatId:{}", accessToken, chatId);
        DefaultDingTalkClient client = new DefaultDingTalkClient(UrlConstant.GET_CHAT_INFO);
        OapiChatGetRequest request = new OapiChatGetRequest();
        request.setChatid(chatId);
        OapiChatGetResponse response;
        try {
            response = client.execute(request, accessToken);
        } catch (ApiException e) {
            log.error("Failed to get chat info by chatid", e);
            return ServiceResult.failure(e.getErrCode(), "Failed to get chat info by chatid: " + e.getErrMsg());
        }
        if (!response.isSuccess()) {
            return ServiceResult.failure(response.getErrorCode(), response.getErrmsg());
        }
        return ServiceResult.success(response);
    }
}
