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

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.ctrip.framework.apollo.spring.annotation.ApolloJsonValue;
import com.tzld.piaoquan.api.common.Constant;
import com.tzld.piaoquan.api.common.enums.ExceptionEnum;
import com.tzld.piaoquan.api.common.enums.wecom.ConfigSyncEnum;
import com.tzld.piaoquan.api.common.enums.wecom.ConfigTaskContentTypeEnum;
import com.tzld.piaoquan.api.common.enums.wecom.ThirdPartWeComStaffStatusEnum;
import com.tzld.piaoquan.api.common.enums.wecom.WeComThirdPartyCallBackTypeEnum;
import com.tzld.piaoquan.api.common.exception.CommonException;
import com.tzld.piaoquan.api.component.WeComThirdPartyApiClient;
import com.tzld.piaoquan.api.dao.mapper.wecom.thirdpart.ThirdPartWeComStaffConfigMapper;
import com.tzld.piaoquan.api.dao.mapper.wecom.thirdpart.ThirdPartWeComStaffConfigTaskContentMapper;
import com.tzld.piaoquan.api.dao.mapper.wecom.thirdpart.ThirdPartWeComStaffConfigTaskMapper;
import com.tzld.piaoquan.api.dao.mapper.wecom.thirdpart.ThirdPartWeComStaffMapper;
import com.tzld.piaoquan.api.dao.mapper.wecom.thirdpart.ext.ThirdPartWeComRoomMapperExt;
import com.tzld.piaoquan.api.dao.mapper.wecom.thirdpart.ext.ThirdPartWeComStaffMapperExt;
import com.tzld.piaoquan.api.model.param.wecom.thirdpart.*;
import com.tzld.piaoquan.api.model.po.wecom.thirdpart.*;
import com.tzld.piaoquan.api.model.vo.IdNameVO;
import com.tzld.piaoquan.api.model.vo.contentplatform.AccountQrCodeVO;
import com.tzld.piaoquan.api.model.vo.wecom.thirdpart.*;
import com.tzld.piaoquan.api.service.wecom.thirdparty.WeComThirdPartyAccountService;
import com.tzld.piaoquan.api.service.wecom.thirdparty.WeComThirdPartyRoomService;
import com.tzld.piaoquan.api.service.wecom.thirdparty.WeComThirdPartyService;
import com.tzld.piaoquan.growth.common.utils.DistributedIdGenerator;
import com.tzld.piaoquan.growth.common.utils.RedisUtils;
import com.tzld.piaoquan.growth.common.utils.page.Page;
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.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WeComThirdPartyAccountServiceImpl implements WeComThirdPartyAccountService {

    @Autowired
    private WeComThirdPartyApiClient apiClient;
    @Autowired
    private WeComThirdPartyService weComThirdPartyService;
    @Autowired
    private WeComThirdPartyRoomService roomService;
    @Autowired
    private ThirdPartWeComStaffMapper staffMapper;
    @Autowired
    private ThirdPartWeComStaffConfigMapper staffConfigMapper;
    @Autowired
    private ThirdPartWeComStaffConfigTaskMapper staffConfigTaskMapper;
    @Autowired
    private ThirdPartWeComStaffConfigTaskContentMapper staffConfigTaskContentMapper;
    @Autowired
    private ThirdPartWeComStaffMapperExt staffMapperExt;
    @Autowired
    private ThirdPartWeComRoomMapperExt roomMapperExt;

    @Autowired
    private RedisUtils redisUtils;

    @Value("${wecom.thirdpart.callback.url:https://test-tp-open.piaoquantv.com/wecom/thirdparty/callback}")
    private String callbackUrl;
    @ApolloJsonValue("${send.room.msg.staff.put.scene.config:{}}")
    private Map<Long, String> staffPutSceneConfig;
    @ApolloJsonValue("${send.room.msg.staff.channel.config:{}}")
    private Map<Long, String> staffChannelConfig;
    @ApolloJsonValue("${send.room.msg.auto.open.staff:[]}")
    private List<Long> autoOpenStaffList;

    @Override
    public AccountQrCodeVO getQrCode(Long id) {
        InitRequest initRequest = new InitRequest();
        if (Objects.nonNull(id)) {
            ThirdPartWeComStaff staff = weComThirdPartyService.getStaffById(id);
            if (Objects.isNull(staff)) {
                throw new CommonException(ExceptionEnum.PARAM_ERROR.getCode(), "企微账号不存在");
            }
            initRequest.setVid(String.valueOf(staff.getThirdStaffId()));
        }
        initRequest.setProxySituation(0);
        initRequest.setDeverType("ipad");
        String initResponseStr = apiClient.init(initRequest);
        CommonResponse<InitResponse> initResponse =
                JSONObject.parseObject(initResponseStr, new TypeReference<CommonResponse<InitResponse>>() {});
        String uuid = initResponse.getData().getUuid();
        apiClient.setCallbackUrl(new SetCallbackUrlRequest(uuid, callbackUrl));
        String qrCodeResponseStr = apiClient.getQrCode(new UuidRequest(uuid));
        CommonResponse<QrCodeResponse> qrCodeResponse =
                JSONObject.parseObject(qrCodeResponseStr, new TypeReference<CommonResponse<QrCodeResponse>>() {});
        if (qrCodeResponse.getErrcode() != 0) {
            log.error("WeComThirdPartyService get qr code failed, request: {}, response: {}", initRequest, qrCodeResponse);
            return null;
        }
        // 置为待扫码状态
        String loginStatusKey = Constant.loginStatusKey.replace("{uuid}", uuid);
        redisUtils.set(loginStatusKey, String.valueOf(1), qrCodeResponse.getData().getTtl());

        AccountQrCodeVO result = new AccountQrCodeVO();
        result.setUuid(uuid);
        result.setQrcode(qrCodeResponse.getData().getQrcode());
        result.setQrcodeBase64(qrCodeResponse.getData().getQrcode_data());
        result.setKey(qrCodeResponse.getData().getKey());
        result.setTtl(qrCodeResponse.getData().getTtl());
        return result;
    }

    @Override
    public Integer checkLogin(String uuid) {
        String loginStatusKey = Constant.loginStatusKey.replace("{uuid}", uuid);
        Integer result = redisUtils.getInteger(loginStatusKey);
        if (result == 0) {
            ThirdPartWeComStaff staff = weComThirdPartyService.getStaffByUuid(uuid);
            if (Objects.isNull(staff)) {
                throw new CommonException(ExceptionEnum.PARAM_ERROR.getCode(), "企微账号不存在");
            }
            if (staff.getStatus() == ThirdPartWeComStaffStatusEnum.NORMAL.getVal()) {
                return WeComThirdPartyCallBackTypeEnum.LOGIN_SUCCESS.getVal();
            }
        }
        return result;
    }

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

    @Override
    public Page<ThirdPartyAccountVO> list(ThirdPartyAccountListParam param) {
        Page<ThirdPartyAccountVO> result = new Page<>(param.getPageNum(), param.getPageSize());
        int offset = (param.getPageNum() - 1) * param.getPageSize();
        int count = staffMapperExt.getAccountCount(param);
        result.setTotalSize(count);
        if (count == 0) {
            return result;
        }
        List<ThirdPartWeComStaff> staffList = staffMapperExt.getAccountList(param, offset, param.getPageSize());
        List<ThirdPartyAccountVO> list = buildThirdPartyAccountVOList(staffList);
        result.setObjs(list);
        return result;
    }

    private List<ThirdPartyAccountVO> buildThirdPartyAccountVOList(List<ThirdPartWeComStaff> staffList) {
        List<Long> corpIds = staffList.stream().map(ThirdPartWeComStaff::getCorpId).collect(Collectors.toList());
        List<ThirdPartWeComCorp> corpList = weComThirdPartyService.getCorpListByIds(corpIds);
        Map<Long, ThirdPartWeComCorp> corpMap = corpList.stream()
                .collect(Collectors.toMap(ThirdPartWeComCorp::getId, corp -> corp));

        List<ThirdPartyAccountVO> result = new ArrayList<>();
        for (ThirdPartWeComStaff staff : staffList) {
            ThirdPartyAccountVO vo = new ThirdPartyAccountVO();
            vo.setId(staff.getId());
            vo.setCorpName(corpMap.get(staff.getCorpId()).getName());
            vo.setAccountName(staff.getName());
            vo.setRealName(staff.getRealName());
            vo.setMobile(staff.getMobile());
            vo.setStatus(staff.getStatus());
            vo.setQrImage(staff.getQrImage());
            vo.setAvatar(staff.getAvatar());
            vo.setThirdStaffId(staff.getThirdStaffId());
            vo.setThirdUuid(staff.getThirdUuid());
            result.add(vo);
        }
        return result;
    }

    @Override
    public List<IdNameVO<Long>> getPushAccountList(Long accountId, String name) {
        List<ThirdPartWeComStaff> pushStaffList = staffMapperExt.getPushStaffList(accountId, null, name);
        List<Long> staffIds = new ArrayList<>();
        return pushStaffList.stream().map(staff -> new IdNameVO<>(staff.getThirdStaffId(), staff.getName()))
                .filter(staff -> {
                    boolean res = !staffIds.contains(staff.getId());
                    staffIds.add(staff.getId());
                    return res;
                })
                .collect(Collectors.toList());
    }

    @Override
    public ThirdPartyAccountConfigVO getAccountConfig(ThirdPartyConfigGetParam param) {
        ThirdPartWeComStaffConfig config = getStaffConfig(param.getId());
        if (Objects.isNull(config)) {
            return null;
        }
        List<ThirdPartWeComStaff> pushStaffList = getStaffConfigPushList(config);
        Map<Long, String> pushStaffMap = pushStaffList.stream()
                .collect(Collectors.toMap(ThirdPartWeComStaff::getThirdStaffId, ThirdPartWeComStaff::getName));
        List<ThirdPartWeComStaffConfigTask> taskList = getStaffConfigTasks(config.getId());
        List<String> taskIds = taskList.stream().map(ThirdPartWeComStaffConfigTask::getId).collect(Collectors.toList());
        List<ThirdPartWeComStaffConfigTaskContent> contentList = getStaffConfigTaskContents(taskIds);
        Map<String, List<ThirdPartWeComStaffConfigTaskContent>> taskContentMap = contentList.stream()
                .collect(Collectors.groupingBy(ThirdPartWeComStaffConfigTaskContent::getTaskId));
        List<ThirdPartWeComRoomConfig> roomConfigList = roomService.getAccountConfigRoomConfigList(config.getId());
        List<Long> roomIds = roomConfigList.stream().map(ThirdPartWeComRoomConfig::getRoomId).collect(Collectors.toList());
        List<ThirdPartWeComRoom> roomList = roomService.getRoomListByRoomIds(roomIds);
        List<IdNameVO<Long>> roomIdNameList = roomList.stream().map(room -> new IdNameVO<>(room.getId(), room.getName()))
                .collect(Collectors.toList());
        ThirdPartyAccountConfigVO result = new ThirdPartyAccountConfigVO();
        result.setId(config.getId());
        result.setPutScene(config.getPutScene());
        result.setChannel(config.getChannel());
        result.setSwitchFlag(config.getSwitchFlag());
        result.setOpenRoomSendSwitchNum(config.getOpenRoomSendSwitchNum());
        result.setConfigSync(config.getConfigSync());
        result.setConfigSyncRoomIdList(roomIdNameList);
        if (Objects.nonNull(config.getPrimaryThirdStaffId())) {
            result.setPrimaryThirdStaffId(config.getPrimaryThirdStaffId());
            result.setPrimaryThirdStaffName(pushStaffMap.get(config.getPrimaryThirdStaffId()));
        }
        if (Objects.nonNull(config.getSecondThirdStaffId())) {
            result.setSecondThirdStaffId(config.getSecondThirdStaffId());
            result.setSecondThirdStaffName(pushStaffMap.get(config.getSecondThirdStaffId()));
        }
        result.setTaskList(taskList.stream().map(task -> {
            ThirdPartyAccountConfigTaskVO vo = new ThirdPartyAccountConfigTaskVO();
            vo.setId(task.getId());
            vo.setSwitchFlag(task.getSwitchFlag());
            vo.setSendTime(JSONObject.parseArray(task.getSendTime(), String.class));
            vo.setRandomMin(task.getRandomMin());
            vo.setSeq(task.getSeq());
            List<ThirdPartWeComStaffConfigTaskContent> contents = taskContentMap.get(task.getId());
            vo.setContentList(contents.stream().map(content -> {
                ThirdPartyAccountConfigTaskContentVO contentVO = new ThirdPartyAccountConfigTaskContentVO();
                contentVO.setId(content.getId());
                contentVO.setType(content.getType());
                contentVO.setContent(content.getContent());
                contentVO.setSource(content.getSource());
                contentVO.setSourceContent(content.getSourceContent());
                contentVO.setSeq(content.getSeq());
                return contentVO;
            }).collect(Collectors.toList()));
            return vo;
        }).collect(Collectors.toList()));
        return result;
    }

    private List<ThirdPartWeComStaff> getStaffConfigPushList(ThirdPartWeComStaffConfig config) {
        List<Long> thirdStaffIds = new ArrayList<>();
        if (Objects.nonNull(config.getPrimaryThirdStaffId())) {
            thirdStaffIds.add(config.getPrimaryThirdStaffId());
        }
        if (Objects.nonNull(config.getSecondThirdStaffId())) {
            thirdStaffIds.add(config.getSecondThirdStaffId());
        }
        return weComThirdPartyService.getStaffListByThirdStaffIds(thirdStaffIds);
    }

    private ThirdPartWeComStaffConfig getStaffConfig(Long accountId) {
        ThirdPartWeComStaffConfigExample example = new ThirdPartWeComStaffConfigExample();
        example.createCriteria().andStaffIdEqualTo(accountId).andStatusEqualTo(1);
        List<ThirdPartWeComStaffConfig> configs = staffConfigMapper.selectByExample(example);
        if (configs.isEmpty()) {
            return null;
        }
        return configs.get(0);
    }

    private List<ThirdPartWeComStaffConfigTask> getStaffConfigTasks(String configId) {
        ThirdPartWeComStaffConfigTaskExample example = new ThirdPartWeComStaffConfigTaskExample();
        example.createCriteria().andConfigIdEqualTo(configId);
        return staffConfigTaskMapper.selectByExample(example);
    }

    private List<ThirdPartWeComStaffConfigTaskContent> getStaffConfigTaskContents(List<String> taskIds) {
        ThirdPartWeComStaffConfigTaskContentExample example = new ThirdPartWeComStaffConfigTaskContentExample();
        example.createCriteria().andTaskIdIn(taskIds);
        return staffConfigTaskContentMapper.selectByExample(example);
    }

    @Override
    public CheckPushAccountExistVO checkPushAccountExist(ThirdPartyAccountConfigParam param) {
        List<ThirdPartWeComRoom> roomList = getNeedSyncRoomList(param);
        if (CollectionUtils.isEmpty(roomList)) {
            return new CheckPushAccountExistVO();
        }
        List<String> thirdRoomIds = roomList.stream().map(ThirdPartWeComRoom::getThirdRoomId).collect(Collectors.toList());
        List<ThirdPartWeComRoomUser> roomUserList = roomService.getRoomUserListByRoomIds(thirdRoomIds);
        Map<String, List<ThirdPartWeComRoomUser>> roomUserMap = roomUserList.stream().collect(Collectors.groupingBy(ThirdPartWeComRoomUser::getThirdRoomId));

        CheckPushAccountExistVO result = new CheckPushAccountExistVO();
        result.setNotExistRooms(new ArrayList<>());
        for (ThirdPartWeComRoom room : roomList) {
            List<IdNameVO<Long>> notExistPushAccounts = new ArrayList<>();
            List<ThirdPartWeComRoomUser> roomUsers = roomUserMap.get(room.getThirdRoomId());
            if (CollectionUtils.isNotEmpty(roomUsers)) {
                List<Long> thirdStaffIds = roomUsers.stream().map(ThirdPartWeComRoomUser::getUin).collect(Collectors.toList());
                if (!thirdStaffIds.contains(param.getPrimaryThirdStaffId())) {
                    notExistPushAccounts.add(new IdNameVO<>(param.getPrimaryThirdStaffId(), param.getPrimaryThirdStaffName()));
                }
                if (Objects.nonNull(param.getSecondThirdStaffId()) && !thirdStaffIds.contains(param.getSecondThirdStaffId())) {
                    notExistPushAccounts.add(new IdNameVO<>(param.getSecondThirdStaffId(), param.getSecondThirdStaffName()));
                }
            }
            if (CollectionUtils.isNotEmpty(notExistPushAccounts)) {
                CheckPushAccountExistVO.Room roomVO = new CheckPushAccountExistVO.Room();
                roomVO.setRoomId(room.getId());
                roomVO.setName(room.getName());
                roomVO.setNotExistPushAccounts(notExistPushAccounts);
                result.getNotExistRooms().add(roomVO);
            }
        }
        if (CollectionUtils.isNotEmpty(result.getNotExistRooms())) {
            result.setPass(false);
        }
        return result;
    }

    @Override
    public void saveAccountConfig(ThirdPartyAccountConfigParam param) {
        // check param
        checkAccountConfigParam(param);
        ThirdPartWeComStaffConfig config = getStaffConfig(param.getAccountId());
        if (Objects.nonNull(config)) {
            config.setStatus(0);
            config.setUpdateTime(new Date());
            staffConfigMapper.updateByPrimaryKey(config);
        }
        ThirdPartWeComStaffConfig newConfig = new ThirdPartWeComStaffConfig();
        newConfig.setId(DistributedIdGenerator.generate());
        newConfig.setStaffId(param.getAccountId());
        newConfig.setPutScene(param.getPutScene());
        newConfig.setChannel(param.getChannel());
        newConfig.setSwitchFlag(param.getSwitchFlag());
        newConfig.setOpenRoomSendSwitchNum(param.getOpenRoomSendSwitchNum());
        newConfig.setPrimaryThirdStaffId(param.getPrimaryThirdStaffId());
        newConfig.setSecondThirdStaffId(param.getSecondThirdStaffId());
        newConfig.setStatus(1);
        newConfig.setConfigSync(param.getConfigSync());
        newConfig.setCreateTime(new Date());
        newConfig.setUpdateTime(new Date());
        staffConfigMapper.insert(newConfig);
        for (ThirdPartyAccountConfigTaskParam taskParam : param.getTaskList()) {
            ThirdPartWeComStaffConfigTask newTask = new ThirdPartWeComStaffConfigTask();
            newTask.setId(DistributedIdGenerator.generate());
            newTask.setConfigId(newConfig.getId());
            newTask.setSwitchFlag(taskParam.getSwitchFlag());
            newTask.setSendTime(JSONObject.toJSONString(taskParam.getSendTime()));
            newTask.setRandomMin(taskParam.getRandomMin());
            newTask.setSeq(taskParam.getSeq());
            newTask.setCreateTime(new Date());
            newTask.setUpdateTime(new Date());
            staffConfigTaskMapper.insert(newTask);
            for (ThirdPartyAccountConfigTaskContentParam taskContentParam : taskParam.getContentList()) {
                ThirdPartWeComStaffConfigTaskContent newContent = new ThirdPartWeComStaffConfigTaskContent();
                newContent.setId(DistributedIdGenerator.generate());
                newContent.setTaskId(newTask.getId());
                newContent.setType(taskContentParam.getType());
                newContent.setContent(taskContentParam.getContent());
                newContent.setSource(taskContentParam.getSource());
                newContent.setSourceContent(taskContentParam.getSourceContent());
                newContent.setSeq(taskContentParam.getSeq());
                newContent.setCreateTime(new Date());
                newContent.setUpdateTime(new Date());
                staffConfigTaskContentMapper.insert(newContent);
            }
            // 任务开关关闭，账号下的群，任务同步关闭

        }
        // 配置同步
        new Thread(() -> syncStaffConfigToRoom(param, newConfig.getId())).start();
    }

    private void syncStaffConfigToRoom(ThirdPartyAccountConfigParam param, String accountConfigId) {
        List<ThirdPartWeComRoom> roomList = getNeedSyncRoomList(param);
        syncConfig(param, accountConfigId, roomList);
    }

    private List<ThirdPartWeComRoom> getNeedSyncRoomList(ThirdPartyAccountConfigParam param) {
        List<ThirdPartWeComRoom> roomList;
        if (param.getConfigSync() == ConfigSyncEnum.ALL.getVal()) {
            // 所有群
            roomList = weComThirdPartyService.getStaffRoomList(param.getAccountId());
        } else if (param.getConfigSync() == ConfigSyncEnum.SPECIFY.getVal()) {
            // 指定群生效
            roomList = weComThirdPartyService.getRoomByRoomIds(param.getConfigSyncRoomIdList());
        } else {
            roomList = new ArrayList<>();
        }
        List<Long> roomIds = roomList.stream().map(ThirdPartWeComRoom::getId).collect(Collectors.toList());
        // 未配置群生效
        List<ThirdPartWeComRoom> noConfigRoomList = roomMapperExt.getNoConfigRoomList(param.getAccountId());
        noConfigRoomList.removeIf(room -> roomIds.contains(room.getId()));
        roomList.addAll(noConfigRoomList);
        return roomList;
    }

    private void syncConfig(ThirdPartyAccountConfigParam param, String accountConfigId, List<ThirdPartWeComRoom> roomList) {
        if (CollectionUtils.isEmpty(roomList)) {
            return;
        }
        for (ThirdPartWeComRoom room : roomList) {
            try {
                roomService.saveRoomConfig(room, accountConfigId, param);
            } catch (Exception e) {
                log.error("同步群配置失败, roomId: {}, accountConfigId: {}, errorMsg: {}", room.getId(), accountConfigId, e.getMessage());
            }
        }
    }

    private void checkAccountConfigParam(ThirdPartyAccountConfigParam param) {
        if (Objects.isNull(param.getAccountId())) {
            throw new CommonException(ExceptionEnum.PARAM_ERROR.getCode(), "账号id不能为空");
        }
        if (StringUtils.isBlank(param.getPutScene())) {
            throw new CommonException(ExceptionEnum.PARAM_ERROR.getCode(), "推送场景不能为空");
        }
        if (Objects.isNull(param.getPrimaryThirdStaffId())) {
            throw new CommonException(ExceptionEnum.PARAM_ERROR.getCode(), "主推送人员不能为空");
        }
        if (CollectionUtils.isEmpty(param.getTaskList())) {
            throw new CommonException(ExceptionEnum.PARAM_ERROR.getCode(), "任务列表不能为空");
        }
        if (param.getConfigSync() == ConfigSyncEnum.SPECIFY.getVal() && CollectionUtils.isEmpty(param.getConfigSyncRoomIdList())) {
            throw new CommonException(ExceptionEnum.PARAM_ERROR.getCode(), "指定群生效时，选定群列表不能为空");
        }
        List<String> timeList = new ArrayList<>();
        for (ThirdPartyAccountConfigTaskParam task : param.getTaskList()) {
            if (CollectionUtils.isEmpty(task.getSendTime())) {
                throw new CommonException(ExceptionEnum.PARAM_ERROR.getCode(), "推送时间不能为空");
            }
            for (String sendTime : task.getSendTime()) {
                if (timeList.contains(sendTime)) {
                    throw new CommonException(ExceptionEnum.PARAM_ERROR.getCode(), "推送时间不能重复: " + sendTime);
                } else {
                    timeList.add(sendTime);
                }
            }
            if (Objects.nonNull(task.getRandomMin())) {
                if (task.getRandomMin() < 0) {
                    throw new CommonException(ExceptionEnum.PARAM_ERROR.getCode(), "随机浮动分钟不能小于0");
                } else if (task.getRandomMin() > 30) {
                    throw new CommonException(ExceptionEnum.PARAM_ERROR.getCode(), "随机浮动分钟不能大于30");
                }
            }
            if (CollectionUtils.isEmpty(task.getContentList()) || task.getContentList().size() > 3) {
                throw new CommonException(ExceptionEnum.PARAM_ERROR.getCode(), "任务内容不能为空，最多3条");
            }
            for (ThirdPartyAccountConfigTaskContentParam content : task.getContentList()) {
                if (Objects.isNull(content.getType())) {
                    throw new CommonException(ExceptionEnum.PARAM_ERROR.getCode(), "任务内容类型不能为空");
                }
                if (content.getType() == ConfigTaskContentTypeEnum.TEXT.getVal()
                        && StringUtils.isBlank(content.getContent())) {
                    throw new CommonException(ExceptionEnum.PARAM_ERROR.getCode(), "文案不能为空");
                } else if (content.getType() == ConfigTaskContentTypeEnum.MINI_PROGRAM.getVal()
                        && Objects.isNull(content.getSource())) {
                    throw new CommonException(ExceptionEnum.PARAM_ERROR.getCode(), "小程序来源不能为空");
                }
            }
        }

    }

    @Override
    public void logout(ThirdPartyAccountLogOutParam param) {
        ThirdPartWeComStaff staff = weComThirdPartyService.getStaffById(param.getId());
        if (Objects.isNull(staff)) {
            throw new CommonException(ExceptionEnum.PARAM_ERROR.getCode(), "企微账号不存在");
        }
        String logoutResponseStr = apiClient.loginOut(new UuidRequest(staff.getThirdUuid()));
        CommonResponse<LoginOutResponse> logoutResponse =
                JSONObject.parseObject(logoutResponseStr, new TypeReference<CommonResponse<LoginOutResponse>>() {});
        if (logoutResponse.getErrcode() != 0) {
            log.error("WeComThirdPartyService logout failed, request: {}, response: {}", staff.getThirdUuid(), logoutResponse);
            throw new CommonException(ExceptionEnum.THIRD_PART_LOGOUT_FAILED.getCode(), "企微账号退出失败");
        }
        staff.setStatus(ThirdPartWeComStaffStatusEnum.QUIT.getVal());
        staff.setUpdateTime(new Date());
        staffMapper.updateByPrimaryKey(staff);
    }

    @Override
    public List<ThirdPartWeComStaffConfig> getStaffConfigListByStaffIds(List<Long> staffIdList) {
        if (CollectionUtils.isEmpty(staffIdList)) {
            return Collections.emptyList();
        }
        ThirdPartWeComStaffConfigExample example = new ThirdPartWeComStaffConfigExample();
        example.createCriteria().andStaffIdIn(staffIdList).andStatusEqualTo(1);
        return staffConfigMapper.selectByExample(example);
    }

    @Override
    public void initAccountConfig() {
        List<ThirdPartWeComStaff> staffList = staffMapper.selectByExample(new ThirdPartWeComStaffExample());
        if (CollectionUtils.isEmpty(staffList)) {
            return;
        }
        for (ThirdPartWeComStaff staff : staffList) {
            ThirdPartyAccountConfigParam configParam = buildThirdPartyAccountConfigParam(staff);
            saveAccountConfig(configParam);
            if (staff.getStatus() == 0) {
                apiClient.setCallbackUrl(new SetCallbackUrlRequest(staff.getThirdUuid(), callbackUrl));
                weComThirdPartyService.saveStaffQrCode(staff.getThirdUuid());
            }
        }
    }

    private ThirdPartyAccountConfigParam buildThirdPartyAccountConfigParam(ThirdPartWeComStaff staff) {
        ThirdPartyAccountConfigParam newConfig = new ThirdPartyAccountConfigParam();
        newConfig.setAccountId(staff.getId());
        newConfig.setPutScene(staffPutSceneConfig.getOrDefault(staff.getThirdStaffId(), "touliu"));
        newConfig.setChannel(staffChannelConfig.getOrDefault(staff.getThirdStaffId(), "tencentqw"));
        newConfig.setSwitchFlag(1);
        if (autoOpenStaffList.contains(staff.getThirdStaffId())) {
            newConfig.setOpenRoomSendSwitchNum(20);
        }
        newConfig.setPrimaryThirdStaffId(staff.getThirdStaffId());
        newConfig.setConfigSync(1);

        ThirdPartyAccountConfigTaskParam newTask = new ThirdPartyAccountConfigTaskParam();
        newTask.setSwitchFlag(1);
        List<String> sendTime = JSONObject.parseArray("[\"08:00\",\"11:00\",\"16:00\",\"21:00\"]", String.class);
        newTask.setSendTime(sendTime);
        newTask.setRandomMin(20);
        newTask.setSeq(0);
        newConfig.setTaskList(Collections.singletonList(newTask));

        List<ThirdPartyAccountConfigTaskContentParam> contentList = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            ThirdPartyAccountConfigTaskContentParam newContent = new ThirdPartyAccountConfigTaskContentParam();
            newContent.setType(1);
            newContent.setSource(0);
            newContent.setSeq(i);
            contentList.add(newContent);
        }
        newTask.setContentList(contentList);

        return newConfig;
    }

}
