package com.pcloud.book.consumer.reader;

import com.pcloud.channelcenter.base.exceptions.ChannelBizException;
import com.pcloud.readercenter.wechat.dto.NickNameAndOpenIdDto;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.pcloud.common.dto.ResponseDto;
import com.pcloud.common.utils.string.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import com.alibaba.druid.support.json.JSONUtils;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.ResponseHandleUtil;
import com.pcloud.readercenter.appUser.service.AppUserService;
import com.pcloud.readercenter.wechat.dto.MiniUserDto;
import com.pcloud.readercenter.wechat.dto.ReaderMessageDto;
import com.pcloud.readercenter.wechat.dto.WechatUserRobotDto;
import com.pcloud.readercenter.wechat.entity.WechatUser;
import com.pcloud.readercenter.wechat.service.WechatUserService;

/**
 * @author lily
 * @date 2018/12/26 16:49
 */
@Component("readerConsr")
public class ReaderConsr {
    /**
     * logger
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ReaderConsr.class);

    @Autowired
    private WechatUserService wechatUserService;
    @Autowired
    private AppUserService appUserService;

    public WechatUser getWechatUser(Long wechatUserId) throws BizException {
        if (wechatUserId == null) {
            return null;
        }
        try {
            return ResponseHandleUtil.parseResponse(wechatUserService.getWechatUser(wechatUserId), WechatUser.class);
        } catch (Exception e) {
            LOGGER.error("获取微信用户信息失败[wechatUserService.getWechatUser]:" + e.getMessage(), e);
        }
        return null;
    }

    public Map<Long, WechatUser> getUserList(List<Long> wechatUserIds) throws BizException {
        if (ListUtils.isEmpty(wechatUserIds)) {
            return new HashMap<>();
        }
        try {
            return ResponseHandleUtil.parseMap(wechatUserService.getUserList(wechatUserIds), Long.class, WechatUser.class);
        } catch (Exception e) {
            LOGGER.error("获取微信用户信息失败[wechatUserService.getUserList]:" + e.getMessage(), e);
        }
        return null;
    }

    @ParamLog(value = "随机获取n个用户", isAfterReturn = false)
    public List<WechatUserRobotDto> selectRobotsRandom(Integer number) throws BizException {
        if (number == null) {
            return null;
        }
        try {
            return ResponseHandleUtil.parseListResponse(wechatUserService.selectRobotsRandom(number), WechatUserRobotDto.class);
        } catch (Exception e) {
            LOGGER.error("随机获取n个用户失败[wechatUserService.getWechatUserRand]:" + e.getMessage(), e);
        }
        return null;
    }


    @ParamLog("获取9个用户头像")
    public String getNineHeadUrl() {
        List<WechatUserRobotDto> wechatUsers = this.selectRobotsRandom(9);
        if (ListUtils.isEmpty(wechatUsers)) {
            return "";
        }
        List<String> headUrls = wechatUsers.stream().map(a -> a.getWechatUserHeadUrl()).collect(Collectors.toList());
        return JSONUtils.toJSONString(headUrls);
    }

    @ParamLog("获取n个用户头像")
    public List<String> getRandomHeadUrlList(Integer random) {
        List<WechatUserRobotDto> wechatUsers = this.selectRobotsRandom(random);
        if (ListUtils.isEmpty(wechatUsers)) {
            return new ArrayList<>();
        }
        List<String> headUrls = wechatUsers.stream().map(a -> a.getWechatUserHeadUrl()).collect(Collectors.toList());
        return headUrls;
    }


    @ParamLog(value = "获取wechatUserId", isAfterReturn = false)
    public Long getWechatUserId(String wxUserId,Long channelId) throws BizException {
        if (channelId == null || StringUtil.isEmpty(wxUserId)) {
            return null;
        }
        try {
            return ResponseHandleUtil.parseResponse(wechatUserService.getWechatUserId(wxUserId,channelId), Long.class);
        } catch (Exception e) {
            LOGGER.error("获取wechatUserId失败[wechatUserService.getWechatUserId]:" + e.getMessage(), e);
        }
        return null;
    }

    @ParamLog(value = "APP获取wechatUserId集合", isAfterReturn = false)
    public List<Long> getAppWechatUserIds(Long wechatUserId) {
        List<Long> list = ResponseHandleUtil.parseList(appUserService.getBusWechatUserIdByAppUserId(wechatUserId),Long.class);
        if(ListUtils.isEmpty(list)) {
            list.add(-1L);
        }
        return list;
    }

    //给小程序用户发送系统消息站内信
    public void sendNotifyMiniUser(ReaderMessageDto readerMessageDto) {
        try {
            wechatUserService.sendNotifyMiniUser(readerMessageDto);
        } catch (Exception e) {
            LOGGER.error("发送系统消息给小程序用户失败:" + e.getMessage(), e);
        }
    }

    //获取小程序和小睿关系
    public List<MiniUserDto> getSendUserRobotInfo(List<Long> wechatUserIds) {
        if(ListUtils.isEmpty(wechatUserIds)){
            return new ArrayList<>();
        }
        List<MiniUserDto> result=new ArrayList<>();
        try {
            ResponseEntity<ResponseDto<List<MiniUserDto>>> sendUserRobotInfo = wechatUserService.getSendUserRobotInfo(wechatUserIds);
            result=ResponseHandleUtil.parseList(sendUserRobotInfo,MiniUserDto.class);
        } catch (Exception e) {
            LOGGER.error("获取小程序和小睿关系失败:" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 去用户中心拿openId和nickname
     */
    public NickNameAndOpenIdDto getOpenIdAndNickName(Long wechatUserId, Long wechatId) throws BizException {
        LOGGER.info("【客户-用户(消)】获取用户的openId和name,<PARAM>.[wechatUserId]=" + wechatUserId + ",[wechatId]=" + wechatId);

        NickNameAndOpenIdDto nickNameAndOpenId = null;
        if (wechatUserId == null || wechatId == null) {
            LOGGER.info("【客户-用户(消)】获取用户的openId和name,<PARAM=NULL>");
            return nickNameAndOpenId;
        }

        try {
            nickNameAndOpenId = ResponseHandleUtil.parseResponse(wechatUserService.getOpenIdAndNickName(wechatUserId, wechatId), NickNameAndOpenIdDto.class);
            LOGGER.info("【客户-用户(消)】获取用户的openId和name,<END>.[nickNameAndOpenId]=" + nickNameAndOpenId.toString());
        } catch (BizException e) {
            throw new BizException(e.getCode(), e.getMessage());
        } catch (Exception e) {
            LOGGER.error("【客户-用户(消)】获取用户的openId和name.<ERROR>[getOpenIdAndNickName]:" + e.getMessage(), e);
            throw new ChannelBizException(ChannelBizException.INVOKE_USER_ERROR, "获取用户信息失败~!");
        }
        return nickNameAndOpenId == null ? new NickNameAndOpenIdDto() : nickNameAndOpenId;
    }

    /**
     * 获取用户openId
     */
    public String getOpenIdByWechatUserIdAndOfficialAccountsId(Long wechatUserId, Long accountSettingId) throws BizException {
        LOGGER.info("获取用户openId,参数列表[wechatUserId:" + wechatUserId + "accountSettingId:" + accountSettingId + "]");

        String openId = "";
        if (wechatUserId == null || accountSettingId == null) {
            LOGGER.error("获取用户openId,参数为空");
            return openId;
        }

        try {
            openId = ResponseHandleUtil.parseResponse(wechatUserService.getOpenIdByWechatUserIdAndOfficialAccountsId(wechatUserId, accountSettingId), String.class);
            LOGGER.info("获取用户openId结束");
        } catch (BizException e) {
            throw new BizException(e.getCode(), e.getMessage());
        } catch (Exception e) {
            LOGGER.error("获取用户openId失败:【wechatUserService.getOpenIdByWechatUserIdAndOfficialAccountsId】" + e.getMessage(), e);
            throw new ChannelBizException(ChannelBizException.INVOKE_ERROR, "获取用户信息失败~!");
        }
        return openId;
    }

}


