package com.pcloud.book.consumer.wechatgroup;

import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.dto.ResponseDto;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.ResponseHandleUtil;
import com.pcloud.common.utils.string.StringUtil;
import com.pcloud.wechatgroup.group.dto.GroupMemberStatisDTO;
import com.pcloud.wechatgroup.group.dto.GroupRobotDTO;
import com.pcloud.wechatgroup.group.dto.GroupUserDTO;
import com.pcloud.wechatgroup.group.dto.RobotReplyDTO;
import com.pcloud.wechatgroup.group.service.GroupMemberService;
import com.pcloud.wechatgroup.message.dto.GroupChatCountDTO;
import com.pcloud.wechatgroup.message.service.MessageService;
import com.pcloud.wechatgroup.monitor.service.MonitorService;
import com.pcloud.wechatgroup.selfrobot.service.SelfRobotService;

import com.pcloud.wechatgroup.selfrobot.dto.SelfRobotDTO;
import com.pcloud.wechatgroup.selfrobot.service.SelfRobotService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component("wechatGroupConsr")
public class WechatGroupConsr {

    @Autowired
    private GroupMemberService groupMemberService;

    @Autowired
    private MessageService messageService;
    @Autowired
    private MonitorService monitorService;
    @Autowired
    private SelfRobotService selfRobotService;

    @ParamLog("根据机器人id和用户微信id获取最新暗号")
    public String getCipherByRobotAndUserWxId(String robotWxId, String userWxId) {
        if (StringUtil.isBlank(robotWxId) || StringUtil.isBlank(userWxId)) {
            return null;
        }
        try {
            return ResponseHandleUtil.parseResponse(selfRobotService.getCipherByRobotAndUserWxId(robotWxId, userWxId), String.class);
        } catch (BizException e) {
            log.warn("根据机器人id和用户微信id获取最新暗号失败:" + e.getMessage(), e);
            throw new BizException(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("根据机器人id和用户微信id获取最新暗号.[getCipherByRobotAndUserWxId]:" + e.getMessage(), e);
            throw new BookBizException(BookBizException.INVOKE_RES_ERROR, "服务内部错误，请稍后重试");
        } finally {
            log.info("【根据机器人id和用户微信id获取最新暗号,<END>");
        }
    }

    @ParamLog("是否群机器人")
    public Boolean isGroupRobot(String robotWxId) {
        if (StringUtil.isBlank(robotWxId)) {
            return null;
        }
        try {
            return ResponseHandleUtil.parseResponse(selfRobotService.isGroupRobot(robotWxId), Boolean.class);
        } catch (BizException e) {
            log.warn("是否群机器人失败:" + e.getMessage(), e);
            throw new BizException(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("是否群机器人.[isGroupRobot]:" + e.getMessage(), e);
            throw new BookBizException(BookBizException.INVOKE_RES_ERROR, "服务内部错误，请稍后重试");
        } finally {
            log.info("【是否群机器人,<END>");
        }
    }

    /**
     * 是否黑名单
     */
    public Boolean isKickUser(String nickName, String wxGroupId) throws BizException {
        log.info("【是否黑名单,<START>.[nickName]={}, wxGroupId:{}" , nickName, wxGroupId);
        if (StringUtil.isBlank(nickName) || StringUtil.isBlank(wxGroupId)) {
            return null;
        }
        try {
            return ResponseHandleUtil.parseResponse(monitorService.isKickUser(nickName, wxGroupId), Boolean.class);
        } catch (BizException e) {
            log.warn("是否黑名单失败:" + e.getMessage(), e);
            throw new BizException(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("是否黑名单.[isKickUser]:" + e.getMessage(), e);
            throw new BookBizException(BookBizException.INVOKE_RES_ERROR, "服务内部错误，请稍后重试");
        } finally {
            log.info("【是否黑名单,<END>");
        }
    }

    /**
     * 根据群号获取机器人微信号
     */
    @ParamLog("根据群号获取机器人微信号")
    public String getRobotIdByGroupId(String groupId) throws BizException {
        log.info("【根据群号获取机器人微信号,<START>.[groupId]=" + groupId + "]");
        if (groupId == null) {
            return null;
        }
        try {
            return ResponseHandleUtil.parseResponse(groupMemberService.getRobotIdByGroupId(groupId), String.class);
        } catch (BizException e) {
            log.warn("根据群号获取机器人微信号失败:" + e.getMessage(), e);
            throw new BizException(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("根据群号获取机器人微信号.[getRobotIdByGroupId]:" + e.getMessage(), e);
            throw new BookBizException(BookBizException.INVOKE_RES_ERROR, "服务内部错误，请稍后重试");
        } finally {
            log.info("【根据群号获取机器人微信号,<END>");
        }
    }

    @ParamLog("根据群号获取发广告机器人微信号")
    public String getSendAdRobotByGroupId(String groupId) throws BizException{
        log.info("【根据群号获取发广告机器人微信号,<START>.[groupId]=" + groupId + "]");
        if (groupId == null) {
            return null;
        }
        try {
            return ResponseHandleUtil.parseResponse(groupMemberService.getSendAdRobotByGroupId(groupId), String.class);
        } catch (BizException e) {
            log.warn("根据群号获取发广告机器人微信号失败:" + e.getMessage(), e);
            throw new BizException(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("根据群号获取发广告机器人微信号.[getSendAdRobotByGroupId]:" + e.getMessage(), e);
            throw new BookBizException(BookBizException.INVOKE_RES_ERROR, "服务内部错误，请稍后重试");
        } finally {
            log.info("【根据群号获取发广告机器人微信号,<END>");
        }
    }

    /**
     * 根据昵称获取微信id
     */
    public List<String> getWxUserIdsByNickName(String nickName) throws BizException {
        log.info("【根据昵称获取微信id,<START>.[nickName]=" + nickName + "]");
        if (StringUtil.isBlank(nickName)) {
            return null;
        }
        try {
            final List<String> strings = ResponseHandleUtil.parseList(groupMemberService.getWxUserIdsByNickName(nickName), String.class);
            log.info("根据昵称获取微信 strings:{}:" ,strings);
            return strings;
        } catch (BizException e) {
            log.warn("根据昵称获取微信id失败:" + e.getMessage(), e);
            throw new BizException(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("根据昵称获取微信id.[getWxUserIdsByNickName]:" + e.getMessage(), e);
            throw new BookBizException(BookBizException.INVOKE_RES_ERROR, "服务内部错误，请稍后重试");
        } finally {
            log.info("【根据昵称获取微信id,<END>");
        }
    }

    @ParamLog(value = "累计进群人数与今日进群人数", isBefore = false, isAfterReturn = false)
    public Map<String, GroupMemberStatisDTO> listGroupMemberStatisInfo(List<String> weixinGroupIds) throws BizException {
        if (ListUtils.isEmpty(weixinGroupIds)) {
            return null;
        }
        try {
            return ResponseHandleUtil.parseMapResponse(groupMemberService.mapGroupMemberStatisInfo(weixinGroupIds), String.class, GroupMemberStatisDTO.class);
        } catch (Exception e) {
            log.error("获取累计进群人数与今日进群人数.[listGroupMemberStatisInfo]:" + e.getMessage(), e);
        }
        return null;
    }

    @ParamLog(value = "群分类累计进群人数与今日进群人数", isBefore = false, isAfterReturn = false)
    public Map<Long, Long> getclassifyMemberCount(List<Long> classifyIds) throws BizException {
        if (ListUtils.isEmpty(classifyIds)) {
            return null;
        }
        try {
            return ResponseHandleUtil.parseMapResponse(groupMemberService.mapGroupClassifyStatisInfo(classifyIds), Long.class, Long.class);
        } catch (Exception e) {
            log.error("群分类累计进群人数与今日进群人数.[getclassifyMemberCount]:" + e.getMessage(), e);
        }
        return null;
    }

    @ParamLog(value = "活跃人数与总发言数", isBefore = false, isAfterReturn = false)
    public Map<Long, GroupChatCountDTO> getChatCountByGroup(List<Long> groupQrcodeIds, Long bookGroupId) throws BizException {
        if (ListUtils.isEmpty(groupQrcodeIds)) {
            return null;
        }
        try {
            return ResponseHandleUtil.parseMapResponse(messageService.getChatCountByGroup(groupQrcodeIds, bookGroupId), Long.class, GroupChatCountDTO.class);
        } catch (Exception e) {
            log.error("获取活跃人数与总发言数.[getChatCountByGroup]:" + e.getMessage(), e);
        }
        return null;
    }

    @ParamLog(value = "获取退群率", isBefore = false, isAfterReturn = false)
    public Map<String, BigDecimal> mapOutGroupRate(List<String> wxGroupIds) throws BizException {
        if (ListUtils.isEmpty(wxGroupIds)) {
            return null;
        }
        try {
            return ResponseHandleUtil.parseMapResponse(groupMemberService.mapOutGroupRate(wxGroupIds), String.class, BigDecimal.class);
        } catch (Exception e) {
            log.error("获取退群率失败.[mapOutGroupRate]:" + e.getMessage(), e);
        }
        return null;
    }

    @ParamLog(value = "上传群二维码时根据群ID添加群管理员（群主，机器人等）")
    public void addGroupManagers(String wxGroupId, String altId) throws BizException {
        try {
            groupMemberService.addGroupManagers(wxGroupId, altId);
        } catch (Exception e) {
            log.error("上传群二维码时根据群ID添加群管理员（群主，机器人等）失败.[addGroupManagers]:" + e.getMessage(), e);
        }
    }

    @ParamLog(value = "获取所有机器人微信号")
    public List<String> listAllRobotWxId() throws BizException {
        try {
            List<String> wxids = ResponseHandleUtil.parseListResponse(groupMemberService.listAllRobotWxId(), String.class);
            return wxids;
        } catch (Exception e) {
            log.error("获取所有机器人微信号失败.[listAllRobotWxId]:" + e.getMessage(), e);
        }
        return null;
    }

    @ParamLog(value = "设置第一个关键词回复")
    public void addFirstRobotReplyRecord(RobotReplyDTO robotReplyDTO) throws BizException {
        try {
            groupMemberService.addFirstRobotReplyRecord(robotReplyDTO);
        } catch (Exception e) {
            log.error("设置第一个关键词回复失败.[addFirstRobotReplyRecord]:" + e.getMessage(), e);
        }
    }

    @ParamLog(value = "获取机器人信息")
    public GroupRobotDTO getRobotInfoByWxUserId(String wxRobotId) throws BizException {
        try {
            return ResponseHandleUtil.parseResponse(groupMemberService.getRobotInfoByWxUserId(wxRobotId), GroupRobotDTO.class);
        } catch (Exception e) {
            log.error("获取机器人信息失败.[getRobotInfoByWxUserId]:" + e.getMessage(), e);
        }
        return null;
    }

    /**
     * 根据群号获取群主微信号
     */
    public String getMasterIdByGroupId(String groupId) throws BizException {
        log.info("【根据群号获取群主微信号,<START>.[groupId]=" + groupId + "]");
        String masterId = null;
        if (groupId == null) {
            return null;
        }
        try {
            masterId = ResponseHandleUtil.parseResponse(groupMemberService.getMasterIdByGroupId(groupId), String.class);
            return masterId;
        } catch (BizException e) {
            log.warn("根据群号获取群主微信号失败:" + e.getMessage(), e);
            throw new BizException(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("根据群号获取群主微信号.[getMasterIdByGroupId]:" + e.getMessage(), e);
            throw new BookBizException(BookBizException.INVOKE_RES_ERROR, "服务内部错误，请稍后重试");
        } finally {
            log.info("【根据群号获取群主微信号,<END>--masterId=" + masterId);
        }
    }

    @ParamLog(value = "最近7天活跃人数")
    public Map<Long, Integer> get7DayActiveUserCountByClassify(List<Long> classifyIds) throws BizException {
        Map<Long, Integer> map = new HashMap<>();
        try {
            map = ResponseHandleUtil.parseMapResponse(messageService.get7DayActiveUserCountByClassify(classifyIds), Long.class, Integer.class);
        } catch (Exception e) {
            log.error("获取最近7天活跃人数失败.[get7DayActiveUserCountByClassify]:" + e.getMessage(), e);
        }
        if (map == null) {
            return new HashMap<>();
        }
        return map;
    }


    @ParamLog(value = "根据群id集合批量获取发消息的小号")
    public Map<String, String> getSendDailyRobotByGroupIds(List<String> weixinIds) throws BizException {
        Map<String, String> map = new HashMap<>();
        for (String weixinId:weixinIds){
            map.put(weixinId,"wxid_mxrau68qs7ou22");
        }
        try {
             map = ResponseHandleUtil.parseMapResponse(groupMemberService.getSendDailyRobotByGroupIds(weixinIds), String.class, String.class);
        } catch (Exception e) {
            log.error("根据群id集合批量获取发消息的小号.[getRobotIdByWeixinIdBatch]:" + e.getMessage(), e);
        }
        if (map == null) {
            return new HashMap<>();
        }
        return map;
    }

    @ParamLog(value = "根据群id集合最近7天活跃人数")
    public Map<Long,Integer> get7DayActiveUserCountByQrcode(List<Long> qrcodeIds) {
        Map<Long, Integer> map = new HashMap<>();
        try {
            map = ResponseHandleUtil.parseMapResponse(messageService.get7DayActiveUserCountByQrcode(qrcodeIds), Long.class, Integer.class);
        } catch (Exception e) {
            log.error("根据群id集合最近7天活跃人数.[get7DayActiveUserCountByQrcode]:" + e.getMessage(), e);
        }
        if (map == null) {
            return new HashMap<>();
        }
        return map;
    }

    @ParamLog("根据用户微信ID获取用户信息")
    public GroupUserDTO getWxUserInfoByWxUserId(String wxUserId) {
        GroupUserDTO dto = new GroupUserDTO();
        try {
            dto = ResponseHandleUtil.parseResponse(groupMemberService.getWxUserInfoByWxId(wxUserId), GroupUserDTO.class);
        } catch (Exception e) {
            log.error("根据用户微信ID获取用户信息.[getWxUserInfoByWxId]:" + e.getMessage(), e);
        }
        return dto;
    }

    @ParamLog(value = "获取可用机器人")
    public SelfRobotDTO getAvailableRobot(Long wechatUserId, Integer largeTemplet, Long classifyId) {
        SelfRobotDTO selfRobotDTO = null;
        try {
            selfRobotDTO = ResponseHandleUtil.parseResponse(selfRobotService.getAvailableRobot(wechatUserId, largeTemplet, classifyId), SelfRobotDTO.class);
        } catch (Exception e) {
            log.error("获取可用机器人.[getAvailableRobot]:" + e.getMessage(), e);
        }
        return selfRobotDTO;
    }

    @ParamLog(value = "根据群id集合最近7天群活跃度")
    public Map<Long,Integer> get7DayActiveCountByQrcode(List<Long> qrcodeIds) {
        Map<Long, Integer> map = new HashMap<>();
        try {
            map = ResponseHandleUtil.parseMapResponse(messageService.get7DayActiveCountByQrcode(qrcodeIds), Long.class, Integer.class);
        } catch (Exception e) {
            log.error("根据群id集合最近7天群活跃度.[get7DayActiveCountByQrcode]:" + e.getMessage(), e);
        }
        if (map == null) {
            return new HashMap<>();
        }
        return map;
    }

    @ParamLog(value = "获取可用机器人")
    public SelfRobotDTO getAvailableRobotByBookGroup(Long wechatUserId, Integer largeTemplet, Long bookGroupId) {
        SelfRobotDTO selfRobotDTO = null;
        try {
            selfRobotDTO = ResponseHandleUtil.parseResponse(selfRobotService.getAvailableRobotByBookGroup(wechatUserId, largeTemplet, bookGroupId), SelfRobotDTO.class);
        } catch (Exception e) {
            log.error("获取可用机器人.[getAvailableRobotByBookGroup]:" + e.getMessage(), e);
        }
        return selfRobotDTO;
    }
}
