package com.tanpu.community.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanpu.common.api.CommonResp;
import com.tanpu.common.constant.BizStatus;
import com.tanpu.common.exception.BizException;
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.resp.Customer;
import com.tanpu.community.api.beans.vo.feign.fatools.UserInfoNew;
import com.tanpu.community.api.beans.vo.feign.fatools.UserInfoOrg;
import com.tanpu.community.api.enums.OperationTypeEnum;
import com.tanpu.community.api.enums.QueryFollowTypeEnum;
import com.tanpu.community.dao.entity.community.FollowRelEntity;
import com.tanpu.community.dao.entity.fund.CompanyInfo;
import com.tanpu.community.dao.entity.fund.FundInfo;
import com.tanpu.community.dao.entity.jydb.MfAdvisorscalerank;
import com.tanpu.community.dao.entity.jydb.MfInvestadvisoroutline;
import com.tanpu.community.dao.entity.user.UserInfoEntity;
import com.tanpu.community.dao.mapper.community.FollowRelMapper;
import com.tanpu.community.dao.mapper.fund.CompanyInfoMapper;
import com.tanpu.community.dao.mapper.fund.FundInfoMapper;
import com.tanpu.community.dao.mapper.jydb.MfAdvisorscalerankMapper;
import com.tanpu.community.dao.mapper.jydb.MfInvestadvisoroutlineMapper;
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.tanpuroom.FeignClientForTanpuroom;
import com.tanpu.community.service.FollowRelService;
import com.tanpu.community.service.UserInfoService;
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 org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class HomePageManager {

    @Resource
    private FollowRelService followRelService;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private FeignClientForFatools feignClientForFatools;
    @Resource
    private FollowRelMapper followRelMapper;
    @Resource
    private MfInvestadvisoroutlineMapper mfInvestadvisoroutlineMapper;
    @Resource
    private MfAdvisorscalerankMapper mfAdvisorscalerankMapper;
    @Resource
    private CompanyInfoMapper companyInfoMapper;
    @Resource
    private FundInfoMapper fundInfoMapper;
    @Resource
    private FeignClientForTanpuroom feignClientForTanpuroom;
    @Resource
    private FeignClientForDiagnose feignClientForDiagnose;
    @Resource
    private FeignClientForCourse feignClientForCourse;

    //查询 个人中心 相关信息
    public UserInfoNew queryUsersListNew(String userIdMyself, String userId) {
        CommonResp<UserInfoNew> queryUsersListNew = feignClientForFatools.queryUsersListNew(StringUtils.isNotBlank(userId) ? userId : userIdMyself);
        if (queryUsersListNew.isNotSuccess())  new BizException("内部接口调用失败");
        UserInfoNew userInfoNew = queryUsersListNew.getData();
        // 关注 按钮的显示逻辑
        if (StringUtils.isNotBlank(userId)) { //查询别人的个人主页
            userInfoNew.setIsShowFollowButton(0);
            //是否已关注
            FollowRelEntity followRelEntity = followRelService.queryRecord(userId, userIdMyself);
            if (ObjectUtils.allNotNull(followRelEntity) && BizStatus.DeleteTag.tag_init == followRelEntity.getDeleteTag()){
                userInfoNew.setShowFollowStatus(1); // 已关注
            } else {
                userInfoNew.setShowFollowStatus(0); // 未关注
            }
        } else {
            // 查询自己的主页
            userInfoNew.setIsShowFollowButton(1);
            userId = userIdMyself;
        }
        //设置粉丝数 关注数
        getFansNUmAndFollowNum(userInfoNew);

        // 主页类型 显示逻辑
        if (50 == userInfoNew.getLevelGrade()){
            userInfoNew.setPersonalCenterType(2);
            // 首席投顾 添加专栏信息 (前端自己取)
            // 成功案例客户
            // 默认显示该投顾管理的客户里,总资产最高的客户
            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().getUserId());
                } else {
                    userInfoNew.getUserInfoNewChief().setClientId(null);
                }
            }
        } else if (2 == userInfoNew.getUserType()){
            // 机构账号
            userInfoNew.setPersonalCenterType(3);
            if (0 == userInfoNew.getUserInfoNewOrg().getBelongOrgType() && StringUtils.isNotBlank(userInfoNew.getUserInfoNewOrg().getBelongOrgId())){ // 公募
                //设置 基金数
                MfAdvisorscalerank mfAdvisorscalerank = mfAdvisorscalerankMapper.selectOne(new LambdaQueryWrapper<MfAdvisorscalerank>()
                        .eq(MfAdvisorscalerank::getInvestadvisorcode, userInfoNew.getUserInfoNewOrg().getBelongOrgId())
                        .last("limit 1"));
                userInfoNew.setFundNumber(ObjectUtils.anyNotNull(mfAdvisorscalerank) ? mfAdvisorscalerank.getTotalfundn() : null);
                //设置成立时间 和 备案编号(公募没有备案编号)
                MfInvestadvisoroutline mfInvestadvisoroutline = mfInvestadvisoroutlineMapper.selectOne(new LambdaQueryWrapper<MfInvestadvisoroutline>()
                        .eq(MfInvestadvisoroutline::getInvestadvisorcode, userInfoNew.getUserInfoNewOrg().getBelongOrgId())
                        .last("limit 1"));
                userInfoNew.setFounded(ObjectUtils.anyNotNull(mfInvestadvisoroutline) ? mfInvestadvisoroutline.getEstablishmentdate().getTime() : null);
            }
            if(1 == userInfoNew.getUserInfoNewOrg().getBelongOrgType() && StringUtils.isNotBlank(userInfoNew.getUserInfoNewOrg().getBelongOrgId())){ // 私募
                //设置 基金数
                Integer integer = fundInfoMapper.selectCount(new LambdaQueryWrapper<FundInfo>().eq(FundInfo::getTrustId, userInfoNew.getUserInfoNewOrg().getBelongOrgId()));
                userInfoNew.setFundNumber(integer);

                //设置成立时间 和 备案编号
                CompanyInfo companyInfo = companyInfoMapper.selectById(userInfoNew.getUserInfoNewOrg().getBelongOrgId());
                if (ObjectUtils.anyNotNull(companyInfo)) {
                    userInfoNew.setFounded(companyInfo.getEstablishDate().getTime());
                    userInfoNew.setRecordNumber(companyInfo.getRegisterNumber());
                }
            }
            //设置团队成员
            CommonResp<List<UserInfoOrg>> usetInfoByOrgUserId = feignClientForFatools.getUsetInfoByOrgUserId(userId);
            if (usetInfoByOrgUserId.isSuccess()){
                List<UserInfoOrg> userInfoOrgs = usetInfoByOrgUserId.getData();
                // 设置关注列表
                List<String> collect = userInfoOrgs.stream().map(UserInfoOrg::getUserId).collect(Collectors.toList());
                List<FollowRelEntity> followRelEntities = followRelMapper.selectList(new LambdaQueryWrapper<FollowRelEntity>()
                        .eq(FollowRelEntity::getFollowerId, userId)
                        .in(FollowRelEntity::getFollowUserId, collect)
                        .eq(FollowRelEntity::getDeleteTag, BizStatus.DeleteTag.tag_init));
                Map<String, FollowRelEntity> collect1 = followRelEntities.stream().collect(Collectors.toMap(FollowRelEntity::getFollowUserId, Function.identity()));
                userInfoOrgs.forEach(userInfoOrg -> {
                    if (collect1.containsKey(userInfoOrg.getUserId())) userInfoOrg.setIsFollower(1);
                });
                userInfoNew.setUserInfoOrgList(userInfoOrgs);
            }

        } else {
            //普通主页
            userInfoNew.setPersonalCenterType(1);
            //设置课程数(学习数)
            CommonResp<Integer> integerCommonResp = feignClientForCourse.getStudyCourseCount(userId);
            if (integerCommonResp.isSuccess()) userInfoNew.setCourseNumber(integerCommonResp.getData());
        }
        return userInfoNew;
    }

    private void getFansNUmAndFollowNum(UserInfoNew userInfoNew) {
        Integer followNumber = followRelMapper.selectCount(new LambdaQueryWrapper<FollowRelEntity>().eq(FollowRelEntity::getFollowUserId, userInfoNew.getUserId())
                .eq(FollowRelEntity::getDeleteTag, BizStatus.DeleteTag.tag_init));
        Integer fansNumber = followRelMapper.selectCount(new LambdaQueryWrapper<FollowRelEntity>().eq(FollowRelEntity::getFollowerId, 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<>();
    }


    //获取用户关注、粉丝列表
    public Page<FollowQo> queryFollow(QueryFollowReq req, String userId) {
        List<String> userIds = QueryFollowTypeEnum.QUERY_FANS.getCode().equals(req.getQueryType()) ?
                followRelService.queryFansByIdolId(req.getUserId()) : followRelService.queryFansByFollowerId(req.getUserId());
        List<FollowQo> followQos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(userIds)) {
            List<UserInfoEntity> userInfos = userInfoService.queryUserByIds(userIds);
            List<FollowQo> collect = userInfos.stream().map(ConvertUtil::userInfoEntity2FollowQo).collect(Collectors.toList());
            followQos = judgeFollowed(collect, userId);

        }
        //分页
        return PageUtils.page(req.getPage(), followQos);
    }


    //判断返回列表中的用户是否被当前用户关注
    public List<FollowQo> judgeFollowed(List<FollowQo> followQos, String followerId) {
        Set<String> idolSet = new HashSet<>(followRelService.queryFansByFollowerId(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())) {
            followRelService.addFollowRel(req.getFollowUserId(), followerId);
        } else if (OperationTypeEnum.CANCEL.getCode().equals(req.getType())) {
            followRelService.deleteFollowRel(req.getFollowUserId(), followerId);
        }
    }



}