package com.tanpu.community.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanpu.biz.common.enums.user.UserLevelEnum;
import com.tanpu.biz.common.enums.user.UserTypeEnum;
import com.tanpu.common.api.CommonResp;
import com.tanpu.common.constant.BizStatus;
import com.tanpu.common.exception.BizException;
import com.tanpu.common.util.DateUtils;
import com.tanpu.community.api.beans.qo.FollowQo;
import com.tanpu.community.api.beans.req.homepage.FollowRelReq;
import com.tanpu.community.api.beans.req.homepage.QueryFollowReq;
import com.tanpu.community.api.beans.req.page.Page;
import com.tanpu.community.api.beans.req.page.Pageable;
import com.tanpu.community.api.beans.resp.Customer;
import com.tanpu.community.api.beans.vo.feign.fatools.UserInfoNewChief;
import com.tanpu.community.api.beans.vo.feign.fatools.UserInfoOrg;
import com.tanpu.community.api.beans.vo.feign.fatools.UserInfoResp;
import com.tanpu.community.api.beans.vo.feign.fund.FundCompanySimpleVO;
import com.tanpu.community.api.enums.FundCompanyTypeEnum;
import com.tanpu.community.api.enums.NotificationTypeEnum;
import com.tanpu.community.api.enums.OperationTypeEnum;
import com.tanpu.community.api.enums.PersonalCenterTypeEnum;
import com.tanpu.community.api.enums.QueryFollowTypeEnum;
import com.tanpu.community.api.enums.ShowFollowStatusEnum;
import com.tanpu.community.cache.RedisCache;
import com.tanpu.community.dao.entity.community.FollowRelEntity;
import com.tanpu.community.dao.mapper.community.FollowRelMapper;
import com.tanpu.community.feign.course.FeignClientForCourse;
import com.tanpu.community.feign.diagnose.FeignClientForDiagnose;
import com.tanpu.community.feign.fatools.FeignClientForFatools;
import com.tanpu.community.feign.product.FeignForFund;
import com.tanpu.community.feign.product.FeignForPublicFund;
import com.tanpu.community.service.FollowRelService;
import com.tanpu.community.service.NotificationService;
import com.tanpu.community.util.ConvertUtil;
import com.tanpu.community.util.PageUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.tanpu.community.api.constants.RedisKeyConstant.CACHE_FEIGN_USER_INFO;

@Service
public class HomePageManager {

    @Resource
    private FollowRelService followRelService;
    @Resource
    private FeignClientForFatools feignClientForFatools;
    @Resource
    private FollowRelMapper followRelMapper;
    @Resource
    private FeignClientForDiagnose feignClientForDiagnose;
    @Resource
    private FeignClientForCourse feignClientForCourse;
    @Resource
    private FeignForFund feignForFund;
    @Resource
    private FeignForPublicFund feignForPublicFund;
    @Resource
    private RedisCache redisCache;

    @Autowired
    private NotificationService notificationService;

    //查询 个人中心 相关信息
    public UserInfoResp queryUsersInfo(String userIdMyself, String userId) {
        CommonResp<UserInfoResp> queryUsersListNew = feignClientForFatools.queryUserInfoNew(StringUtils.isNotBlank(userId) ? userId : userIdMyself);
        if (queryUsersListNew.isNotSuccess() || !ObjectUtils.anyNotNull(queryUsersListNew.getData()))
            throw new BizException("内部接口调用失败");
        UserInfoResp userInfoNew = queryUsersListNew.getData();

        if (StringUtils.isNotBlank(userId) && !StringUtils.equals(userIdMyself, userId)) { //查询别人的个人主页
            // 关注 按钮的显示逻辑
            FollowRelEntity followRelEntity = followRelService.queryRecord(userId, userIdMyself);
            if (ObjectUtils.allNotNull(followRelEntity) && BizStatus.DeleteTag.tag_init == followRelEntity.getDeleteTag()) {
                userInfoNew.setShowFollowStatus(ShowFollowStatusEnum.FOLLOWED.getCode()); // 已关注
            } else {
                userInfoNew.setShowFollowStatus(ShowFollowStatusEnum.NOT_FOLLOWED.getCode()); // 未关注
            }
            if (userInfoNew.getWorkshopStatus() == 2) userInfoNew.setWorkshopStatus(1); //别人的主页不需要展示 工作室
        } else {
            // 查询自己的主页
            userId = userIdMyself;
        }
        //获取粉丝数 关注数
        getFansNUmAndFollowNum(userInfoNew);

        // 主页类型 显示逻辑
        if (UserLevelEnum.USER_CHIEF_FINANCIAL_ADVISER.getCode() == userInfoNew.getLevelGrade()) {
            // 首席投顾
            userInfoNew.setPersonalCenterType(PersonalCenterTypeEnum.CHIEF.getCode());
            // 成功案例客户
            // 默认显示该投顾管理的客户里,总资产最高的客户
            if (StringUtils.isBlank(userInfoNew.getUserInfoNewChief().getClientId())) {
                List<Customer> customers = queryUserCustomerList(userId);
                Optional<Customer> first = customers.stream().max(Comparator.comparing(Customer::getTotalMarket));
                if (first.isPresent()) {
                    userInfoNew.getUserInfoNewChief().setClientId(first.get().getCustomerId());
                } else {
                    userInfoNew.getUserInfoNewChief().setClientId(null);
                }
            }
            // 查询首席投顾数量
            CommonResp<Page<UserInfoNewChief>> pageCommonResp = feignClientForFatools.queryChiefFinancialAdviserList(1, 1);
            if (pageCommonResp.isSuccess()) {
                userInfoNew.getUserInfoNewChief().setChiefCount(pageCommonResp.getData().getTotalSize());
            } else {
                userInfoNew.getUserInfoNewChief().setChiefCount(0L);
            }


        } else if (UserTypeEnum.USER_ORG.getCode() == userInfoNew.getUserType()) {
            // 机构账号
            userInfoNew.setPersonalCenterType(PersonalCenterTypeEnum.ORG.getCode());
            if (FundCompanyTypeEnum.PUBLIC.getCode() == userInfoNew.getUserInfoNewOrg().getRelationFundCompanyType() && StringUtils.isNotBlank(userInfoNew.getUserInfoNewOrg().getRelationFundCompanyId())) { // 公募
                // 设置 基金数
                CommonResp<FundCompanySimpleVO> companyFundCount = feignForPublicFund.getCompanyFundCount(userInfoNew.getUserInfoNewOrg().getRelationFundCompanyId());
                userInfoNew.setFundNumber(companyFundCount.isSuccess() ? companyFundCount.getData().getFundCount() : 0);
                // 设置成立时间 和 备案编号(公募没有备案编号)
                CommonResp<FundCompanySimpleVO> fundCompanyInfoSimple = feignForPublicFund.getFundCompanyInfoSimple(userInfoNew.getUserInfoNewOrg().getRelationFundCompanyId());
                if (fundCompanyInfoSimple.isSuccess()) {
                    FundCompanySimpleVO data = fundCompanyInfoSimple.getData();
                    userInfoNew.setFounded(data.getEstablishDate() > 0 ? DateUtils.formatYMD(new Date(data.getEstablishDate())) : null);
                    userInfoNew.setRecordNumber(data.getRegisterNumber());
                }
            }
            if (FundCompanyTypeEnum.PRIVATE.getCode() == userInfoNew.getUserInfoNewOrg().getRelationFundCompanyType() && StringUtils.isNotBlank(userInfoNew.getUserInfoNewOrg().getRelationFundCompanyId())) { // 私募
                // 设置成立时间 和 备案编号
                CommonResp<FundCompanySimpleVO> fundCompanyInfoSimple = feignForFund.getFundCompanyInfoSimple(userInfoNew.getUserInfoNewOrg().getRelationFundCompanyId());
                if (fundCompanyInfoSimple.isSuccess()) {
                    FundCompanySimpleVO data = fundCompanyInfoSimple.getData();
                    userInfoNew.setFounded(data.getEstablishDate() > 0 ? DateUtils.formatYMD(new Date(data.getEstablishDate())) : null);
                    userInfoNew.setRecordNumber(data.getRegisterNumber());
                }
                // 设置 基金数
                CommonResp<FundCompanySimpleVO> companyFundCount = feignForFund.getCompanyFundCount(userInfoNew.getUserInfoNewOrg().getRelationFundCompanyId());
                userInfoNew.setFundNumber(companyFundCount.isSuccess() ? companyFundCount.getData().getFundCount() : 0);
            }
            //设置团队成员
            CommonResp<List<UserInfoOrg>> usetInfoByOrgUserId = feignClientForFatools.getUsetInfoByOrgUserId(userId);
            if (usetInfoByOrgUserId.isSuccess() && CollectionUtils.isNotEmpty(usetInfoByOrgUserId.getData())) {
                List<UserInfoOrg> userInfoOrgs = usetInfoByOrgUserId.getData();
                // 设置关注列表
                List<String> collect = userInfoOrgs.stream().map(UserInfoOrg::getUserId).collect(Collectors.toList());
                List<FollowRelEntity> followRelEntities = followRelMapper.selectList(new LambdaQueryWrapper<FollowRelEntity>()
                        .in(FollowRelEntity::getIdolId, collect)
                        .eq(FollowRelEntity::getFansId, userIdMyself)
                        .eq(FollowRelEntity::getDeleteTag, BizStatus.DeleteTag.tag_init));
                Map<String, FollowRelEntity> collect1 = followRelEntities.stream().collect(Collectors.toMap(FollowRelEntity::getIdolId, Function.identity()));
                userInfoOrgs.forEach(userInfoOrg -> {
                    if (collect1.containsKey(userInfoOrg.getUserId()))
                        userInfoOrg.setIsFollower(ShowFollowStatusEnum.FOLLOWED.getCode());//1已关注
                });
                userInfoNew.setUserInfoOrgList(userInfoOrgs);
            }

        } else {
            //普通主页
            userInfoNew.setPersonalCenterType(PersonalCenterTypeEnum.GENERAL.getCode());
            //设置课程数(学习数)
            CommonResp<Integer> integerCommonResp = feignClientForCourse.getStudyCourseCount(userId);
            if (integerCommonResp.isSuccess()) userInfoNew.setCourseNumber(integerCommonResp.getData());
        }
        //刷新用户缓存
        redisCache.put(StringUtils.joinWith("_", CACHE_FEIGN_USER_INFO, userId), userInfoNew, 60);

        return userInfoNew;
    }

    public Page<UserInfoNewChief> queryChiefFinancialAdviserList(Pageable page) {
        CommonResp<Page<UserInfoNewChief>> pageCommonResp = feignClientForFatools.queryChiefFinancialAdviserList(page.pageNumber, page.pageSize);
        return pageCommonResp.getData();

    }

    private void getFansNUmAndFollowNum(UserInfoResp userInfoNew) {
        Integer fansNumber = followRelMapper.selectCount(new LambdaQueryWrapper<FollowRelEntity>().eq(FollowRelEntity::getIdolId, userInfoNew.getUserId())
                .eq(FollowRelEntity::getDeleteTag, BizStatus.DeleteTag.tag_init));
        Integer followNumber = followRelMapper.selectCount(new LambdaQueryWrapper<FollowRelEntity>().eq(FollowRelEntity::getFansId, userInfoNew.getUserId())
                .eq(FollowRelEntity::getDeleteTag, BizStatus.DeleteTag.tag_init));
        userInfoNew.setFollowNumber(followNumber);
        userInfoNew.setFansNumber(fansNumber);
    }

    public List<Customer> queryUserCustomerList(String userId) {
        CommonResp<List<Customer>> ifaCustomerList = feignClientForDiagnose.getIfaCustomerList(userId);
        if (ifaCustomerList.isSuccess()) return ifaCustomerList.getData();
        return new ArrayList<>();
    }


    /**
     * 用户关注列表
     *
     * @param req    目标用户
     * @param userId 当前用户
     * @return
     */
    public Page<FollowQo> queryFollow(QueryFollowReq req, String userId) {
        //数据库分页
        Integer pageSize = req.page.pageSize;
        Integer pageNumber = req.page.pageNumber;

        Page<String> userIdsPage = QueryFollowTypeEnum.QUERY_FANS.getCode().equals(req.getQueryType()) ?
                followRelService.queryFansByIdolId(req.userId, pageNumber, pageSize)
                : followRelService.queryIdolsByFansId(req.userId, pageNumber, pageSize);
        List<FollowQo> followQos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(userIdsPage.getContent())) {
            List<UserInfoResp> userInfoNews = feignClientForFatools.queryUserListNew(userIdsPage.getContent());
            List<FollowQo> collect = userInfoNews.stream().map(ConvertUtil::userInfoNew2FollowQo).collect(Collectors.toList());
            followQos = judgeFollowed(collect, userId);
        }
        return PageUtils.page(userIdsPage, followQos);
    }


    //判断返回列表中的用户是否被当前用户关注
    public List<FollowQo> judgeFollowed(List<FollowQo> followQos, String followerId) {
        Set<String> idolSet = new HashSet<>(followRelService.queryIdolsByFansId(followerId));
        return followQos.stream().map(o -> {
            if (idolSet.contains(o.getUserId())) {
                o.setFollowed(true);
            }
            return o;
        }).collect(Collectors.toList());

    }

    public void addFollowRel(FollowRelReq req, String followerId) {
        if (OperationTypeEnum.CONFIRM.getCode().equals(req.getType())) {
            // 第一次关注才有消息通知
            if (followRelService.addFollowRel(req.getFollowUserId(), followerId)) {
                notificationService.insert(followerId, req.getFollowUserId(), NotificationTypeEnum.FOLLOW, req.getFollowUserId(), null);
                notificationService.putNotifyCache(req.getFollowUserId(), followerId,NotificationTypeEnum.FOLLOW);
            }
        } else if (OperationTypeEnum.CANCEL.getCode().equals(req.getType())) {
            followRelService.deleteFollowRel(req.getFollowUserId(), followerId);
        }
    }

    private UserInfoResp getUserInfo(String authorId) {
        CommonResp<UserInfoResp> userInfoNewCommonResp = feignClientForFatools.queryUserInfoNew(authorId);
        if (userInfoNewCommonResp.isNotSuccess()) {
            throw new BizException("内部接口调用失败");
        }
        return userInfoNewCommonResp.getData();
    }

}