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.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.*;
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.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.stereotype.Service;

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 FeignClientForFatools feignClientForFatools;
    @Resource
    private FollowRelMapper followRelMapper;
    @Resource
    private FeignClientForDiagnose feignClientForDiagnose;
    @Resource
    private FeignClientForCourse feignClientForCourse;
    @Resource
    private FeignForFund feignForFund;
    @Resource
    private FeignForPublicFund feignForPublicFund;

    //查询 个人中心 相关信息
    public UserInfoResp queryUsersInfo(String userIdMyself, String userId) {
        CommonResp<UserInfoResp> queryUsersListNew = feignClientForFatools.queryUsersListNew(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);
                }
            }


        } 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());
                    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());
                    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>()
                        .eq(FollowRelEntity::getIdolId, userId)
                        .in(FollowRelEntity::getFansId, collect)
                        .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());
        }
        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<>();
    }


    //获取用户关注、粉丝列表
    public Page<FollowQo> queryFollow(QueryFollowReq req, String userId) {
        //TODO 数据库分页
        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<UserInfoResp> userInfoNews = feignClientForFatools.queryUserListNew(userIds);
            List<FollowQo> collect = userInfoNews.stream().map(ConvertUtil::userInfoNew2FollowQo).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);
        }
    }


}