package com.yizhi.application.protal.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.album.application.feign.AlbumClient;
import com.yizhi.album.application.vo.ApiListAlbumVo;
import com.yizhi.album.application.vo.domain.Album;
import com.yizhi.application.protal.constant.SiteEnum;
import com.yizhi.application.tools.PageTools;
import com.yizhi.application.wechat.utils.WechatConstant;
import com.yizhi.assignment.application.feign.AssignmentStudentClient;
import com.yizhi.assignment.application.vo.entity.Assignment;
import com.yizhi.certificate.application.feign.CertificateClient;
import com.yizhi.certificate.application.vo.domain.CertificateVo;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.course.application.feign.CourseClient;
import com.yizhi.course.application.feign.CoursePcClient;
import com.yizhi.course.application.feign.OfflineCourseClient;
import com.yizhi.course.application.vo.CourseStudentStatusVO;
import com.yizhi.course.application.vo.HomePageCoursePageVo;
import com.yizhi.course.application.vo.OfflineCourseVo;
import com.yizhi.course.application.vo.domain.CourseEntityVo;
import com.yizhi.drools.application.feign.RecommendStrategyClient;
import com.yizhi.drools.application.vo.drools.BusinessVo4Portal;
import com.yizhi.drools.application.vo.drools.BusinessVo4PortalParam;
import com.yizhi.drools.application.vo.drools.BusinessVo4PortalResponse;
import com.yizhi.enroll.application.feign.EnrollFeignClient;
import com.yizhi.enroll.application.vo.domain.Enroll;
import com.yizhi.exam.application.feign.ExamClient;
import com.yizhi.exam.application.vo.domain.Exam;
import com.yizhi.forum.application.feign.remote.RemotePostsClient;
import com.yizhi.lecturer.application.feign.LecturerClient;
import com.yizhi.lecturer.application.vo.domain.LecturerVo;
import com.yizhi.library.application.feign.StudentCaseClient;
import com.yizhi.library.application.vo.FavoriteVO;
import com.yizhi.live.application.feign.LiveActivityClient;
import com.yizhi.live.application.vo.LiveActivityVO;
import com.yizhi.live.application.vo.LiveOnlineCountVo;
import com.yizhi.mall.application.feign.TokenControllerClient;
import com.yizhi.mall.application.pojo.vo.TokenConfigVO;
import com.yizhi.practice.application.feign.PracticeConfigStudentClient;
import com.yizhi.practice.application.pojo.vo.PracticeVo;
import com.yizhi.research.application.feign.ResearchClient;
import com.yizhi.research.application.vo.domain.ResearchVo;
import com.yizhi.site.application.enums.FunctionTypeCode;
import com.yizhi.site.application.enums.PortalEnum;
import com.yizhi.site.application.feign.InformationStudentFeignClients;
import com.yizhi.site.application.feign.PortalManagePCFeignClients;
import com.yizhi.site.application.feign.api.FunctionDisplayConfigApiClients;
import com.yizhi.site.application.feign.api.PortalApiFeignClients;
import com.yizhi.site.application.feign.api.PortalApiPCFeignClients;
import com.yizhi.site.application.vo.domain.FunctionDisplayConfigVo;
import com.yizhi.site.application.vo.domain.PortalTemplateVo;
import com.yizhi.site.application.vo.domain.ProtalPlateVo;
import com.yizhi.site.application.vo.site.*;
import com.yizhi.training.application.feign.TpPlanActivityClient;
import com.yizhi.training.application.feign.TrainingProjectClient;
import com.yizhi.training.application.vo.api.TrainingProjectVoPortalVo;
import com.yizhi.training.application.vo.domain.TpPlanActivityVo;
import com.yizhi.training.application.vo.domain.TrainingProjectVo;
import com.yizhi.util.application.domain.BizResponse;
import com.yizhi.util.application.domain.Response;
import com.yizhi.util.application.enums.i18n.Constants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * @description: 微信APP端接口
 * @author: lly
 * @date: 2019-01-10 16:33
 **/
@RestController
@Api(tags = "微信/APP端接口")
@RequestMapping(value = "/homepage")
public class HomePageController {

    private static final Logger LOGGER = LoggerFactory.getLogger(HomePageController.class);
    @Autowired
    private PortalApiPCFeignClients portalApiPCFeignClient;

    @Autowired
    private PortalApiFeignClients portalApiFeignClients;

    @Autowired
    private TpPlanActivityClient projectActivityClient;


    @Autowired
    private TrainingProjectClient projectClient;

    @Autowired
    private PortalManagePCFeignClients portalManagePCFeignClients;

    @Autowired
    private CourseClient courseClient;
    @Autowired
    private LiveActivityClient liveClient;
    @Autowired
    private ExamClient examClient;
    @Autowired
    private ResearchClient researchClient;
    @Autowired
    private AssignmentStudentClient assignmentClient;
    @Autowired
    private CertificateClient certificateClient;

    @Autowired
    private OfflineCourseClient offlineCourseClient;

    @Autowired
    private LecturerClient lecturerClient;

    @Autowired
    private FunctionDisplayConfigApiClients configApiClients;

    @Autowired
    private TpPlanActivityClient tpPlanActivityClient;

    @Autowired
    private CoursePcClient coursePcClient;
    @Autowired
    private StudentCaseClient studentCaseClient;

    @Autowired
    private RecommendStrategyClient recommendStrategyClient;

    @Autowired
    private LiveActivityClient liveActivityClient;

    @Autowired
    private AlbumClient albumClient;

    @Autowired
    private RemotePostsClient postClient;

    @Autowired
    private PortalUtil portalUtil;
    @Autowired
    PracticeConfigStudentClient practiceStudentClient;
    @Autowired
    InformationStudentFeignClients informationStudentFeignClients;
    @Autowired
    EnrollFeignClient enrollFeignClient;
    @Autowired
    TokenControllerClient tokenControllerClient;


    @ApiOperation(value = "返回模板列表信息", response = PortalTemplateVO.class)
    @GetMapping("/module/list")
    public Response<List<PortalTemplateVO>> findModuleList(
            @ApiParam(name = "type", value = "终端类型 2:APP;3:WECHAT", required = true) @RequestParam(value = "type") Integer type) {
        try {
            Long siteId = ContextHolder.get().getSiteId();
            List<PortalTemplateVo> portalTemplateList = portalApiPCFeignClient.moduleListSelectApi(siteId, type);
            List<PortalTemplateVO> portalTemplateVOList = null;
            if (CollectionUtils.isNotEmpty(portalTemplateList)) {
                portalTemplateVOList = portalTemplateList.parallelStream().map(portalTemplate -> {
                    if (portalTemplate != null) {
                        PortalTemplateVO portalTemplateVO = new PortalTemplateVO();
                        portalTemplateVO.setId(portalTemplate.getId());
                        portalTemplateVO.setName(portalTemplate.getModuleName());
                        portalTemplateVO.setType(portalTemplate.getModuleType());
                        return portalTemplateVO;
                    } else {
                        return null;
                    }
                }).collect(toList());
            }

            return Response.ok(portalTemplateVOList);
        } catch (Exception e) {
            LOGGER.info("异常：" + e);
            return Response.fail(Constants.COURSE_MSG_BIZ_ERROR);
        }
    }


    @ApiOperation(value = "根据id获取模块内容", response = PortalPlateVO.class)
    @GetMapping("/module/get")
    public Response moduleListSelect(
            @ApiParam(name = "id", value = "模块id", required = true) @RequestParam(value = "id") Long id,
            @ApiParam(name = "pageNo", value = "页码") @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo
    ) {
        RequestContext context = ContextHolder.get();

        //模板关联的活动信息
        List<PortalPlateVO> portalPlateVOList = portalApiFeignClients.getPlateVOList(id);
        LOGGER.info("parameter portalPlateVOList:" + portalPlateVOList);
        if (CollectionUtils.isEmpty(portalPlateVOList)) {
            return Response.ok(portalPlateVOList);
        }

        Integer type = Integer.valueOf(portalPlateVOList.get(0).getType());
        if (type == PortalEnum.TEN.ordinal()){
            //专区
            List<PortalPlateVO> portalPlateVOS = new ArrayList<PortalPlateVO>(16);
            List<PortalPlateVO> siteStudent = portalUtil.getSiteStudent(portalPlateVOList);
            portalPlateVOS.addAll(siteStudent == null ? new ArrayList<>() : siteStudent);
            return Response.ok(portalPlateVOS);
        }
        List<PortalPlateVO> portalPlateVOS = new ArrayList<PortalPlateVO>(WechatConstant.INITSIZE);

        //目前只有项目或者课程是需要查询配置
        Map<String, List<FunctionDisplayConfigVo>> functionDisplay = new HashMap<>();
        if (type == 3 || type == 2) {
            List<FunctionDisplayConfigVo> dataFunction = configApiClients.getAllBySiteId();
            //学时配置
            functionDisplay = dataFunction.stream().collect(Collectors.groupingBy(FunctionDisplayConfigVo::getFunctionType));
        }

        Pair<List<PortalPlateVO>, Map<String, Integer>> listMapPair = null;

        switch (type) {
            case 1:
                // 推荐、精选
                try {

                    portalPlateVOS = getRecommendData(portalPlateVOList);
                    // 直播观看类型获取
                    if(CollectionUtils.isNotEmpty(portalPlateVOS)){
                        List<Long> filterData = portalPlateVOS.stream().filter(moduleItem -> Integer.valueOf(3).equals(moduleItem.getType()))
                                .map(moduleItemId->moduleItemId.getActivityId()).collect(toList());
                        if(filterData != null){
                            Page<LiveActivityVO> liveData = liveActivityClient.LiveActivityByIds(filterData,0,filterData.size());
                            Map<Long,Integer> dataMap = liveData.getRecords().stream().
                                    collect(Collectors.toMap(key->key.getId(),val->val.getViewType()));
                            for(PortalPlateVO itemTmp :  portalPlateVOS){
                                if(Integer.valueOf(3).equals(itemTmp.getType()) && dataMap.containsKey(itemTmp.getActivityId())){
                                    itemTmp.setViewType(dataMap.get(itemTmp.getActivityId()));
                                }
                            }
                        }
                    }

                } catch (Exception e) {
                    LOGGER.error("推荐精选异常:", e);
                    return Response.fail(Constants.MSG_BIZ_FAIL);
                }
                break;
            case 2:
                // 项目培训
                try {
                    Boolean trainingShowDisplay = functionDisplay.get(FunctionTypeCode.TRAINING.getCode()).get(0).getShowDisplay();
                    LOGGER.info("培训学时是否显示：" + trainingShowDisplay);
                    portalPlateVOS = getTrainingProject(portalPlateVOList, context, trainingShowDisplay);
                } catch (Exception e) {
                    return Response.fail(Constants.TRAINING_MSG_BIZ_ERROR);
                }
                break;
            case 3:
                //课程
                try {
                    Boolean courseShowDisplay = functionDisplay.get(FunctionTypeCode.COURSE.getCode()).get(0).getShowDisplay();
                    LOGGER.info("课程是否显示：" + courseShowDisplay);
                    portalPlateVOS = getCourse(portalPlateVOList, context, courseShowDisplay);
                } catch (Exception e) {
                    return Response.fail(Constants.COURSE_MSG_BIZ_ERROR);
                }
                break;
            case 4:
                try {
                    portalPlateVOS = getLecturerList(portalPlateVOList);
                    LOGGER.info("讲师返回结果：" + portalPlateVOS);
                } catch (Exception e) {
                    LOGGER.error("讲师服务异常:", e);
                    return Response.fail(Constants.LECTURER_MSG_BIZ_ERROR);
                }
                break;
            case 5:
                try {
                    //直播
                    portalPlateVOS = getLive(portalPlateVOList);
                } catch (Exception e) {
                    LOGGER.error("学员端获取直播列表异常 templateId = {}",id,e);
                    return Response.fail(Constants.LIVE_MSG_CHANNEL_RESPONSE_EXCEPTION);
                }
                break;
            case 6:
                try {
                    portalPlateVOS = getCaseList(portalPlateVOList);
                } catch (Exception e) {
                    return Response.fail(Constants.CASELIBRARY_MSG_BIZ_ERROR);
                }
                break;
            case 7:
                try {
                    // 返回
                    Page<PortalPlateVO> portalPlateVOPage = getDroolList(portalPlateVOList, pageNo);

                    // 直播观看类型获取
                    if(portalPlateVOPage != null){
                        List<PortalPlateVO> portalPlateVOList1 = portalPlateVOPage.getRecords();
                        if(CollectionUtils.isNotEmpty(portalPlateVOList1)){
                            List<Long> filterData = portalPlateVOList1.stream().filter(moduleItem -> "live".equals(moduleItem.getType()))
                                    .map(moduleItemId->moduleItemId.getActivityId()).collect(toList());
                            if(filterData != null){
                                Page<LiveActivityVO> liveData = liveActivityClient.LiveActivityByIds(filterData,0,filterData.size());
                                Map<Long,Integer> dataMap = liveData.getRecords().stream().
                                        collect(Collectors.toMap(key->key.getId(),val->val.getViewType()));
                                for(PortalPlateVO itemTmp :  portalPlateVOList1){
                                    if("live".equals(itemTmp.getType()) && dataMap.containsKey(itemTmp.getActivityId())){
                                        itemTmp.setViewType(dataMap.get(itemTmp.getActivityId()));
                                    }
                                }
                            }
                        }

                    }
                    listMapPair = PageTools.versaPage(portalPlateVOPage);
                } catch (Exception e) {
                    LOGGER.error("策略异常：",e);
                    return Response.fail(Constants.MSG_BIZ_FAIL);
                }
                break;
            case 8:
                try {
                    //专辑
                    portalPlateVOS = getAlbumlList(portalPlateVOList);
                } catch (Exception e) {
                    LOGGER.error("专辑异常：", e);
                    return Response.fail(Constants.MSG_BIZ_FAIL);
                }
                break;
            case 9:
                try {
                    // 返回
                    portalPlateVOS = portalPlateVOList;
                } catch (Exception e) {
                    LOGGER.error("论坛业务：", e);
                    return Response.fail(Constants.MSG_BIZ_FAIL);
                }
                break;
            case 11:
                try {
                    //新闻资讯
                    portalPlateVOS = getNewsList(portalPlateVOList);
                }catch (Exception e){
                    LOGGER.error("新闻资讯获取模块列表异常: ",e);
                }
                break;
            case 12:
                try {
                    //付费资源
                    portalPlateVOS = getPayResource(portalPlateVOList);
                }catch (Exception e){
                    LOGGER.error("付费资源获取模块列表异常: ",e);
                }
                break;
            default:
                break;
        }
        if (type == 7) {
            return Response.ok(listMapPair);
        } else {
            return Response.ok(portalPlateVOS);
        }
    }

    /**
     * 获取付费资源内容
     * @param portalPlateVOList 模板列表
     */
    private List<PortalPlateVO> getPayResource(List<PortalPlateVO> portalPlateVOList) {
        List<PortalPlateVO> list = new ArrayList<>();
        if (null == portalPlateVOList || portalPlateVOList.isEmpty()){
            return list;
        }
        if (portalPlateVOList.size() > 8){
            portalPlateVOList = portalPlateVOList.subList(0,8);
            LOGGER.info("移动首页-付费资源-获取到模板内容列表长度大于8，截取长度size={}",portalPlateVOList.size());
        }
        portalPlateVOList.forEach(portalPlateVO -> {
            PortalPlateVO plateVO = new PortalPlateVO();
            try {
                //类型 type=12 项目
                Integer activityType = portalPlateVO.getActivityType();
                if (null != activityType){
                    plateVO.setType(String.valueOf(activityType));
                }
                Long activityId = portalPlateVO.getActivityId();
                //目前只有一个项目类型，故不做id区分
                TrainingProjectVo trainingProjectVo = projectClient.getOne(activityId);
                plateVO.setId(activityId);
                plateVO.setTemplateId(portalPlateVO.getTemplateId());
                plateVO.setModuleName(portalPlateVO.getModuleName());
                plateVO.setSiteId(portalPlateVO.getSiteId());
                plateVO.setName(trainingProjectVo.getName());
                plateVO.setHomeId(portalPlateVO.getHomeId());
                //项目名称
                plateVO.setTitle(trainingProjectVo.getName());
                //缩略图, 1:使用内容图片, 2:使用新图片
                Integer thumbnail = portalPlateVO.getThumbnail();
                plateVO.setImage(trainingProjectVo.getLogoImg());
                if (null != thumbnail && thumbnail.equals(2)){
                    plateVO.setImage(portalPlateVO.getImage());
                }
                //价格
                Integer enableEnroll = trainingProjectVo.getEnableEnroll();
                if (null == enableEnroll || !enableEnroll.equals(1)){
                    LOGGER.error("移动端-首页配置的付费项目未开启报名,trainingId = {}",activityId);
                    return;
                }
                Enroll enroll = enrollFeignClient.selectByProjectId(activityId);
                if (null == enroll){
                    LOGGER.error("移动端-首页配置的付费项目开启报名,但是查询报名信息为空,trainingId = {}",activityId);
                    return;
                }
                plateVO.setTotal(enroll.getActualPrice());
                plateVO.setActualPrice(enroll.getActualPrice());
                plateVO.setOriginalPrice(enroll.getOriginalPrice());
                list.add(plateVO);

            }catch (Exception e){
                LOGGER.error("移动端-获取首页付费项目异常: ",e);
            }
        });

        return list;
    }

    /**
     * 获取新闻资讯
     */
    private List<PortalPlateVO> getNewsList(List<PortalPlateVO> portalPlateVOList) {

        List<PortalPlateVO> portalPlateList = new ArrayList<>();
        if (null == portalPlateVOList || portalPlateVOList.isEmpty()){
            return portalPlateList;
        }
        portalPlateVOList.forEach(portalPlateVO -> {
            PortalPlateVO vo = new PortalPlateVO();
            Long newsId = portalPlateVO.getActivityId();
            IdOneVO newsOneVo = new IdOneVO();
            newsOneVo.setId(newsId);
            newsOneVo.setContext(ContextHolder.get());
            InformationViewVO info = informationStudentFeignClients.getInformation(newsOneVo);
            if (null != info){
                BeanUtils.copyProperties(portalPlateVO,vo);
                vo.setStartTime(info.getReleaseTime());
                vo.setTitle(info.getFileName());
                vo.setActivityId(info.getId());
                vo.setImage(info.getLogoPath());
                //新闻观看人数
                Integer readCount = info.getReadCount();
                vo.setTotal(0);
                if (null != readCount && readCount > 0){
                    vo.setTotal(readCount);
                }
                portalPlateList.add(vo);
            }
        });
        return portalPlateList;
    }


    /**
     * 获取精选/推荐的数据
     *
     * @param
     * @return
     */
    private List<PortalPlateVO> getRecommendData(List<PortalPlateVO> portalPlateVOList) {

        List<PortalPlateVO> portalPlateVOs = new ArrayList<>(WechatConstant.INITSIZE);

        List<Long> courseIdList = new ArrayList<>();
        for (PortalPlateVO ppVO : portalPlateVOList) {
            //0课程 1考试 2调研 3直播 4投票 5作业 6证书 7外部链接 8报名 9签到 10线下课程
            Integer type = ppVO.getActivityType();
            //关联的活动没有类型就不处理
            if (type == null) {
                continue;
            }

            com.yizhi.training.application.vo.domain.TpPlanActivityVo activity = projectActivityClient.getOne(ppVO.getId());

            Long id = ppVO.getActivityId();
            switch (type) {
                case 0:
                    ppVO.setType(SiteEnum.COURSE.getValue());
                    try {
                        CourseEntityVo course = courseClient.view(id);
                        if (course != null) {
                            ppVO.setId(course.getId());
                            ppVO.setName(course.getName());
                            if (ppVO.getThumbnail() == 1) {
                                //使用内容图片
                                ppVO.setImage(course.getImage());
                            }
                            // 添加课程的完成状态 by lingye 2019-10-12 10:53:30
                            courseIdList.add(course.getId());
                            try {
                                List<CourseStudentStatusVO> statusByIds = coursePcClient.getStatusByIds(courseIdList);
                                LOGGER.info("获取到的课程状态：" + statusByIds);
                                if (CollectionUtils.isNotEmpty(statusByIds)) {
                                    Integer studentStatus = statusByIds.get(0).getStudentStatus();
                                    ppVO.setStatus(studentStatus);
                                }
                            } catch (Exception e) {
                                LOGGER.error("课程完成状态：", e);
                            }
                            if (courseIdList.size() > 0) {
                                courseIdList.clear();
                            }
                        }
                    } catch (Exception e) {
                        LOGGER.error("课程异常：" + e);
                    }
                    break;
                case 1:
                    ppVO.setType(SiteEnum.EXAM.getValue());
                    Exam exam = null;
                    try {
                        exam = examClient.selectExamById(id);
                        if (exam != null) {
                            ppVO.setId(exam.getId());
                            ppVO.setName(exam.getName());
                        }
                    } catch (Exception e) {
                        LOGGER.error("考试异常：" + e);
                    }

                    break;
                case 2:
                    ResearchVo research = null;
                    try {
                        research = researchClient.viewOne(id);
                        if (research != null) {
                            ppVO.setId(research.getId());
                            ppVO.setName(research.getName());
                            ppVO.setType(SiteEnum.SURVEY.getValue());
                        }
                    } catch (Exception e) {
                        LOGGER.error("调研异常：" + e);
                    }
                    break;
                case 3:
                    LiveActivityVO live = null;
                    try {
                        live = liveClient.getLive(id);
                        if (live != null) {
                            ppVO.setId(Long.valueOf(live.getChannel()));
                            ppVO.setType(SiteEnum.LIVE.getValue());
                            ppVO.setName(live.getTitle());
                            ppVO.setViewType(live.getViewType());
                            ppVO.setActivityId(live.getId());
                            if (ppVO.getThumbnail() == 1) {
                                ppVO.setImage(live.getLogoImage());
                            }
                        }
                    } catch (NumberFormatException e) {
                        LOGGER.error("直播异常：" + e);
                    }
                    break;
                case 4:
//                    VoteVO vote = null;
//                    try {
//                        vote = voteClient.viewVote(String.valueOf(id));
//                        if (vote != null) {
//                            ppVO.setId(vote.getId());
//                            if (ppVO.getThumbnail() == 1) {
//                                ppVO.setImage(vote.getAdvertPictureUrl());
//                            }
//                            ppVO.setType(SiteEnum.VOTE.getValue());
//                        }
//                    } catch (Exception e) {
//                        LOGGER.error("投票异常:" + e);
//                    }
                    break;
                case 5:
                    Assignment assignment = null;
                    try {
                        assignment = assignmentClient.toAssignmentActivity(id);
                        if (assignment != null) {
                            ppVO.setName(assignment.getName());
                            ppVO.setId(assignment.getId());
                            ppVO.setType(SiteEnum.HOMEWORK.getValue());
                        }
                    } catch (Exception e) {
                        LOGGER.error("作业异常:" + e);
                    }

                    break;
                case 6:
                    CertificateVo certificate = null;
                    try {
                        certificate = certificateClient.getCertificate(id);
                        if (certificate != null) {
                            ppVO.setId(certificate.getId());
                            ppVO.setType(SiteEnum.CERTIFICATE.getValue());
                        }
                    } catch (Exception e) {
                        LOGGER.error("证书异常:" + e);
                    }

                    break;
                case 7:
                    TpPlanActivityVo tpPlanActivity = null;
                    try {
                        tpPlanActivity = tpPlanActivityClient.getOne(id);
                        ppVO.setName(tpPlanActivity.getName());
                        if (ppVO.getThumbnail() == 1) {
                            //外链必须有图片
                        }
                        if (null != activity) {
                            ppVO.setUrl(activity.getAddress());
                        }
                        ppVO.setType(SiteEnum.OUTERCHAIN.getValue());
                    } catch (Exception e) {
                        LOGGER.error("外链异常:" + e);
                    }
                    break;
                case 10:
                    OfflineCourseVo offlineCourse = null;
                    try {
                        offlineCourse = offlineCourseClient.getCourseById(id);
                        ppVO.setName(offlineCourse.getName());
                        if (ppVO.getThumbnail() == 1) {
                            ppVO.setImage(offlineCourse.getImage());
                        }
                        if (null != activity) {
                            ppVO.setUrl(activity.getAddress());
                        }
                        ppVO.setType("offlinecourse");
                    } catch (Exception e) {
                        LOGGER.error("线下课程异常:" + e);
                    }

                    break;
                case 11:
                    CourseEntityVo course = null;
                    try {
                        course = courseClient.view(id);
                        ppVO.setName(course.getName());
                        if (ppVO.getThumbnail() == 1) {
                            ppVO.setImage(course.getImage());
                        }
                        if (null != activity) {
                            ppVO.setUrl(activity.getAddress());
                        }
                        ppVO.setType(SiteEnum.MARKET.getValue());
                    } catch (Exception e) {
                        LOGGER.error("营销课程异常:" + e);
                    }

                    break;
                case 12:
                    TrainingProjectVo training = null;
                    try {
                        training = projectClient.getOne(id);
                        ppVO.setName(training.getName());
                        if (ppVO.getThumbnail() == 1) {
                            ppVO.setImage(training.getLogoImg());
                        }
                        if (null != activity) {
                            ppVO.setUrl(activity.getAddress());
                        }
                        ppVO.setType(SiteEnum.TRAIN.getValue());
                    } catch (Exception e) {
                        LOGGER.error("培训项目异常:" + e);
                    }

                    break;
                case 13:
                    //13属于门户的活动id
                    ProtalPlateVo pp = null;
                    try {
                        pp = portalManagePCFeignClients.getUrl(id);
                        ppVO.setName(pp.getLinkContentName());
                        ppVO.setUrl(pp.getSelectActivityName());
                        ppVO.setImage(pp.getImgPath());
                        ppVO.setType(SiteEnum.SITOUTERCHAIN.getValue());

                    } catch (Exception e) {
                        LOGGER.error("门户外链异常:" + e);
                    }
                    break;
                case 15:
                    try {
                        Album album = albumClient.get(id);
                        ppVO.setName(album.getName());
                        if (ppVO.getThumbnail() == 1) {
                            ppVO.setImage(album.getImage());
                        }
                        ppVO.setType(SiteEnum.ALBUM.getValue());

                    } catch (Exception e) {
                        LOGGER.error("专辑异常:" + e);
                    }
                    break;
                case 16:
                    List<Long> ids = new ArrayList<>();
                    ids.add(id);
                    try {
                        ppVO.setName(ppVO.getName());
                        ppVO.setImage(ppVO.getImage());
                        ppVO.setType(SiteEnum.POST.getValue());
                        Map<Long, String> names = postClient.getNames(ids);
                        String postName = null;
                        if (!names.isEmpty()) {
                            postName = names.get(id);
                            LOGGER.info("帖子的名称：{}",postName);
                        }
                        ppVO.setName(postName);
                    } catch (Exception e) {
                        LOGGER.error("论坛异常异常:",e);
                    }
                    break;
                case 28:
                    //智能陪练
                    try {
                        String imageUrl = ppVO.getImage();
                        BizResponse<PracticeVo> response = practiceStudentClient.getPractice(id);
                        PracticeVo practiceVo = response.getData();
                        if (null != practiceVo){
                            String logoUrl = practiceVo.getLogoUrl();
                            ppVO.setName(practiceVo.getName());
                            if (StringUtils.isEmpty(imageUrl)){
                                ppVO.setImage(logoUrl);
                            }
                        }

                        ppVO.setType(SiteEnum.MY_PRACTICE.getValue());
                    }catch (Exception e){
                        LOGGER.error("智能陪练获取异常:",e);
                    }

                default:
                    break;
            }
            portalPlateVOs.add(ppVO);
        }
        return portalPlateVOs;
    }

    /**
     * 获取项目培训列表
     *
     * @param portalPlateVOList
     * @param context
     * @param trainingShowDisplay 是否显示学时
     * @return
     */
    private List<PortalPlateVO> getTrainingProject(List<PortalPlateVO> portalPlateVOList, RequestContext context, Boolean trainingShowDisplay) {

        List<Long> pIds = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(portalPlateVOList)) {
            pIds = portalPlateVOList.parallelStream().map(portalPlateVO -> {
                return portalPlateVO.getId();
            }).limit(PortalEnum.FOUR.ordinal()).collect(toList());
        }

        List<TrainingProjectVoPortalVo> trainingList = projectClient.getTrainingListByIds(pIds);

        List<TrainingProjectVo> projectList = new ArrayList<>();

        List<PortalPlateVO> plateVOList = new ArrayList<>();
        for (PortalPlateVO pp : portalPlateVOList) {
            for (TrainingProjectVo tp : trainingList) {
                if ((tp.getId()).equals(pp.getId())) {
                    pp.setId(tp.getId());
                    pp.setName(tp.getName());
                    pp.setImage(pp.getThumbnail() == 1 ? pp.getImage() : tp.getLogoImg());
                    LOGGER.info("图片的地址：" + tp.getLogoImg());
                    pp.setStartTime(tp.getStartTime());
                    pp.setEndTime(tp.getEndTime());
                    pp.setActivityCount(tp.getEnableEnroll());
                    //List<Long> activeIds = projectActivityClient.getActiveCountById(tp.getId());
                    List<Long> activeIds = projectActivityClient.getExcCertiferActiveCountById(tp.getId());
                    pp.setActivityCount(CollectionUtils.isNotEmpty(activeIds) ? activeIds.size() : PortalEnum.ZERO.toValue());
                    if (activeIds != null && activeIds.size() > 0) {
                        pp.setTotalDuration(getStudyHour(activeIds));
                    }
                    pp.setCourseDurationShow(trainingShowDisplay);
                    break;
                }
            }
            plateVOList.add(pp);
        }

        LOGGER.info("打印信息" + projectList);
        return plateVOList;
    }


    /**
     * 获取首页课程
     *
     * @param portalPlateVOList
     * @param context
     * @param durationDisplay   学时显示
     * @return
     */
    private List<PortalPlateVO> getCourse(List<PortalPlateVO> portalPlateVOList, RequestContext context, Boolean durationDisplay) {

        List<Long> courseIds = new ArrayList<>();

        if (CollectionUtils.isNotEmpty(portalPlateVOList)) {
            courseIds = portalPlateVOList.parallelStream().map(portalPlateVO -> {
                return portalPlateVO.getId();
            }).collect(toList());
        }
        LOGGER.info("courseIds：{}", courseIds);
        // 获取课时
        Map<Long, Long> materialTime = coursePcClient.getMaterialTimeByCourseIds(courseIds);
        List<HomePageCoursePageVo> homeCourseList = null;
        List<HomePageCoursePageVo> courseList = new ArrayList<>();
        try {
            homeCourseList = courseClient.findHomeCourseList(courseIds);
            LOGGER.info("返回的homeCourseList：" + homeCourseList);

            List<Long> newCourseIds = homeCourseList.parallelStream().map(homePageCoursePageVo -> {
                return homePageCoursePageVo.getCourseId();
            }).collect(toList());
            LOGGER.info("返回的newCourseIds：" + newCourseIds);

            List<PortalPlateVO> plateVOList = new ArrayList<>();
            for (PortalPlateVO pp : portalPlateVOList) {
                // 判断不存在的
                if (!newCourseIds.contains(pp.getId())) {
                    continue;
                }
                // 实际顺序
                List<Long> courseIdList = new ArrayList<>();

                for (HomePageCoursePageVo hc : homeCourseList) {

                    if ((hc.getCourseId()).equals(pp.getId())) {
                        if (pp.getThumbnail() != 1) {
                            pp.setImage(pp.getImage());
                        }
                        pp.setId(hc.getCourseId());
                        pp.setName(hc.getName());
                        pp.setScore(hc.getLevel() == null ? "0" : String.valueOf(hc.getLevel()));
                        pp.setStudyCount(hc.getStudyNum() != null ? hc.getStudyNum() : 0);
                        pp.setType(SiteEnum.COURSE.getValue());
                        pp.setValid(hc.getValid());
                        pp.setDuration(materialTime != null ? materialTime.get(hc.getCourseId()).intValue() : PortalEnum.ZERO.toValue());
                        pp.setTotalDuration(hc.getTotalDuration());
                        pp.setTotalDurationStr(String.valueOf(hc.getTotalDuration()));
                        pp.setCourseDurationShow(durationDisplay);
                        pp.setImage(pp.getThumbnail() == 1 ? pp.getImage() : hc.getImage());


                        courseIdList.add(hc.getCourseId());
                        try {
                            List<CourseStudentStatusVO> statusByIds = coursePcClient.getStatusByIds(courseIdList);
                            LOGGER.info("获取到的课程状态：" + statusByIds);
                            if (CollectionUtils.isNotEmpty(statusByIds)) {
                                Integer studentStatus = statusByIds.get(0).getStudentStatus();
                                pp.setStatus(studentStatus);
                            }
                        } catch (Exception e) {
                            LOGGER.error("课程完成状态：", e);
                        }
                        if (courseIdList.size() > 0) {
                            courseIdList.clear();
                        }
                        break;
                    }


                }
                plateVOList.add(pp);
            }
            return plateVOList;
        } catch (Exception e) {
            LOGGER.error("Error occurred:", e);
            return null;

        }
    }


    /**
     * 获取直播
     *
     * @param portalPlateVOList
     * @return
     */
    private List<PortalPlateVO> getLive(List<PortalPlateVO> portalPlateVOList) {
        List<PortalPlateVO> portalPlateVOs = new ArrayList<>();
        if (null == portalPlateVOList || portalPlateVOList.isEmpty()){
            LOGGER.info("首页获取直播列表为空");
            return portalPlateVOs;
        }
        if (portalPlateVOList.size() > 5){
            portalPlateVOList = portalPlateVOList.subList(0,5);
        }
        portalPlateVOList.stream().forEach(plateVO-> {
            try {
                LiveActivityVO live = liveClient.getLive(plateVO.getId());
                PortalPlateVO ppVO = new PortalPlateVO();
                if (live != null) {
                    ppVO.setId(Long.valueOf(live.getChannel()));
                    ppVO.setType(SiteEnum.LIVE.getValue());
                    ppVO.setName(live.getTitle());
                    ppVO.setStartTime(live.getStartTime());
                    ppVO.setViewType(live.getViewType());
                    ppVO.setEndTime(live.getEndTime());
                    ppVO.setActivityId(live.getId());
                    String image = plateVO.getImage();
                    ppVO.setImage(image);
                    if (StringUtils.isEmpty(image)){
                        ppVO.setImage(live.getLogoImage());
                    }
                    String channel = live.getChannel();
                    // 获取直播状态
                    Integer liveStatus = liveClient.getLiveStatus(channel);
                    String anchor = live.getAnchor();
                    Date startTime = live.getStartTime();
                    Date endTime = live.getEndTime();
                    //0: 公开播放 ; 1: 站内授权播放;
                    Integer viewType = live.getViewType();
                    //设置返回学员端的直播信息
                    //直播号、直播主题、主播名称、开始时间、结束时间、直播类型[公开、站内]、直播状态[进行中、已结束、未开始]、观看人数
                    ppVO.setCourseNo(channel);
                    ppVO.setTitle(live.getTitle());
                    ppVO.setCreateByName(anchor);
                    ppVO.setStartTime(startTime);
                    ppVO.setEndTime(endTime);
                    ppVO.setViewType(viewType);
                    //设置直播状态、观看人数
                    List<LiveOnlineCountVo> liveOnlineCountVos = liveActivityClient.liveCountOnlineRealTime(channel);
                    if (null != liveOnlineCountVos && !liveOnlineCountVos.isEmpty()){
                        LiveOnlineCountVo liveOnlineCountVo = liveOnlineCountVos.get(0);
                        Integer onlineCountVoCount = liveOnlineCountVo.getCount();
                        ppVO.setLikeNum(onlineCountVoCount);
                    }else {
                        ppVO.setLikeNum(0);
                    }
                    ppVO.setStatus(liveStatus);
                    portalPlateVOs.add(ppVO);
                }
            } catch (NumberFormatException e) {
                LOGGER.error("获取直信息异常：" + e);
            }
        });
        return portalPlateVOs;
    }


    /**
     * 获取讲师库的信息
     *
     * @param portalPlateVOList
     * @return
     */
    public List<PortalPlateVO> getLecturerList(List<PortalPlateVO> portalPlateVOList) {

        LOGGER.info("讲师列参数表：" + portalPlateVOList);

        List<PortalPlateVO> portalPlateVOs = portalPlateVOList.parallelStream().map(portalPlateVO -> {
            PortalPlateVO ppVO = new PortalPlateVO();
            LecturerVo lecturer = lecturerClient.getLecturerById(portalPlateVO.getId());
            ppVO.setId(lecturer.getId());
            ppVO.setName(lecturer.getLecturerName());
            ppVO.setImage(lecturer.getAvatar());
            ppVO.setTitle(lecturer.getTitle() != null ? lecturer.getTitle() : "");

            return ppVO;
        }).limit(4).collect(toList());

        return portalPlateVOs;
    }

    /**
     * 根据项目培训的id获取培训学时
     *
     * @param activeIds
     * @return
     */
    public Float getStudyHour(List<Long> activeIds) {
        Map<Long, Float> studyHours = coursePcClient.getStudyHourByCourseIds(activeIds);
        Float studyHour = 0f;
        if (null != studyHours && studyHours.size() > 0) {
            for (Long h : studyHours.keySet()) {
                LOGGER.info("课程学时：" + studyHours.get(h));
                studyHour = studyHour + (studyHours.get(h) != null ? studyHours.get(h) : 0f);
            }
        }
        return studyHour;
    }

    /**
     * 获取案例库的首页配置的礼拜
     *
     * @param portalPlateVOList
     * @return
     */
    public List<PortalPlateVO> getCaseList(List<PortalPlateVO> portalPlateVOList) {

        LOGGER.info("讲师列参数表：" + portalPlateVOList);

        List<PortalPlateVO> portalPlateVOs = portalPlateVOList.parallelStream().map(portalPlateVO -> {
            PortalPlateVO ppVO = new PortalPlateVO();
            FavoriteVO caseDetails = studentCaseClient.getStudentCaseDetail(portalPlateVO.getId());
            ppVO.setId(caseDetails.getStudentCaseId());
            ppVO.setName(caseDetails.getStudentCaseTittle());
            ppVO.setImage(caseDetails.getStudentCaseLogoUrl());
            ppVO.setCreateByName(caseDetails.getAuthorFullName());
            ppVO.setLikeNum(caseDetails.getAdmireNum());
            ppVO.setStudyCount(caseDetails.getStudyNum());
            ppVO.setStartTime(caseDetails.getSubmitTime());

            return ppVO;
        }).collect(toList());

        return portalPlateVOs;
    }

    /**
     * 获取策略的列表
     *
     * @param portalPlateVOList
     * @return
     */
    public Page<PortalPlateVO> getDroolList(List<PortalPlateVO> portalPlateVOList, Integer pageNo) {
        Page<PortalPlateVO> portalPlateVOPage = new Page<>();

        List<Long> ids = portalPlateVOList.parallelStream().map(portalPlateVO -> {
            return portalPlateVO.getId();
        }).collect(toList());
        // 显示 数量
        Integer num = portalPlateVOList.get(0).getNum();
        // 获取智能推荐列表
        List<BusinessVo4Portal> businessVo4Portals = null;
        try {
            BusinessVo4PortalParam businessVo4PortalParam = new BusinessVo4PortalParam();
            businessVo4PortalParam.setPageNo(pageNo);
            businessVo4PortalParam.setPageSize(num);
            businessVo4PortalParam.setStrategyIds(ids);
            businessVo4PortalParam.setRequestContext(ContextHolder.get());
            LOGGER.info(" 参数：{}", JSON.toJSON(businessVo4PortalParam));
            BusinessVo4PortalResponse businessVo4PortalResponse = recommendStrategyClient.businessVo4Portal(businessVo4PortalParam);
            LOGGER.info(" 智能推荐返回结果：{}", JSON.toJSON(businessVo4PortalResponse));
            businessVo4Portals = businessVo4PortalResponse.getList();

            if (CollectionUtils.isNotEmpty(businessVo4Portals)) {
                LOGGER.info("智能推荐返回不为空");
                portalPlateVOList = businessVo4Portals.parallelStream().map(businessVo4Portal -> {
                    PortalPlateVO portalPlateVO = new PortalPlateVO();
                    // portalPlateVO.setId(businessVo4Portal.getId());
                    if ("live".equals(businessVo4Portal.getType())) {
                        try {
                            LOGGER.info("直播id:{}", businessVo4Portal.getId());
                            String channelNo = liveActivityClient.getChannelNo(businessVo4Portal.getId());
                            LOGGER.info("直播id:{}", channelNo);
                            portalPlateVO.setId(Long.valueOf(channelNo));
                            portalPlateVO.setActivityId(businessVo4Portal.getId());
                        } catch (Exception e) {
                            LOGGER.error("直播报错:", e);
                        }
                    } else {
                        portalPlateVO.setId(businessVo4Portal.getId());
                    }
                    portalPlateVO.setName(businessVo4Portal.getName());
                    portalPlateVO.setImage(businessVo4Portal.getImage());
                    portalPlateVO.setType(businessVo4Portal.getType());
                    return portalPlateVO;
                }).collect(toList());

                portalPlateVOPage.setRecords(portalPlateVOList);
                portalPlateVOPage.setTotal(businessVo4PortalResponse.getTotal());
                portalPlateVOPage.setCurrent(businessVo4PortalResponse.getPageNo());
                portalPlateVOPage.setSize(businessVo4PortalResponse.getPageSize());
            } else {
                portalPlateVOPage.setRecords(new ArrayList<>());
                portalPlateVOPage.setTotal(0);
                portalPlateVOPage.setCurrent(pageNo);
                portalPlateVOPage.setSize(num);
            }
        } catch (Exception e) {
            LOGGER.error("智能推荐接口异常：", e);
        }
        return portalPlateVOPage;
    }

    /**
     * 专辑模块
     *
     * @param portalPlateVOList
     * @return
     */
    public List<PortalPlateVO> getAlbumlList(List<PortalPlateVO> portalPlateVOList) {

        List<Long> ids = portalPlateVOList.parallelStream().map(portalPlateVO -> {
            return portalPlateVO.getId();
        }).collect(toList());
        List<ApiListAlbumVo> albumList = null;
        try {
            albumList = albumClient.getPortalList(ids);
            if (CollectionUtils.isNotEmpty(albumList)) {
                LOGGER.info("专辑返回：{}", JSON.toJSON(albumList));
                portalPlateVOList = albumList.parallelStream().map(apiListAlbumVo -> {
                    PortalPlateVO portalPlateVO = new PortalPlateVO();
                    portalPlateVO.setId(apiListAlbumVo.getId());
                    portalPlateVO.setName(apiListAlbumVo.getName());
                    portalPlateVO.setImage(apiListAlbumVo.getImage());
                    portalPlateVO.setDuration(apiListAlbumVo.getDuration().intValue());
                    portalPlateVO.setStatus(apiListAlbumVo.getOvered());
                    portalPlateVO.setStudyCount(apiListAlbumVo.getStudyNum());
                    portalPlateVO.setUpdateTime(apiListAlbumVo.getUnLockTime());
                    //新增已完结状态下专辑包含的课程数
                    portalPlateVO.setTotal(apiListAlbumVo.getCourseNum());
                    return portalPlateVO;
                }).collect(toList());
                return portalPlateVOList;
            } else {
                return new ArrayList<>();
            }
        } catch (Exception e) {
            LOGGER.error("智能推荐接口异常：", e);
            return new ArrayList<>();
        }
    }
}
