package com.tanpu.community.service;

import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.tanpu.biz.common.enums.RelTypeEnum;
import com.tanpu.biz.common.enums.user.UserLevelEnum;
import com.tanpu.common.api.CommonResp;
import com.tanpu.common.enums.fund.ProductTypeEnum;
import com.tanpu.common.util.JsonUtil;
import com.tanpu.community.api.CommunityConstant;
import com.tanpu.community.api.beans.qo.AttachmentDetailVo;
import com.tanpu.community.api.beans.qo.ThemeContentQo;
import com.tanpu.community.api.beans.qo.ThemeQo;
import com.tanpu.community.api.beans.vo.ImagesDTO;
import com.tanpu.community.api.beans.vo.feign.course.CourseSimpleResp;
import com.tanpu.community.api.beans.vo.feign.course.ShortVideoBaseInfoResp;
import com.tanpu.community.api.beans.vo.feign.fatools.UserInfoResp;
import com.tanpu.community.api.beans.vo.feign.product.FundInfoBaseResp;
import com.tanpu.community.api.beans.vo.feign.product.ProductInfoVO;
import com.tanpu.community.api.beans.vo.feign.zhibo.ZhiboListResp;
import com.tanpu.community.api.enums.FileChechStatusEnum;
import com.tanpu.community.dao.entity.community.FileRecordEntity;
import com.tanpu.community.dao.entity.community.TopicEntity;
import com.tanpu.community.feign.course.FeignClientForCourse;
import com.tanpu.community.feign.fatools.FeignClientForFatools;
import com.tanpu.community.feign.product.FeignClientForProducts;
import com.tanpu.community.feign.product.FeignForFund;
import com.tanpu.community.feign.product.FeignForPublicFund;
import com.tanpu.community.feign.tanpuroom.FeignClientForTanpuroom;
import com.tanpu.community.feign.zhibo.FeignClientForZhibo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

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

/**
 * 批量调用Feign查询接口
 */
@Service
public class BatchFeignCallService {


    @Resource
    private FeignClientForTanpuroom feignClientForTanpuroom;

    @Resource
    private FeignClientForZhibo feignClientForZhibo;

    @Resource
    private FeignClientForProducts feignForProduct;

    @Resource
    private FeignClientForCourse feignForCourse;

    @Resource
    private FeignForFund feignForFund;

    @Resource
    private FeignForPublicFund feignForPublicFund;

    @Resource
    private FeignClientForFatools feignClientForFatools;

    @Resource
    private OSSFileService ossFileService;

    @Autowired
    private FeignService feignService;

    @Resource
    private TopicService topicService;


    public void getAttachDetail(ThemeQo themeQo) {
        ArrayList<ThemeQo> themeQos = new ArrayList<>();
        themeQos.add(themeQo);
        getAttachDetailByBatch(themeQos);
    }


    public void getAttachDetailByBatch(List<ThemeQo> themeQos) {
        // 短视频信息
        Map<String, ShortVideoBaseInfoResp> shortVideoMap = Maps.newHashMap();
        // 课程信息
        Map<String, ShortVideoBaseInfoResp> curriculumMap = Maps.newHashMap();
        // 新课程信息
        Map<String, CourseSimpleResp> courseMap = Maps.newHashMap();
        // 直播信息
        Map<String, ZhiboListResp> zhiboMap = Maps.newHashMap();
        // 设置产品信息
        Map<String, FundInfoBaseResp> fundMap = Maps.newHashMap();
        // 图片信息
        Map<String, FileRecordEntity> imgMap = Maps.newHashMap();
        // 话题标题
        Map<String, String> topicMap = Maps.newHashMap();
        // 图片信息
        Map<String, UserInfoResp> userMap = Maps.newHashMap();
        // 批量查询资源信息
        this.getResInfo(shortVideoMap, curriculumMap, courseMap, zhiboMap, fundMap, imgMap, topicMap, userMap, themeQos);
        //逐个装入
        setResInfo(themeQos, shortVideoMap, curriculumMap, courseMap, zhiboMap, fundMap, imgMap, userMap, topicMap);

    }


    /**
     * 获取资源信息
     *
     * @param shortVideoMap
     * @param curriculumMap
     * @param zhiboMap
     * @param fundMap
     */
    private void getResInfo(Map<String, ShortVideoBaseInfoResp> shortVideoMap,
                            Map<String, ShortVideoBaseInfoResp> curriculumMap,
                            Map<String, CourseSimpleResp> courseMap,
                            Map<String, ZhiboListResp> zhiboMap,
                            Map<String, FundInfoBaseResp> fundMap,
                            Map<String, FileRecordEntity> imgMap,
                            Map<String, String> topicMap,
                            Map<String, UserInfoResp> userMap,
                            List<ThemeQo> themeQos
    ) {
        // 白名单基金id
        HashSet<String> tanpuFundIds = Sets.newHashSet();
        // 私募基金id
        HashSet<String> fundIds = Sets.newHashSet();
        // 理财师导入
        HashSet<String> ifaFundIds = Sets.newHashSet();
        // 公募基金id
        HashSet<String> publicFundIds = Sets.newHashSet();
        // 无净值产品id
        HashSet<String> notNetFundIds = Sets.newHashSet();
        // 短视频id
        HashSet<String> shortVideoIds = Sets.newHashSet();
        // 直播id
        HashSet<String> zhiboIds = Sets.newHashSet();
        // 课程id
        HashSet<String> curriculumIds = Sets.newHashSet();
        // 新课程id
        HashSet<String> courseIds = Sets.newHashSet();
        // 图片id
        HashSet<String> imageIds = Sets.newHashSet();
        // 话题id
        HashSet<String> topicIds = Sets.newHashSet();
        // 用户id
        HashSet<String> userIds = Sets.newHashSet();
        // 获取关联资源id
        if (themeQos != null) {
            themeQos.forEach(o -> {
                userIds.add(o.getAuthorId());
                if (o.getTopicId() != null) {
                    topicIds.add(o.getTopicId());
                }
            });

            themeQos.forEach(o -> o.getContent().forEach(c -> {
                        if (c.getType().equals(RelTypeEnum.LIVE.type)) {
                            zhiboIds.add(c.getValue());
                        } else if (c.getType().equals(RelTypeEnum.SHORT_VIDEO.type)) {
                            shortVideoIds.add(c.getValue());
                        } else if (c.getType().equals(RelTypeEnum.FUND.type)) {
                            if (c.getProductType() == ProductTypeEnum.PUBLIC.type) {
                                publicFundIds.add(c.getValue());
                            } else if (c.getProductType() == ProductTypeEnum.PRIVATE.type) {
                                fundIds.add(c.getValue());
                            } else if (c.getProductType() == ProductTypeEnum.TAMP.type) {
                                tanpuFundIds.add(c.getValue());
                            } else if (c.getProductType() == ProductTypeEnum.CUSTOMER_IMPORT.type) {
                                ifaFundIds.add(c.getValue());
                            } else if (c.getProductType() == ProductTypeEnum.NOT_NET_PRODUCT.type) {
                                notNetFundIds.add(c.getValue());
                            }

                        } else if (c.getType().equals(RelTypeEnum.VIDEO.type) || c.getType().equals(RelTypeEnum.AUDIO.type)) {
                            curriculumIds.add(c.getValue());
                        } else if (c.getType().equals(RelTypeEnum.SINGLE_IMG.type)) {
                            imageIds.add(c.getValue());
                        }else if (c.getType().equals(RelTypeEnum.MULTIPLE_IMAGE.type)) {
                            c.getImgList().forEach(img->imageIds.add(img.getRelId()));
                        }
                        else if (c.getType().equals(RelTypeEnum.NEW_COURSE_SECTION_AUDIO.type) ||
                                c.getType().equals(RelTypeEnum.NEW_COURSE_SECTION_VIDEO.type)) {
                            courseIds.add(c.getValue());
                        }
                    })
            );

        }
        if (!CollectionUtils.isEmpty(shortVideoIds)) {
            // 短视频列表
            List<ShortVideoBaseInfoResp> list = feignService.batchGetShortVideoBaseInfo(setToList(shortVideoIds));
            shortVideoMap.putAll(list.stream().collect(Collectors.toMap(ShortVideoBaseInfoResp::getSourceId, item -> item, (oldValue, newValue) -> oldValue)));
        }
        if (!CollectionUtils.isEmpty(curriculumIds)) {
            // 课程列表
            List<ShortVideoBaseInfoResp> commonResp =
                    feignClientForFatools.getCurriculumByColumnRelId(setToList(curriculumIds));
            if (commonResp != null && !CollectionUtils.isEmpty(commonResp)) {
                curriculumMap.putAll(commonResp.stream()
                        .collect(Collectors.toMap(ShortVideoBaseInfoResp::getColumnRelId, item -> item, (oldValue, newValue) -> oldValue)));
            }
        }
        if (!CollectionUtils.isEmpty(courseIds)) {
            // 新版课程列表
            List<CourseSimpleResp> list = feignService.getCourseSimpleList(setToList(courseIds));
            courseMap.putAll(list.stream().collect(Collectors.toMap(CourseSimpleResp::getCourseId, item -> item, (oldValue, newValue) -> oldValue)));
        }
        if (!CollectionUtils.isEmpty(zhiboIds)) {
            // 直播列表
            List<ZhiboListResp> list = feignService.getZhiboSimpleList(setToList(zhiboIds));
            feignClientForZhibo.simpleList(setToList(zhiboIds));
            zhiboMap.putAll(list.stream().collect(Collectors.toMap(ZhiboListResp::getId, item -> item, (oldValue, newValue) -> oldValue)));
        }
        if (!CollectionUtils.isEmpty(imageIds)) {
            // 查询图片
            List<FileRecordEntity> fileRecordEntities =
                    ossFileService.queryByIds(setToList(imageIds));
            if (!CollectionUtils.isEmpty(fileRecordEntities)) {
                imgMap.putAll(fileRecordEntities.stream().collect(Collectors
                        .toMap(FileRecordEntity::getFileId, o -> o)));
            }

        }
        if (!CollectionUtils.isEmpty(topicIds)) {
            // 查询话题标题
            List<TopicEntity> topicEntities =
                    topicService.queryByIds(setToList(topicIds));
            if (!CollectionUtils.isEmpty(topicEntities)) {
                topicMap.putAll(topicEntities.stream().collect(Collectors
                        .toMap(TopicEntity::getTopicId, TopicEntity::getTopicTitle)));
            }
        }
        if (!CollectionUtils.isEmpty(userIds)) {
            // 查询用户信息
            List<UserInfoResp> queryUsersListNew = feignService.getUserList(setToList(userIds));
            if (!CollectionUtils.isEmpty(userIds)) {
                userMap.putAll(queryUsersListNew.stream().collect(Collectors
                        .toMap(UserInfoResp::getUserId, o -> o)));
            }

        }
        this.getFundInfo(tanpuFundIds, fundIds, publicFundIds, ifaFundIds, notNetFundIds, fundMap);
    }

    /**
     * 设置产品信息
     *
     * @param tanpuFundIds
     * @param fundIds
     * @param publicFundIds
     * @param fundMap
     */
    private void getFundInfo(Set<String> tanpuFundIds,
                             Set<String> fundIds,
                             Set<String> publicFundIds,
                             Set<String> ifaFundIds,
                             Set<String> notNetFundIds,
                             Map<String, FundInfoBaseResp> fundMap) {
        Map<String, FundInfoBaseResp> tampFundMap;
        Map<String, FundInfoBaseResp> privateFundMap;
        Map<String, FundInfoBaseResp> publicFundMap;
        Map<String, FundInfoBaseResp> ifaFundMap;
        Map<String, FundInfoBaseResp> notNetFundMap = null;
        if (!CollectionUtils.isEmpty(tanpuFundIds)) {
//            ProductListReq productListReq = ProductListReq.builder()
//                    .fundIds(Lists.newArrayList(tanpuFundIds))
//                    .build();
            // 探普产品
            List<ProductInfoVO> list = feignService.getProductInfoByIds(setToList(tanpuFundIds));
            List<FundInfoBaseResp> fundInfoBaseRespList = list.stream().map(item -> {
                FundInfoBaseResp fundInfoBaseResp = FundInfoBaseResp.builder().build();
                BeanUtils.copyProperties(item, fundInfoBaseResp);
                return fundInfoBaseResp;
            }).collect(Collectors.toList());
            tampFundMap = fundInfoBaseRespList.stream().collect(Collectors.toMap(FundInfoBaseResp::getFundId, item -> item));

            if (tampFundMap.size() > 0) {
                fundMap.putAll(tampFundMap);
            }
        }
        // 私募产品
        if (!CollectionUtils.isEmpty(fundIds)) {
            // 私募产品
            List<ProductInfoVO> list = feignService.getFundList(setToList(fundIds));
            List<FundInfoBaseResp> fundInfoBaseRespList = list.stream().map(item -> {
                FundInfoBaseResp fundInfoBaseResp = FundInfoBaseResp.builder().build();
                BeanUtils.copyProperties(item, fundInfoBaseResp);
                return fundInfoBaseResp;
            }).collect(Collectors.toList());
            privateFundMap = fundInfoBaseRespList.stream().collect(Collectors.toMap(FundInfoBaseResp::getFundId, item -> item));

            if (privateFundMap.size() > 0) {
                fundMap.putAll(privateFundMap);
            }
        }

        // 理财师导入产品
        if (!CollectionUtils.isEmpty(ifaFundIds)) {
            List<ProductInfoVO> list = feignService.getPrivateFundList(setToList(ifaFundIds));
            List<FundInfoBaseResp> fundInfoBaseRespList = list.stream().map(item -> {
                FundInfoBaseResp fundInfoBaseResp = FundInfoBaseResp.builder().build();
                BeanUtils.copyProperties(item, fundInfoBaseResp);
                return fundInfoBaseResp;
            }).collect(Collectors.toList());
            ifaFundMap = fundInfoBaseRespList.stream().collect(Collectors.toMap(FundInfoBaseResp::getFundId, item -> item));


            if (ifaFundMap.size() > 0) {
                fundMap.putAll(ifaFundMap);
            }
        }

        if (!CollectionUtils.isEmpty(publicFundIds)) {
            // 公募产品
            List<ProductInfoVO> list = feignService.getPublicFundList(setToList(publicFundIds));
            List<FundInfoBaseResp> fundInfoBaseRespList = list.stream().map(item -> {
                FundInfoBaseResp fundInfoBaseResp = FundInfoBaseResp.builder().build();
                BeanUtils.copyProperties(item, fundInfoBaseResp);
                return fundInfoBaseResp;
            }).collect(Collectors.toList());
            publicFundMap = fundInfoBaseRespList.stream().collect(Collectors.toMap(FundInfoBaseResp::getFundId, item -> item));

            if (publicFundMap.size() > 0) {
                fundMap.putAll(publicFundMap);
            }
        }

        if (!CollectionUtils.isEmpty(notNetFundIds)) {
            // 无净值产品
            CommonResp<List<ProductInfoVO>> notNetInfoResult =
                    feignForFund.getProductListNotNetInfo(setToList(notNetFundIds));
            if (notNetInfoResult.isSuccess() && !CollectionUtils.isEmpty(notNetInfoResult.getData())) {
                List<FundInfoBaseResp> fundInfoBaseRespList = notNetInfoResult.getData().stream().map(item -> {
                    FundInfoBaseResp fundInfoBaseResp = FundInfoBaseResp.builder().build();
                    BeanUtils.copyProperties(item, fundInfoBaseResp);
                    return fundInfoBaseResp;
                }).collect(Collectors.toList());
                notNetFundMap = fundInfoBaseRespList.stream().collect(Collectors.toMap(FundInfoBaseResp::getFundId, item -> item));
            }
            if (notNetFundMap != null && notNetFundMap.size() > 0) {
                fundMap.putAll(notNetFundMap);
            }
        }
    }

    /**
     * 设置资源信息
     */
    private void setResInfo(List<ThemeQo> themeQos,
                            Map<String, ShortVideoBaseInfoResp> shortVideoMap,
                            Map<String, ShortVideoBaseInfoResp> curriculumMap,
                            Map<String, CourseSimpleResp> courseMap,
                            Map<String, ZhiboListResp> zhiboMap,
                            Map<String, FundInfoBaseResp> fundMap,
                            Map<String, FileRecordEntity> imgUrlMap,
                            Map<String, UserInfoResp> userMap,
                            Map<String, String> topicMap) {
        for (ThemeQo themeQo : themeQos) {
            if (!StringUtils.isEmpty(themeQo.getTopicId()) && topicMap.containsKey(themeQo.getTopicId())) {
                //话题标题
                themeQo.setTopicTitle(topicMap.get(themeQo.getTopicId()));
            }
            if (!StringUtils.isEmpty(themeQo.getAuthorId()) && userMap.containsKey(themeQo.getAuthorId())) {
                //用户信息
                UserInfoResp userInfo = userMap.get(themeQo.getAuthorId());
                //昵称头像简介
                themeQo.setNickName(userInfo.getNickName());
                themeQo.setUserImg(userInfo.getHeadImageUrl());
                themeQo.setUserIntroduction(userInfo.getIntroduction());
                //认证标签相关
                themeQo.setUserType(userInfo.getUserType());
                themeQo.setLevelGrade(userInfo.getLevelGrade());
                themeQo.setUserInvestorType(userInfo.getUserInvestorType());
                themeQo.setBelongUserOrgId(userInfo.getBelongUserOrgId());
                themeQo.setBelongUserOrgName(userInfo.getBelongUserOrgName());
                //工作室相关
                themeQo.setWorkshopName(userInfo.getWorkshopName());
                themeQo.setWorkshopStatus(userInfo.getWorkshopStatus());
                themeQo.setWorkshopIntroduction(userInfo.getWorkshopIntroduction());
                //首席投顾
                if (UserLevelEnum.USER_CHIEF_FINANCIAL_ADVISER.getCode() == userInfo.getLevelGrade()
                        && userInfo.getUserInfoNewChief() != null) {
                    themeQo.setNickName(userInfo.getUserInfoNewChief().getUserName());
                    themeQo.setUserImg(userInfo.getUserInfoNewChief().getHeadImageUrl());
                    themeQo.setUserIntroduction(userInfo.getUserInfoNewChief().getPersonalProfile());
                }
            }
            if (themeQo.getContent() == null) {
                continue;
            }
            for (ThemeContentQo themeContent : themeQo.getContent()) {
                if (themeContent.getType().equals(RelTypeEnum.LIVE.type)) {
                    if (zhiboMap.containsKey(themeContent.getValue())) {
                        ZhiboListResp zhibo = zhiboMap.get(themeContent.getValue());
                        themeContent.setDetail(AttachmentDetailVo.builder().zhibo(zhibo).build());
                    }
                } else if (themeContent.getType().equals(RelTypeEnum.SHORT_VIDEO.type)) {
                    if (shortVideoMap.containsKey(themeContent.getValue())) {
                        themeContent.setDetail(AttachmentDetailVo.builder()
                                .shortVideo(shortVideoMap.get(themeContent.getValue())).build());
                    }
                } else if (themeContent.getType().equals(RelTypeEnum.VIDEO.type) ||
                        themeContent.getType().equals(RelTypeEnum.AUDIO.type)) {
                    if (curriculumMap.containsKey(themeContent.getValue())) {
                        themeContent.setDetail(AttachmentDetailVo.builder()
                                .curriculum(curriculumMap.get(themeContent.getValue())).build());
                    }
                } else if (themeContent.getType().equals(RelTypeEnum.NEW_COURSE_SECTION_VIDEO.type) ||
                        themeContent.getType().equals(RelTypeEnum.NEW_COURSE_SECTION_AUDIO.type)) {
                    if (courseMap.containsKey(themeContent.getValue())) {
                        themeContent.setDetail(AttachmentDetailVo.builder()
                                .course(courseMap.get(themeContent.getValue())).build());
                    }
                } else if (themeContent.getType().equals(RelTypeEnum.FUND.type)) {
                    if (fundMap.containsKey(themeContent.getValue())) {
                        FundInfoBaseResp product = fundMap.get(themeContent.getValue());
                        // 推荐语
                        product.setRemark(themeContent.getRemark());
                        // 产品类型
                        product.setProductType(themeContent.getProductType());
                        themeContent.setDetail(AttachmentDetailVo.builder()
                                .product(product).build());
                    }
                } else if (themeContent.getType().equals(RelTypeEnum.SINGLE_IMG.type)) {
                    //单图封装到imglist列表中
                    if (imgUrlMap.containsKey(themeContent.getValue())) {
                        FileRecordEntity imgEntity = imgUrlMap.get(themeContent.getValue());
                        if (imgEntity != null && !StringUtils.isEmpty(imgEntity.getExtInfo())) {
                            Map<String, Object> extMap = JsonUtil.toMap(imgEntity.getExtInfo());
                            ImagesDTO imagesDTO = ImagesDTO.builder().imgHeight((Integer) extMap.get("height"))
                                    .imgWidth((Integer) extMap.get("width"))
                                    .remark(imgEntity.getUrl())
                                    .relId(imgEntity.getFileId())
                                    //压缩图片
                                    .resizeUrl(imgEntity.getUrl() + CommunityConstant.OSS_RESIZE_RATIO)
                                    .build();
                            // 图片审核屏蔽
                            if (FileChechStatusEnum.BLOCK.getCode().equals(imgEntity.getCheckStatus())){
                                imagesDTO.setRemark(CommunityConstant.OSS_CHECK_FAIL_DEFAULT);
                                imagesDTO.setResizeUrl(CommunityConstant.OSS_CHECK_FAIL_DEFAULT+ CommunityConstant.OSS_RESIZE_RATIO);
                                imagesDTO.setImgWidth(CommunityConstant.OSS_CHECK_FAIL_DEFAULT_WIDTH);
                                imagesDTO.setImgHeight(CommunityConstant.OSS_CHECK_FAIL_DEFAULT_HEIGHT);
                            }
                            themeContent.setImgList(Collections.singletonList(imagesDTO));
                        }
                    }
                } else if (themeContent.getType().equals(RelTypeEnum.MULTIPLE_IMAGE.type)) {
                    //多图写入图片宽高,压缩图片url
                    List<ImagesDTO> imgList = themeContent.getImgList();
                    for (ImagesDTO imagesDTO : imgList) {

                        if (imgUrlMap.containsKey(imagesDTO.getRelId())) {
                            FileRecordEntity imgEntity = imgUrlMap.get(imagesDTO.getRelId());
                            // 图片审核不通过,替换为默认图片 todo 配置移除
                            if (FileChechStatusEnum.BLOCK.getCode().equals(imgEntity.getCheckStatus())){
                                imagesDTO.setRemark(CommunityConstant.OSS_CHECK_FAIL_DEFAULT);
                                imagesDTO.setResizeUrl(CommunityConstant.OSS_CHECK_FAIL_DEFAULT+ CommunityConstant.OSS_RESIZE_RATIO);
                                imagesDTO.setImgWidth(CommunityConstant.OSS_CHECK_FAIL_DEFAULT_WIDTH);
                                imagesDTO.setImgHeight(CommunityConstant.OSS_CHECK_FAIL_DEFAULT_HEIGHT);
                            }else {
                                imagesDTO.setRemark(imgEntity.getUrl());
                                imagesDTO.setResizeUrl(imgEntity.getUrl() + CommunityConstant.OSS_RESIZE_RATIO);
                                String extInfo = imgEntity.getExtInfo();
                                if (!StringUtils.isEmpty(extInfo)) {
                                    Map<String, Object> extMap = JsonUtil.toMap(extInfo);
                                    imagesDTO.setImgHeight((Integer) extMap.get("height"));
                                    imagesDTO.setImgWidth((Integer) extMap.get("width"));
                                }
                            }
                        }
                    }

                }
            }
//            String formerThemeId = themeQo.getFormerThemeId();
//            if (!StringUtils.isEmpty(formerThemeId)) {
//                FormerThemeQo formerTheme = themeQo.getFormerTheme();
//
//                //单个查询详情
////            productService.getAttachDetail(formerTheme);
//
//                FormerThemeQo f = ConvertUtil.themeQo2FormerThemeQo(formerTheme);
//                themeQo.setFormerTheme(f);
//            }
        }

    }

    private List<String> setToList(Set<String> set) {
        List<String> l = new ArrayList<>();
        l.addAll(set);
        return l;
    }

    //组装被转发主题
    private void buildFormerTheme(ThemeQo themeQo) {

    }

}