package com.tzld.piaoquan.api.service.wecom.thirdparty.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.stuuudy.commons.external.filestorage.enums.EnumFileType;
import com.stuuudy.commons.external.filestorage.enums.EnumPublicBuckets;
import com.tzld.piaoquan.api.common.enums.ExceptionEnum;
import com.tzld.piaoquan.api.common.enums.wecom.ThirdPartWeComStaffStatusEnum;
import com.tzld.piaoquan.api.common.exception.CommonException;
import com.tzld.piaoquan.api.component.WeComThirdPartyApiClient;
import com.tzld.piaoquan.api.dao.mapper.wecom.thirdpart.ThirdPartWeComCorpMapper;
import com.tzld.piaoquan.api.dao.mapper.wecom.thirdpart.ThirdPartWeComRoomMapper;
import com.tzld.piaoquan.api.dao.mapper.wecom.thirdpart.ThirdPartWeComStaffMapper;
import com.tzld.piaoquan.api.dao.mapper.wecom.thirdpart.ext.ThirdPartWeComMapperExt;
import com.tzld.piaoquan.api.job.wecom.thirdpart.WeComUserDetailJob;
import com.tzld.piaoquan.api.model.param.wecom.thirdpart.*;
import com.tzld.piaoquan.api.model.po.wecom.thirdpart.*;
import com.tzld.piaoquan.api.service.wecom.thirdparty.WeComThirdPartyService;
import com.tzld.piaoquan.api.util.AliOssFileTool;
import com.tzld.piaoquan.growth.common.dao.mapper.CorpMapper;
import com.tzld.piaoquan.growth.common.model.po.Corp;
import com.tzld.piaoquan.growth.common.model.po.CorpExample;
import com.tzld.piaoquan.growth.common.utils.DateUtil;
import com.tzld.piaoquan.growth.common.utils.LarkRobotUtil;
import com.tzld.piaoquan.growth.common.utils.RandomUtil;
import com.tzld.piaoquan.growth.common.utils.RedisUtils;
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.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;

@Slf4j
@Service
public class WeComThirdPartyServiceImpl implements WeComThirdPartyService {

    @Autowired
    private WeComThirdPartyApiClient apiClient;
    @Autowired
    private WeComUserDetailJob weComUserDetailJob;
    @Autowired
    private ThirdPartWeComStaffMapper thirdPartWeComStaffMapper;
    @Autowired
    private ThirdPartWeComRoomMapper thirdPartWeComRoomMapper;
    @Autowired
    private ThirdPartWeComCorpMapper thirdPartWeComCorpMapper;
    @Autowired
    private ThirdPartWeComMapperExt weComMapperExt;
    @Autowired
    private CorpMapper corpMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Value("${wecom.thirdpart.callback.url:https://test-tp-open.piaoquantv.com/wecom/thirdparty/callback}")
    private String callbackUrl;

    @Override
    public InitResponse init(InitRequest request) {
        if (Objects.isNull(request)) {
            request = new InitRequest();
        }
        request.setProxySituation(0);
        request.setDeverType("ipad");
        String response = apiClient.init(request);
        CommonResponse<InitResponse> commonResponse =
                JSONObject.parseObject(response, new TypeReference<CommonResponse<InitResponse>>() {});
        if (commonResponse.getErrcode() != 0) {
            log.error("WeComThirdPartyService init failed, request: {}, response: {}", request, response);
            return null;
        }
        return commonResponse.getData();
    }

    @Override
    public void setCallbackUrl(SetCallbackUrlRequest request) {
        apiClient.setCallbackUrl(request);
    }

    @Override
    public QrCodeResponse getQrCode(UuidRequest request) {
        String response = apiClient.getQrCode(request);
        CommonResponse<QrCodeResponse> commonResponse =
                JSONObject.parseObject(response, new TypeReference<CommonResponse<QrCodeResponse>>() {});
        if (commonResponse.getErrcode() != 0) {
            log.error("WeComThirdPartyService get qr code failed, request: {}, response: {}", request, response);
            return null;
        }
        apiClient.setCallbackUrl(new SetCallbackUrlRequest(request.getUuid(), callbackUrl));
        return commonResponse.getData();
    }

    @Override
    public void setCheckCode(CheckCodeRequest request) {
        apiClient.checkCode(request);
    }

    @Override
    public String secondaryValidation(UuidRequest request) {
        String response = apiClient.secondaryValidation(request);
        CommonResponse<SecondaryValidationResponse> commonResponse =
                JSONObject.parseObject(response, new TypeReference<CommonResponse<SecondaryValidationResponse>>() {});
        if (commonResponse.getErrcode() != 0) {
            log.error("WeComThirdPartyService secondary validation failed, request: {}, response: {}", request, response);
            return null;
        }
        return commonResponse.getData().getQrcode();
    }

    @Override
    public LoginInfo getRunClientByUuid(UuidRequest request) {
        String response = apiClient.getRunClientByUuid(request);
        CommonResponse<LoginInfo> commonResponse =
                JSONObject.parseObject(response, new TypeReference<CommonResponse<LoginInfo>>() {});
        if (commonResponse.getErrcode() != 0) {
            log.error("WeComThirdPartyService get run client by uuid failed, request: {}, response: {}", request, response);
            return null;
        }
        new Thread(() -> saveStaffDetail(commonResponse.getData())).start();
        return commonResponse.getData();
    }

    private void saveStaffDetail(LoginInfo data) {
        if (Objects.isNull(data)) {
            return;
        }
        String uuid = data.getUuid();
        LoginInfo.UserInfo userInfo = data.getUser_info();
        if (Objects.isNull(userInfo)) {
            return;
        }
        LoginInfo.UserObject userObject = userInfo.getObject();
        if (Objects.isNull(userObject)) {
            return;
        }
        Corp corp = getCorpByName(userObject.getCorp_name());
        ThirdPartWeComCorp existCorp = getExistCorpByThirdCorpId(userObject.getCorp_id());
        if (Objects.isNull(existCorp)) {
            existCorp = new ThirdPartWeComCorp();
            existCorp.setThirdCorpId(userObject.getCorp_id());
            existCorp.setName(userObject.getCorp_name());
            if (Objects.nonNull(corp)) {
                existCorp.setCorpId(corp.getId());
            }
            thirdPartWeComCorpMapper.insertSelective(existCorp);
        } else {
            if (Objects.nonNull(corp)) {
                existCorp.setCorpId(corp.getId());
            }
            existCorp.setName(userObject.getCorp_name());
            thirdPartWeComCorpMapper.updateByPrimaryKeySelective(existCorp);
        }
        ThirdPartWeComStaff existStaff = getExistStaffByThirdStaffId(userObject.getUser_id());
        if (Objects.isNull(existStaff)) {
            existStaff = new ThirdPartWeComStaff();
            existStaff.setThirdStaffId(userObject.getUser_id());
            existStaff.setCorpId(existCorp.getId());
            existStaff.setName(userObject.getNickname());
            existStaff.setRealName(userObject.getRealname());
            existStaff.setMobile(userObject.getMobile());
            existStaff.setAvatar(userObject.getAvatar());
            existStaff.setThirdStaffId(userObject.getUser_id());
            existStaff.setThirdUuid(uuid);
            thirdPartWeComStaffMapper.insertSelective(existStaff);
        } else {
            existStaff.setCorpId(existCorp.getId());
            existStaff.setName(userObject.getNickname());
            existStaff.setRealName(userObject.getRealname());
            existStaff.setMobile(userObject.getMobile());
            existStaff.setAvatar(userObject.getAvatar());
            existStaff.setThirdUuid(uuid);
            existStaff.setStatus(ThirdPartWeComStaffStatusEnum.NORMAL.getVal());
            existStaff.setUpdateTime(new Date());
            thirdPartWeComStaffMapper.updateByPrimaryKeySelective(existStaff);
        }
        saveStaffQrCode(uuid);

        // 同步用户详情
        ThirdPartWeComStaff staff = getStaffByUuid(uuid);
        weComUserDetailJob.syncStaffUserDetail(staff);

        // 清除掉线检测
        String offLineKey = "wecom:thirdpart:offline:" + uuid;
        redisUtils.del(offLineKey);
    }

    @Override
    public void saveStaffQrCode(String uuid) {
        // 获取名片二维码
        String response = apiClient.getExternalBusinessCard(new UuidRequest(uuid));
        CommonResponse<ExternalBusinessCardResponse> cardCommonResponse =
                JSONObject.parseObject(response, new TypeReference<CommonResponse<ExternalBusinessCardResponse>>() {});
        // base64 to inputStream
        ExternalBusinessCardResponse cardResponse = cardCommonResponse.getData();
        if (Objects.isNull(cardResponse)) {
            return;
        }
        String qrImageBase64 = cardResponse.getQr_image();
        if (StringUtils.isBlank(qrImageBase64)) {
            return;
        }
        byte[] bytes = Base64.getDecoder().decode(qrImageBase64);
        InputStream inputStream = new ByteArrayInputStream(bytes);
        String fileUri = "temp/" + System.currentTimeMillis() + "_" + RandomUtil.generate18String() + ".png";
        String qrImage = AliOssFileTool.saveInPublicReturnHost(inputStream, EnumPublicBuckets.PUBBUCKET, fileUri, EnumFileType.PICTURE);
        weComMapperExt.updateStaffQrImageByUuid(uuid, qrImage);
    }

    private Corp getCorpByName(String corpName) {
        CorpExample example = new CorpExample();
        example.createCriteria().andNameEqualTo(corpName);
        List<Corp> list = corpMapper.selectByExample(example);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    private ThirdPartWeComStaff getExistStaffByThirdStaffId(Long userId) {
        ThirdPartWeComStaffExample example = new ThirdPartWeComStaffExample();
        example.createCriteria().andThirdStaffIdEqualTo(userId);
        List<ThirdPartWeComStaff> list = thirdPartWeComStaffMapper.selectByExample(example);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    private ThirdPartWeComCorp getExistCorpByThirdCorpId(Long thirdCorpId) {
        ThirdPartWeComCorpExample example = new ThirdPartWeComCorpExample();
        example.createCriteria().andThirdCorpIdEqualTo(thirdCorpId);
        List<ThirdPartWeComCorp> list = thirdPartWeComCorpMapper.selectByExample(example);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public List<ThirdPartWeComCorp> getCorpListByIds(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Collections.emptyList();
        }
        ThirdPartWeComCorpExample example = new ThirdPartWeComCorpExample();
        example.createCriteria().andIdIn(ids);
        List<ThirdPartWeComCorp> list = thirdPartWeComCorpMapper.selectByExample(example);
        if (list.isEmpty()) {
            return null;
        }
        return list;
    }

    @Override
    public List<GetInnerContactsResponse.ContactItem> getInnerContacts(GetInnerContactsRequest request) {
        List<GetInnerContactsResponse.ContactItem> result = new ArrayList<>();
        String seq = null;
        do {
            if (StringUtils.isBlank(seq)) {
                request.setStrSeq("");
            } else {
                request.setStrSeq(seq);
            }
            String response = apiClient.getInnerContacts(request);
            CommonResponse<GetInnerContactsResponse> commonResponse =
                    JSONObject.parseObject(response, new TypeReference<CommonResponse<GetInnerContactsResponse>>() {});
            if (commonResponse.getErrcode() != 0) {
                log.error("WeComThirdPartyService get inner contacts failed, request: {}, response: {}", request, response);
                return result;
            }
            result.addAll(commonResponse.getData().getList());
            seq = commonResponse.getData().getSeq();
        } while (StringUtils.isNotBlank(seq));
        return result;
    }

    @Override
    public List<ExternalContactsResponse.ContactItem> getExternalContacts(GetExternalContactsRequest request) {
        List<ExternalContactsResponse.ContactItem> result = new ArrayList<>();
        Integer seq = null;
        do {
            if (Objects.isNull(seq)) {
                request.setSeq(0);
            } else {
                request.setSeq(seq);
            }
            String response = apiClient.getExternalContacts(request);
            CommonResponse<ExternalContactsResponse> commonResponse =
                    JSONObject.parseObject(response, new TypeReference<CommonResponse<ExternalContactsResponse>>() {});
            if (commonResponse.getErrcode() != 0) {
                log.error("WeComThirdPartyService get external contacts failed, request: {}, response: {}", request, response);
                return result;
            }
            result.addAll(commonResponse.getData().getList());
            seq = commonResponse.getData().getSeq();
        } while (Objects.nonNull(seq));
        return result;
    }

    @Override
    public List<GetChatroomMembersResponse.RoomInfo> getChatroomMembers(GetChatroomMembersRequest request) {
        List<GetChatroomMembersResponse.RoomInfo> result = new ArrayList<>();
        Integer startIndex = null;
        do {
            if (Objects.isNull(startIndex)) {
                request.setStar_index(0);
            } else {
                request.setStar_index(startIndex);
            }
            String response = apiClient.getChatroomMembers(request);
            CommonResponse<GetChatroomMembersResponse> commonResponse =
                    JSONObject.parseObject(response, new TypeReference<CommonResponse<GetChatroomMembersResponse>>() {});
            if (commonResponse.getErrcode() != 0) {
                log.error("WeComThirdPartyService get chatroom members failed, request: {}, response: {}", request, response);
                return result;
            }
            result.addAll(commonResponse.getData().getRoomList());
            startIndex = commonResponse.getData().getNext_start();
        } while (Objects.nonNull(startIndex) && startIndex > 0);
        return result;
    }

    @Override
    public List<GetRoomUserListResponse.Member> getRoomUserList(GetRoomUserListRequest request) {
        List<GetRoomUserListResponse.Member> result = new ArrayList<>();
        String response = apiClient.getRoomUserList(request);
        CommonResponse<GetRoomUserListResponse> commonResponse =
                JSONObject.parseObject(response, new TypeReference<CommonResponse<GetRoomUserListResponse>>() {});
        if (commonResponse.getErrcode() != 0) {
            log.error("WeComThirdPartyService get room user list failed, request: {}, response: {}", request, response);
            return result;
        }
        result.addAll(commonResponse.getData().getMember_list());
        return result;
    }

    @Override
    public CdnUploadImgLinkResponse cdnUploadImgLink(CdnUploadImgLinkRequest request) {
        int retryCount = 3;
        while (retryCount > 0) {
            String response = apiClient.cdnUploadImgLink(request);
            CommonResponse<CdnUploadImgLinkResponse> commonResponse =
                    JSONObject.parseObject(response, new TypeReference<CommonResponse<CdnUploadImgLinkResponse>>() {});
            if (commonResponse.getErrcode() == 0) {
                return commonResponse.getData();
            } else {
                log.error("WeComThirdPartyService cdn upload img link failed, request: {}, response: {}", request, response);
            }
            retryCount--;
        }
        return null;
    }

    @Override
    public CommonResponse<SendAppMsgResponse> sendAppMsg(ThirdPartWeComStaff staff, ThirdPartWeComRoom room, SendAppMsgRequest request) {
        String response = apiClient.sendAppMsg(request);
        CommonResponse<SendAppMsgResponse> commonResponse =
                JSONObject.parseObject(response, new TypeReference<CommonResponse<SendAppMsgResponse>>() {});
        if (commonResponse.getErrcode() != 0) {
            LarkRobotUtil.sendWeComThirdPartMessage(
                    "【发送应用消息失败通知】\n" +
                            "账号名称：" + staff.getName() + "\n" +
                            "群名：" + room.getName() + "\n" +
                            "错误码：" + commonResponse.getErrcode() + "\n" +
                            "错误信息：" + commonResponse.getErrmsg());
            log.error("WeComThirdPartyService send app msg failed, request: {}, response: {}", request, response);
        }
        return commonResponse;
    }

    @Override
    public CommonResponse<SendTextMsgResponse> sendTextMsg(ThirdPartWeComStaff staff, ThirdPartWeComRoom room, SendTextMsgRequest request) {
        String response = apiClient.sendTextMsg(request);
        CommonResponse<SendTextMsgResponse> commonResponse =
                JSONObject.parseObject(response, new TypeReference<CommonResponse<SendTextMsgResponse>>() {});
        if (commonResponse.getErrcode() != 0) {
            LarkRobotUtil.sendWeComThirdPartMessage(
                    "【发送应用消息失败通知】\n" +
                            "账号名称：" + staff.getName() + "\n" +
                            "群名：" + room.getName() + "\n" +
                            "错误码：" + commonResponse.getErrcode() + "\n" +
                            "错误信息：" + commonResponse.getErrmsg());
            log.error("WeComThirdPartyService send text msg failed, request: {}, response: {}", request, response);
        }
        return commonResponse;
    }

    @Override
    public List<ThirdPartWeComStaff> getActiveStaffList() {
        ThirdPartWeComStaffExample example = new ThirdPartWeComStaffExample();
        example.createCriteria().andStatusEqualTo(ThirdPartWeComStaffStatusEnum.NORMAL.getVal());
        return thirdPartWeComStaffMapper.selectByExample(example);
    }

    @Override
    public List<ThirdPartWeComRoom> getAllStaffRoomList(Long staffId) {
        ThirdPartWeComRoomExample example = new ThirdPartWeComRoomExample();
        example.createCriteria().andStaffIdEqualTo(staffId);
        return thirdPartWeComRoomMapper.selectByExample(example);
    }

    @Override
    public List<ThirdPartWeComRoom> getStaffRoomList(Long staffId) {
        ThirdPartWeComRoomExample example = new ThirdPartWeComRoomExample();
        example.createCriteria().andStaffIdEqualTo(staffId).andIsDeleteEqualTo(0);
        return thirdPartWeComRoomMapper.selectByExample(example);
    }

    @Override
    public CreateRoomWxResponse createRoom(CreateRoomWxRequest request) {
        String response = apiClient.createRoomWx(request);
        CommonResponse<CreateRoomWxResponse> commonResponse =
                JSONObject.parseObject(response, new TypeReference<CommonResponse<CreateRoomWxResponse>>() {});
        if (commonResponse.getErrcode() != 0) {
            log.error("WeComThirdPartyService create room failed, request: {}, response: {}", request, response);
            ThirdPartWeComStaff staff = getStaffByUuid(request.getUuid());
            LarkRobotUtil.sendWeComThirdPartMessage(
                    "【建群失败通知】\n" +
                            "账号UUID：" + request.getUuid() + "\n" +
                            "账号名称：" + (Objects.nonNull(staff) ? staff.getName() : "") + "\n" +
                            "群名称：" + request.getRoomName() + "\n" +
                            "邀请用户：" + request.getVids() + "\n" +
                            "错误信息：" + response);
            return null;
        }
        return commonResponse.getData();
    }

    @Override
    public void updateRoomName(UpdateRoomNameRequest request) {
        String response = apiClient.updateRoomName(request);
        CommonResponse<UpdateRoomNameResponse> commonResponse =
                JSONObject.parseObject(response, new TypeReference<CommonResponse<UpdateRoomNameResponse>>() {});
        if (commonResponse.getErrcode() != 0) {
            log.error("WeComThirdPartyService updateRoomName failed, request: {}, response: {}", request, response);
        }
    }

    @Override
    public List<AntiSpamRuleResponse.AntiSpamRule> queryCRMAntiSpamRule(QueryCRMAntiSpamRuleRequest request) {
        List<AntiSpamRuleResponse.AntiSpamRule> result = new ArrayList<>();
        String lastIndexInfo = "";
        do {
            request.setLastIndexInfo(lastIndexInfo);
            String response = apiClient.queryCRMAntiSpamRule(request);
            CommonResponse<AntiSpamRuleResponse> commonResponse =
                    JSONObject.parseObject(response, new TypeReference<CommonResponse<AntiSpamRuleResponse>>() {});
            if (commonResponse.getErrcode() != 0) {
                log.error("WeComThirdPartyService query crm AntiSpamRule failed, request: {}, response: {}", request, response);
                return result;
            }
            result.addAll(commonResponse.getData().getList());
            if (commonResponse.getData().getIs_end()) {
                break;
            }
            lastIndexInfo = commonResponse.getData().getLast_index_infoo();
        } while (true);
        return result;
    }

    @Override
    public void updateRoomSendStatus(UpdateRoomSendStatusRequest request) {
        ThirdPartWeComStaff staff = getStaffByName(request.getStaffName());
        if (Objects.isNull(staff)) {
            throw new CommonException(ExceptionEnum.THIRD_PART_STAFF_NOT_FOUND);
        }
        ThirdPartWeComRoomExample example = new ThirdPartWeComRoomExample();
        example.createCriteria().andStaffIdEqualTo(staff.getId()).andNameEqualTo(request.getRoomName());
        List<ThirdPartWeComRoom> roomList = thirdPartWeComRoomMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(roomList)) {
            throw new CommonException(ExceptionEnum.THIRD_PART_ROOM_NOT_FOUND);
        }
        for (ThirdPartWeComRoom room : roomList) {
            room.setSendStatus(request.getSendStatus());
            if (CollectionUtils.isNotEmpty(request.getSendTimeList())) {
                room.setSendTime(JSONObject.toJSONString(request.getSendTimeList()));
            }
            thirdPartWeComRoomMapper.updateByPrimaryKeySelective(room);
        }
    }

    private ThirdPartWeComStaff getStaffByName(String staffName) {
        ThirdPartWeComStaffExample example = new ThirdPartWeComStaffExample();
        example.createCriteria().andNameEqualTo(staffName);
        List<ThirdPartWeComStaff> staffList = thirdPartWeComStaffMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(staffList)) {
            return null;
        }
        return staffList.get(0);
    }

    @Override
    public Long getTodayCreateRoomCount(Long staffId) {
        Date todayStart = DateUtil.getTodayStartDate();
        ThirdPartWeComRoomExample example = new ThirdPartWeComRoomExample();
        example.createCriteria().andStaffIdEqualTo(staffId).andCreateTimeBetween(todayStart, new Date());
        return thirdPartWeComRoomMapper.countByExample(example);
    }

    @Override
    public CommonResponse<String> invitationToRoom(InvitationToRoomRequest request) {
        String res = apiClient.invitationToRoom(request);
        CommonResponse<String> commonResponse = JSONObject.parseObject(res, new TypeReference<CommonResponse<String>>() {});
        if (commonResponse.getErrcode() != 0) {
            log.error("WeComThirdPartyService invitationToRoom error, roomId: {}, vids: {}, errMsg: {}",
                    request.getRoomid(), request.getVids(), commonResponse.getErrmsg());
            ThirdPartWeComStaff staff = getStaffByUuid(request.getUuid());
            ThirdPartWeComRoom room = getRoomByThirdRoomId(request.getRoomid());
            LarkRobotUtil.sendWeComThirdPartMessage(
                    "【邀请群成员失败通知】\n" +
                            "账号UUID：" + request.getUuid() + "\n" +
                            "账号名称：" + (Objects.nonNull(staff) ? staff.getName() : "") + "\n" +
                            "群ID：" + request.getRoomid() + "\n" +
                            "群名称：" + (Objects.nonNull(room) ? room.getName() : "") + "\n" +
                            "邀请用户：" + request.getVids() + "\n" +
                            "错误信息：" + res);
            return null;
        }
        return commonResponse;
    }

    @Override
    public ThirdPartWeComRoom getRoomByThirdRoomId(Long roomId) {
        ThirdPartWeComRoomExample example = new ThirdPartWeComRoomExample();
        example.createCriteria().andThirdRoomIdEqualTo(String.valueOf(roomId));
        List<ThirdPartWeComRoom> roomList = thirdPartWeComRoomMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(roomList)) {
            return null;
        }
        return roomList.get(0);
    }

    @Override
    public List<ThirdPartWeComRoom> getRoomByRoomIds(List<Long> roomIds) {
        if (CollectionUtils.isEmpty(roomIds)) {
            return Collections.emptyList();
        }
        ThirdPartWeComRoomExample example = new ThirdPartWeComRoomExample();
        example.createCriteria().andIdIn(roomIds);
        return thirdPartWeComRoomMapper.selectByExample(example);
    }

    @Override
    public ThirdPartWeComStaff getStaffById(Long id) {
        return thirdPartWeComStaffMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<ThirdPartWeComStaff> getStaffByIds(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Collections.emptyList();
        }
        ThirdPartWeComStaffExample example = new ThirdPartWeComStaffExample();
        example.createCriteria().andIdIn(ids);
        return thirdPartWeComStaffMapper.selectByExample(example);
    }

    @Override
    public ThirdPartWeComStaff getStaffByUuid(String uuid) {
        ThirdPartWeComStaffExample example = new ThirdPartWeComStaffExample();
        example.createCriteria().andThirdUuidEqualTo(uuid);
        List<ThirdPartWeComStaff> staffList = thirdPartWeComStaffMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(staffList)) {
            return null;
        }
        return staffList.get(0);
    }

    @Override
    public List<ThirdPartWeComStaff> getStaffListByThirdStaffIds(List<Long> thirdStaffIds) {
        if (CollectionUtils.isEmpty(thirdStaffIds)) {
            return Collections.emptyList();
        }
        ThirdPartWeComStaffExample example = new ThirdPartWeComStaffExample();
        example.createCriteria().andThirdStaffIdIn(thirdStaffIds);
        return thirdPartWeComStaffMapper.selectByExample(example);
    }

    @Override
    public void updateStaffStatus(UpdateStaffStatusRequest request) {
        ThirdPartWeComStaff staff = getStaffByName(request.getStaffName());
        if (Objects.isNull(staff)) {
            throw new CommonException(ExceptionEnum.THIRD_PART_STAFF_NOT_FOUND);
        }
        staff.setStatus(request.getStatus());
        thirdPartWeComStaffMapper.updateByPrimaryKeySelective(staff);
    }

    @Override
    public void updateAutoCreateRoomStatus(UpdateAutoCreateRoomStatusRequest request) {
        ThirdPartWeComStaff staff = getStaffByName(request.getStaffName());
        if (Objects.isNull(staff)) {
            throw new CommonException(ExceptionEnum.THIRD_PART_STAFF_NOT_FOUND);
        }
        staff.setAutoCreateRoom(request.getAutoCreateRoomStatus());
        thirdPartWeComStaffMapper.updateByPrimaryKeySelective(staff);
    }

    @Override
    public ThirdPartWeComRoom getRoomById(Long roomId) {
        return thirdPartWeComRoomMapper.selectByPrimaryKey(roomId);
    }

    @Override
    public void automaticLogin(UuidRequest request) {
        if (Objects.nonNull(request) && StringUtils.isNotEmpty(request.getUuid())) {
            apiClient.automaticLogin(request);
            return;
        }
        ThirdPartWeComStaffExample example = new ThirdPartWeComStaffExample();
        example.createCriteria().andStatusIn(Arrays.asList(ThirdPartWeComStaffStatusEnum.NORMAL.getVal(),
                ThirdPartWeComStaffStatusEnum.OFFLINE.getVal()));
        List<ThirdPartWeComStaff> staffList = thirdPartWeComStaffMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(staffList)) {
            for (ThirdPartWeComStaff staff : staffList) {
                InitRequest initRequest = new InitRequest();
                initRequest.setVid(String.valueOf(staff.getThirdStaffId()));
                initRequest.setProxySituation(0);
                initRequest.setDeverType("ipad");
                apiClient.init(initRequest);
                apiClient.setCallbackUrl(new SetCallbackUrlRequest(staff.getThirdUuid(), callbackUrl));
                UuidRequest uuidRequest = new UuidRequest();
                uuidRequest.setUuid(staff.getThirdUuid());
                apiClient.automaticLogin(uuidRequest);
            }
        }
    }

}
