package com.pcloud.book.consumer.reader;

import cn.hutool.core.collection.CollUtil;
import com.pcloud.book.applet.dto.SpecialBookDTO;
import com.pcloud.channelcenter.base.exceptions.ChannelBizException;
import com.pcloud.readercenter.wechat.dto.NickNameAndOpenIdDto;
import java.util.ArrayList;
import java.util.Date;
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 com.pcloud.readercenter.wechat.dto.SpecialBookDTO4Reader;
import com.pcloud.readercenter.wechat.dto.SpecialBookQueryDTO4Reader;
import com.pcloud.usercenter.party.agent.dto.AgentCity;
import com.pcloud.usercenter.party.agent.service.AgentService;
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;
    @Autowired
    private AgentService agentService;

    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;
    }

    public String getCityCodeByWechatUserId(Long wechatUserId) {
        LOGGER.info("根据wechatUserId查询cityCode:{}", wechatUserId);
        String cityCode = null;
        try {
            cityCode = ResponseHandleUtil.parseResponse(appUserService.getCityCodeByWechatUserId(wechatUserId), String.class);
            LOGGER.info("根据wechatUserId查询cityCode结束：{}", cityCode);
        } catch (BizException e) {
            throw new BizException(e.getCode(), e.getMessage());
        }
        return cityCode;
    }

    public Map<Long, AgentCity> getAgentPositionByAdviserIds(List<Long> advisers) {
        LOGGER.info("根据advisers查询出版社地理位置:{}", advisers);
        Map<Long, AgentCity> map = CollUtil.newHashMap(0);
        try {
            map = ResponseHandleUtil.parseMap(agentService.getAgentPositionByAdviserIds(advisers), Long.class, AgentCity.class);
        } catch (Exception e) {
            LOGGER.error("ReaderConsr.getAgentPositionByAdviserIds 根据advisers查询出版社地理位置失败", e);
        }
        return map;
    }

    public void deleteGroupRecore(List<Long> groupIds, Integer groupType, Integer updateType, Integer showState) {
        LOGGER.info("根据deleteGroupRecore groupIds:{},groupType:{},updateType:{}, showState:{}", groupIds, groupType, updateType, showState);
        try {
            wechatUserService.deleteGroupRecore(groupIds, groupType, updateType, showState);
            LOGGER.info("根据deleteGroupRecore结束");
        } catch (BizException e) {
            throw new BizException(e.getCode(), e.getMessage());
        }
    }

    @ParamLog("公众号用户数量")
    public Integer getAccountUserCountByTime(Long officialAccountsId, String startTime, String endTime){
        Integer count = 0;
        try {
            count = ResponseHandleUtil.parseResponse(wechatUserService.getAccountUserCountByTime(officialAccountsId, startTime, endTime),Integer.class);
        }catch (Exception e){
            LOGGER.error("调用getAccountUserCountByTime失败"+e.getMessage(),e);
        }
        return count;
    }

    public Map<Long, SpecialBookDTO4Reader> getAppletStatisticsMap(SpecialBookQueryDTO4Reader specialBookQueryDTO) {
        LOGGER.info("小程序用户统计数据");
        Map<Long, SpecialBookDTO4Reader> map = new HashMap<>();
        try {
            map = ResponseHandleUtil.parseMapResponse(wechatUserService.getAppletStatisticsMap(specialBookQueryDTO), Long.class, SpecialBookDTO4Reader.class);

        } catch (Exception e) {
            LOGGER.error("小程序用户统计数据.[getAppletStatisticsMap]失败" + e.getMessage(), e);
        }
        return map;
    }

    public List<Long> getWechatUserByNameOrId(String wechatUser) {
        LOGGER.info("根据名称或id获取用户id");
        List<Long> wechatUserIds = new ArrayList<>();
        try {
            wechatUserIds = ResponseHandleUtil.parseList(wechatUserService.getWechatUserByNameOrId(wechatUser), Long.class);

        } catch (Exception e) {
            LOGGER.error("根据名称或id获取用户id.[getWechatUserByNameOrId]失败" + e.getMessage(), e);
        }
        return wechatUserIds;
    }

    public List<Long> getWechatUserIdsByUserProfile(String cityCode, String startTime, String endTime) {
        LOGGER.info("根据名称或id获取用户id");
        List<Long> wechatUserIds = new ArrayList<>();
        try {
            wechatUserIds = ResponseHandleUtil.parseList(wechatUserService.getWechatUserIdsByUserProfile(cityCode, startTime, endTime), Long.class);
        } catch (Exception e) {
            LOGGER.error("根据用户画像获取用户id.[getWechatUserByNameOrId]失败" + e.getMessage(), e);
        }
        return wechatUserIds;
    }

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

    public List<Long> getMiniUsersByBookIds(List<Long> bookIds) {
        LOGGER.info("根据名称或id获取用户id");
        List<Long> wechatUserIds = new ArrayList<>();
        try {
            wechatUserIds = ResponseHandleUtil.parseList(wechatUserService.getMiniUsersByBookIds(bookIds), Long.class);
        } catch (Exception e) {
            LOGGER.error("根据用户画像获取用户id.[getWechatUserByNameOrId]失败" + e.getMessage(), e);
        }
        return wechatUserIds;
    }
}


