package com.yizhi.application.protal.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.yizhi.album.application.feign.AlbumClient;
import com.yizhi.album.application.vo.ApiListAlbumVo;
import com.yizhi.application.tools.PageTools;
import com.yizhi.assignment.application.feign.AssignmentClient;
import com.yizhi.certificate.application.feign.CertificateClient;
import com.yizhi.core.application.context.ContextHolder;
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.ModuleAllVoCourse;
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.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.*;
import com.yizhi.research.application.feign.ResearchClient;
import com.yizhi.sign.application.feign.SignManageClient;
import com.yizhi.site.application.enums.FunctionTypeCode;
import com.yizhi.site.application.enums.PortalEnum;
import com.yizhi.site.application.feign.PageFooterClient;
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.*;
import com.yizhi.site.application.vo.site.*;
import com.yizhi.system.application.enums.TerminalType;
import com.yizhi.system.application.system.remote.LoginLogClient;
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.TrainingProjectVo;
import com.yizhi.util.application.constant.ReturnCode;
import com.yizhi.util.application.domain.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

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

@Api(tags = "门户学员PC端接口", description = "门户学员PC端接口")
@RestController
@RequestMapping("/api/portal/pc")
@SuppressWarnings("unused")
public class PortalApiPcController {

    private static final Logger LOG = LoggerFactory.getLogger(PortalApiPcController.class);

    @Autowired
    private PageFooterClient pageFooterClient;


    @Autowired
    private LoginLogClient loginLogClient;


    @Autowired
    private PortalApiPCFeignClients portalApiPCFeignClients;

    @Autowired
    private LiveActivityClient liveActivityClient;

    @Autowired
    private TrainingProjectClient trainingProjectClient;

    @Autowired
    private CoursePcClient coursePcClient;
    @Autowired
    private CourseClient courseClient;
    @Autowired
    private PortalManagePCFeignClients portalManagePCFeignClients;
    @Autowired
    private ExamClient examClient;
    @Autowired
    private ResearchClient researchClient;
//    @Autowired
//    private VoteClient voteClient;
    @Autowired
    private AssignmentClient assignmentClient;
    @Autowired
    private CertificateClient certificateClient;
    @Autowired
    private SignManageClient signManageClient;
    @Autowired
    private OfflineCourseClient offlineCourseClient;
    @Autowired
    private TpPlanActivityClient tpPlanActivityClient;

    @Autowired
    private PortalApiFeignClients portalApiFeignClients;

    @Autowired
    private LecturerClient lecturerClient;

    @Autowired
    private FunctionDisplayConfigApiClients configApiClients;

    @Autowired
    private PortalUtil portalUtil;

    @Autowired
    private HomePageController homePageController;

    @Autowired
    StudentCaseClient studentCaseClient;

    @Autowired
    private RecommendStrategyClient recommendStrategyClient;

    @Autowired
    private AlbumClient albumClient;
    @Autowired
    EnrollFeignClient enrollFeignClient;


    @ApiOperation(value = "PC学员端首页第一行信息", notes = "首页第一行信息", response = PortalHomeOtherVO.class)
    @GetMapping("/base/message")
    public Response<ApiPortalPCBaseMessage> baseInformation(@ApiParam(name = "terminalType", value = "终端类型", required = true) Integer terminalType) {
        try {
            ApiPortalPCBaseMessage apiPortalPCBaseMessage = new ApiPortalPCBaseMessage();
            Long siteId = ContextHolder.get().getSiteId();

            HomeLogoEntityVo homeLogo = portalApiPCFeignClients.baseMeaage(siteId, terminalType);
            if (homeLogo != null) {
                apiPortalPCBaseMessage.setImgLogo(homeLogo.getLogoPath());
            }
            //前端调用别人的接口
		       /*apiPortalPCBaseMessage.setSiteName(ContextHolder.get().getSiteName());
		       apiPortalPCBaseMessage.setMessageNum(0);
		       apiPortalPCBaseMessage.setAccountName(ContextHolder.get().getAccountName());*/
            return Response.ok(apiPortalPCBaseMessage);
        } catch (Exception e) {
            LOG.error("门户logo:", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }


    @ApiOperation(value = "PC学员端首页链接信息/上边", notes = "PC学员端首页链接信息/上边", response = ApiPortalPCBaseMessage.class)
    @GetMapping("/link/up")
    public Response<ApiPortalPCLink> listApiPortalPCLinkUp(@ApiParam(name = "terminalType", value = "终端类型", required = true) Integer terminalType) {
        try {
            Long siteId = ContextHolder.get().getSiteId();
            return Response.ok(portalApiPCFeignClients.listApiPortalPCLinkUp(siteId, terminalType));
        } catch (Exception e) {
            LOG.error("PC学员端首页链接信息/上边:", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }


    @ApiOperation(value = "PC学员端首页轮播图", notes = "PC学员端首页轮播图", response = PortalImageVo.class)
    @GetMapping("/banner/image")
    public Response<List<PortalImageVo>> listApiPortalPCBanner(@ApiParam(name = "terminalType", value = "终端类型", required = true) Integer terminalType) {
        try {
            Long siteId = ContextHolder.get().getSiteId();
            return Response.ok(portalApiPCFeignClients.listApiPortalPCPortalImage(siteId, terminalType));
        } catch (Exception e) {
            LOG.error("PC学员端首页轮播图:", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }


    @ApiOperation(value = "PC学员端首页访问人数", notes = "PC学员端首页访问人数", response = Integer.class)
    @GetMapping("/look/num")
    public Response<Long> listApiPortalPCLookNum(@ApiParam(name = "terminalType", value = "终端类型1.pc,2 App,3 微信", required = true)
                                                 @RequestParam(name = "terminalType") Integer terminalType) {
        try {
            Long siteId = ContextHolder.get().getSiteId();
            TrPortalLookNumVo trPortalLookNum = portalApiPCFeignClients.listApiPortalPCPortalLookNum(siteId, terminalType);
            LOG.info("站点id：" + siteId + ";terminalType:" + terminalType);
            LOG.info("TTL:" + trPortalLookNum);
            if (trPortalLookNum != null) {
                if (trPortalLookNum.getDisplay() == 1) {
                    Integer defaultLookNum =
                            (trPortalLookNum.getDefaultNum() != null ? trPortalLookNum.getDefaultNum() : 0);

                    //1代表pc登陆
                    Integer loginNum = loginLogClient.loginLookNum(siteId, terminalType);
                    LOG.info("visitor TTL:" + loginNum);
                    return Response.ok(defaultLookNum + (loginNum != null ? loginNum : 0));
                } else {
                    return Response.ok();
                }
            } else {
                return Response.ok();
            }

        } catch (Exception e) {
            LOG.error("学员端首页访问人数:", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }


    @ApiOperation(value = "PC学员端首页直播", notes = "PC学员端首页直播", response = ApiPortalPCBaseMessage.class)
    @GetMapping("/live")
    public Response<ApiPortalPCLive> listApiPortalPCLive(@ApiParam(name = "terminalType", value = "终端类型", required = true) Integer terminalType) {
        try {
            ApiPortalPCLive apiPortalPCLive = null;
            Long siteId = ContextHolder.get().getSiteId();
            Long liveId = portalApiPCFeignClients.getLiveActivityPc(siteId, terminalType);
            if (liveId != null) {
                LiveActivityResultVO vo = liveActivityClient.get(liveId);
                if (vo != null) {
                    //0全平台
                    LiveActivityVO liveActivity = vo.getLiveActivity();
                    List<ScopeAuthorizationVO> listScopeAuthorization = vo.getScopeAuthorizations();
                    List<Long> relationList = new ArrayList<Long>();
                    listScopeAuthorization.forEach(e->relationList.add(e.getAccountId()));
                    if (liveActivity != null) {
                        boolean isContain = false;//判断是否可见

                        if (liveActivity.getScope() == 0) {//全平台可见，可以看到
                            isContain = true;
                        }
                        if (liveActivity.getScope() == 1) {//指定范围
                            List<Long> relationIds = ContextHolder.get().getRelationIds();
                            if (CollectionUtils.isNotEmpty(relationIds)) {
                                for (int i = 0; i < relationIds.size(); i++) {
                                    Long relation = relationIds.get(i);
                                    isContain = relationList.contains(relation);
                                    if (isContain) {
                                        break;
                                    } else {
                                        continue;
                                    }
                                }
                            }
                        }
                        if (isContain) {
                            apiPortalPCLive = new ApiPortalPCLive();
                            apiPortalPCLive.setId(liveActivity.getId());
                            apiPortalPCLive.setTitle(liveActivity.getTitle());
                            apiPortalPCLive.setTeacherName(liveActivity.getAnchor());
                            apiPortalPCLive.setLogo(liveActivity.getLogoImage());
                            apiPortalPCLive.setChannel(liveActivity.getChannel());
                            apiPortalPCLive.setViewType(liveActivity.getViewType());
                            apiPortalPCLive.setLiveStartTime(liveActivity.getStartTime());
                            apiPortalPCLive.setLiveEndTime(liveActivity.getEndTime());
                            apiPortalPCLive.setOnlineCount(0);
                            SimpleDateFormat sim = new SimpleDateFormat("MM/dd  HH:mm");
                            if (liveActivity.getStartTime() != null && liveActivity.getEndTime() != null) {
                                String startTime = sim.format(liveActivity.getStartTime());
                                String endTime = sim.format(liveActivity.getEndTime());
                                apiPortalPCLive.setStartTime(startTime + "~" + endTime);
                            }
                            Integer state = -1;
                            String channelId = liveActivity.getChannel();
                            try {
                                state = liveActivityClient.getLiveStatus(channelId);
                                if (null != state && state.equals(30)){
                                    //直播中获取在学人数
                                    List<LiveOnlineCountVo> liveOnlineCountVos = liveActivityClient.liveCountOnlineRealTime(channelId);
                                    if (null != liveOnlineCountVos && !liveOnlineCountVos.isEmpty()){
                                        LiveOnlineCountVo liveOnlineCountVo = liveOnlineCountVos.get(0);
                                        Integer onlineCount = liveOnlineCountVo.getCount();
                                        apiPortalPCLive.setOnlineCount(onlineCount);
                                    }
                                }
                            } catch (Exception e) {
                                LOG.info("直播状态获取异常。",e);
                            }
                            apiPortalPCLive.setState(state);
                        }

                    }
                }
            }

            return Response.ok(apiPortalPCLive);
        } catch (Exception e) {
            LOG.error("PC学员端首页直播:", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }


    @ApiOperation(value = "PC学员端首页链接信息/下边", notes = "PC学员端首页链接信息/下边", response = ApiPortalPCBaseMessage.class)
    @GetMapping("/link/down")
    public Response<ApiPortalPCLink> listApiPortalPCLinkDown(@ApiParam(name = "terminalType", value = "终端类型", required = true) Integer terminalType) {
        try {
            Long siteId = ContextHolder.get().getSiteId();
            return Response.ok(portalApiPCFeignClients.listApiPortalPCLinkDown(siteId, terminalType));
        } catch (Exception e) {
            LOG.error("PC学员端首页链接信息/下边:", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }


    @ApiOperation(value = "PC学员端首页公告", notes = "PC学员端首页公告", response = ApiPortalPCBaseMessage.class)
    @GetMapping("/announcement/select")
    public Response<List<AnnouncementVO>> getApiRelationAnnouncement(@ApiParam(name = "terminalType", value = "终端类型", required = true) Integer terminalType) {
        try {
            Long siteId = ContextHolder.get().getSiteId();
            return Response.ok(portalApiPCFeignClients.getApiRelationAnnouncement(siteId, terminalType));
        } catch (Exception e) {
            LOG.error("PC学员端首页公告:", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }


    @ApiOperation("返回模板列表信息")
    @GetMapping("/module/list/select")
    public Response<List<PortalTemplateVo>> moduleListSelect(
            @ApiParam(name = "terminalType", value = "终端类型", required = true) Integer terminalType) {
        try {
            Long siteId = ContextHolder.get().getSiteId();
            return Response.ok(portalApiPCFeignClients.moduleListSelectApi(siteId, terminalType));
        } catch (Exception e) {
            LOG.error("返回模板列表信息:", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }


    @ApiOperation("模板内容展示")
    @GetMapping("/template/content/view")
    public Response templateContentView(
            @ApiParam(name = "id", value = "模板ID", required = true) @RequestParam(name = "id", required = true) Long id,
            @ApiParam(name = "pageNo", value = "当前页", required = true) @RequestParam(name = "pageNo", required = true, defaultValue = "1") Integer pageNo,
            @ApiParam(name = "moduleType", value = "板块类型,1:推荐/精选,2:项目培训,3:课程,4,讲师库,5:新闻", required = true) @RequestParam(name = "moduleType", required = true) Integer moduleType) {

        Page<ModuleAllVO> moduleAllVOPage = new Page<>();
        //展示集合
        List<ModuleAllVO> listModuleAllVO =null;
        try {
            if (moduleType == PortalEnum.TEN.ordinal()){
                //专区
                listModuleAllVO = new ArrayList<ModuleAllVO>(16);
                portalUtil.getSiteStudentPC(listModuleAllVO,id);
                return Response.ok(listModuleAllVO);
            }
            listModuleAllVO = new ArrayList<ModuleAllVO>();
            //学时
            List<FunctionDisplayConfigVo> dataFunction = configApiClients.getAllBySiteId();

            Map<String, List<FunctionDisplayConfigVo>> functionDisplay = dataFunction.stream().collect(Collectors.groupingBy(FunctionDisplayConfigVo::getFunctionType));

            Boolean courseShowDisplay = functionDisplay.get(FunctionTypeCode.COURSE.getCode()).get(0).getShowDisplay();
            LOG.info("课程是否显示：" + courseShowDisplay);
            Boolean trainingShowDisplay = functionDisplay.get(FunctionTypeCode.TRAINING.getCode()).get(0).getShowDisplay();
            LOG.info("培训学时是否显示：" + trainingShowDisplay);


            //模板关联的活动信息
            List<ProtalPlateVo> listProtalPlate = portalApiPCFeignClients.templateContentView(id);
            ModuleAllVO mv = null;
            if (moduleType == 1 && listProtalPlate != null && listProtalPlate.size() > 0) {
                //有些模块 没有默认图片，采用甲方给的默认图片
                List<RelationLinkVo> listRelationLink = portalManagePCFeignClients.getAllListLink(null, 2);
                for (ProtalPlateVo portalPlate : listProtalPlate) {
                    Long mId = portalPlate.getLinkContent();
                    String type = portalPlate.getLinkType().toString();
                    String imgUrl = portalPlate.getImgPath();//新图片
                    Integer thumbnail = portalPlate.getThumbnail();//缩略图, 1:使用内容图片, 2:使用新图片
                    //有logo的业务：  课程、线下课程、投票、直播、证书、  培训项目
                    //没有logo：          考试、调研、作业
                    //0 '课程'      1 '考试'             2  '调研'             3  '直播'             4  '投票'                5  '作业'              6  '证书'         7  '外部链接'      8  '报名'       9  '签到'       10  '线下课程'
                    //8，9只是培训项目的条件，不是培训项目的活动
                    mv = portalUtil.getRecommend(mId, Integer.parseInt(type), thumbnail, imgUrl, listRelationLink);
                    //模块类型
                    mv.setModuleType(type);
                    listModuleAllVO.add(mv);
                }
                if(org.apache.commons.collections.CollectionUtils.isNotEmpty(listModuleAllVO)){
                    LOG.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
                    LOG.info("返回数据= {}", JSON.toJSONString(listModuleAllVO));
                    List<Long> filterData = listModuleAllVO.stream().filter(moduleItem -> "3".equals(moduleItem.getModuleType()))
                            .map(moduleItemId->moduleItemId.getId()).collect(toList());
                    LOG.info("过滤完的数据= {}", JSON.toJSONString(filterData));
                    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()));
                        LOG.info("查询出来的直播信息= {}", JSON.toJSONString(dataMap));
                        for(ModuleAllVO itemTmp :  listModuleAllVO){
                            if("3".equals(itemTmp.getModuleType()) && dataMap.containsKey(itemTmp.getId())){
                                itemTmp.setViewType(dataMap.get(itemTmp.getId()));
                            }
                        }
                    }
                }
            } else if (moduleType == 2) {
                List<TrainingProjectVoPortalVo> listTrainingProjectPortalVo = null;
                List<Long> listIds = new ArrayList<Long>();
                SimpleDateFormat formate = new SimpleDateFormat("yyyy-MM-dd");
                if (CollectionUtils.isNotEmpty(listProtalPlate)) {
                    for (ProtalPlateVo plate : listProtalPlate) {
                        listIds.add(plate.getLinkContent());
                    }
                    listTrainingProjectPortalVo = trainingProjectClient.getTrainingListByIds(listIds);
                    //因为要根据sort排序，所以循环重新装
                    List<TrainingProjectVoPortalVo> listSort = new ArrayList<TrainingProjectVoPortalVo>();
                    for (Long trainingProjectId : listIds) {
                        for (TrainingProjectVoPortalVo trainingProjectPortalVo : listTrainingProjectPortalVo) {
                            Long tpId = trainingProjectPortalVo.getId();
                            if (trainingProjectId.longValue() == tpId.longValue()) {
                                listSort.add(trainingProjectPortalVo);
                                break;
                            } else {
                                continue;
                            }
                        }
                    }

                    //如果查到培训项目
                    if (CollectionUtils.isNotEmpty(listSort)) {
                        //多四个，截取四个
                        if (listSort.size() >= 4) {
                            listSort = listSort.subList(0, 4);
                        }
                        listTrainingProjectPortalVo = listSort;
                    }
                }
                if (CollectionUtils.isNotEmpty(listTrainingProjectPortalVo)) {
                    for (TrainingProjectVoPortalVo tp : listTrainingProjectPortalVo) {
                        mv = new ModuleAllVO();
                        List<Long> listCourseIds = tp.getListCourseIds();
                        mv.setActivityNum(0);
                        if (CollectionUtils.isNotEmpty(listCourseIds)) {

                            //获取除了证书外的活动数
                            List<Long> activeIds = tpPlanActivityClient.getExcCertiferActiveCountById(tp.getId());
                            if (null != activeIds){
                                mv.setActivityNum(activeIds.size());
                            }

                            Long courseTotalTime = 0L;
                            Map<Long, Long> map = coursePcClient.getMaterialTimeByCourseIds(listCourseIds);
                            for (int i = 0; i < listCourseIds.size(); i++) {
                                Long courseMs = 0L;
                                if (map != null) {
                                    courseMs = map.get(listCourseIds.get(i));
                                }

                                if (courseMs == null) {
                                    courseMs = 0L;
                                }
                                courseTotalTime = courseTotalTime + courseMs;
                            }
                            mv.setCourseTotalTime(courseTotalTime);
                        } else {
                            mv.setActivityNum(0);
                            mv.setCourseTotalTime(0L);
                        }
                        mv.setId(tp.getId());
                        mv.setModuleName(tp.getName());
                        mv.setModuleLogo(tp.getLogoImg());
                        mv.setStartTime(formate.format(tp.getStartTime()));
                        mv.setEndTime(formate.format(tp.getEndTime()));
                        // 是否显示学时
                        mv.setCourseDurationShow(trainingShowDisplay);
                        // 培训学时
                        mv.setTotalDuration(homePageController.getStudyHour(listCourseIds));
                        listModuleAllVO.add(mv);
                    }
                }
            } else if (moduleType == 3) {
                List<Long> listIds = null;
                List<ModuleAllVoCourse> listModuleAllVoCourse = null;
                if (CollectionUtils.isNotEmpty(listProtalPlate)) {
                    listIds = new ArrayList<Long>();
                    for (ProtalPlateVo plate : listProtalPlate) {
                        listIds.add(plate.getLinkContent());
                    }
                    listModuleAllVoCourse = coursePcClient.listCoursePCgrade(listIds);
                    //排序
                    //拿着关联id如果查到课程
                    if (CollectionUtils.isNotEmpty(listModuleAllVoCourse)) {
                        List<ModuleAllVoCourse> listSort = new ArrayList<ModuleAllVoCourse>();
                        for (Long courseId : listIds) {
                            for (ModuleAllVoCourse moduleAllVoCourse : listModuleAllVoCourse) {
                                if (courseId.longValue() == moduleAllVoCourse.getId()) {
                                    listSort.add(moduleAllVoCourse);
                                    break;
                                } else {
                                    continue;
                                }
                            }
                        }
                        listModuleAllVoCourse = listSort;
                        //多余十个截取10个
                        if (listModuleAllVoCourse.size() >= 10) {
                            listModuleAllVoCourse.subList(0, 10);
                        }

                    }

                }

                //循环装到输出对象
                if (CollectionUtils.isNotEmpty(listModuleAllVoCourse)) {
                    BigDecimal bigDecimalValue1 = new BigDecimal(5.0);//没有评分给5分
                    List<Long> listCourseIds = new ArrayList<Long>();
                    for (int i = 0; i < listModuleAllVoCourse.size(); i++) {
                        listCourseIds.add(listModuleAllVoCourse.get(i).getId());
                    }
                    Map<Long, Long> map = coursePcClient.getMaterialTimeByCourseIds(listCourseIds);

                    for (ModuleAllVoCourse mavc : listModuleAllVoCourse) {
                        mv = new ModuleAllVO();
                        Long ms = map.get(mavc.getId());
                        if (ms == null) {
                            ms = 0L;
                        }
                        mv.setId(mavc.getId());
                        mv.setModuleName(mavc.getModuleName());
                        mv.setCourseTotalTime(ms);
                        mv.setModuleLogo(mavc.getModuleLogo());
                        mv.setCourseNum(mavc.getCourseNum());
                        mv.setStudyNum(mavc.getCourseNum());
                        if (mavc.getGrade() == null) {
                            mv.setGrade(bigDecimalValue1);
                        } else {
                            mv.setGrade(mavc.getGrade());
                        }

                        //add bylingye
                        mv.setTotalDuration(mavc.getTotalDuration());
                        mv.setCourseDurationShow(courseShowDisplay);
                        // 课程 学习状态
                        List<Long> courseIdList = new ArrayList<>();
                        courseIdList.add(mavc.getId());
                        try {
                            List<CourseStudentStatusVO> statusByIds = coursePcClient.getStatusByIds(courseIdList);
                            LOG.info("获取到的课程状态：" + statusByIds);
                            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(statusByIds)) {
                                Integer studentStatus = statusByIds.get(0).getStudentStatus();
                                mv.setStatus(studentStatus);
                            }
                        } catch (Exception e) {
                            LOG.info("课程完成状态异常：{}", e.getMessage());
                        }
                        listModuleAllVO.add(mv);
                    }
                }
            } else if (moduleType == 5) {
                //查询已经关联的新闻
                List<InformationViewVO> list = portalManagePCFeignClients.getRelationInformation(id);
                if (CollectionUtils.isNotEmpty(list)) {
                    List<Long> listIds = new ArrayList<Long>();
                    for (int i = 0; i < list.size(); i++) {
                        listIds.add(list.get(i).getId());
                    }

                }
                //新闻循环装入到对象中
                if (CollectionUtils.isNotEmpty(list)) {
                    for (InformationVo information : list) {
                        mv = new ModuleAllVO();
                        mv.setId(information.getId());
                        mv.setModuleName(information.getFileName());
                        mv.setModuleLogo(information.getLogoPath());
                        mv.setNewsContent(information.getContent());
                        mv.setNewsReadCount(portalApiPCFeignClients.newsReadCount(information.getId()));
                        mv.setCreateTime(information.getReleaseTime());
                        if (information.getReleaseTime() != null) {
                            mv.setReleaseTime(DateUtil.format(information.getReleaseTime(),"yyyy-MM-dd HH:mm"));
                        }
                        listModuleAllVO.add(mv);
                    }
                    //按照创建时间倒叙排序listModuleAllVO
                    listModuleAllVO = listModuleAllVO.stream().sorted(Comparator.comparing(ModuleAllVO::getCreateTime).reversed()).collect(toList());
                }

            } else if (moduleType == PortalEnum.FOUR.ordinal()) {
                // 首页显示 add by 2019-5-8 16:55:13
                List<PortalPlateVO> portalPlateVOList = portalApiFeignClients.getPlateVOList(id);
                listModuleAllVO = portalPlateVOList.parallelStream().map(
                        portalPlateVO -> {
                            ModuleAllVO moduleAllVO = new ModuleAllVO();
                            LecturerVo lecturer = lecturerClient.getLecturerById(portalPlateVO.getId());
                            moduleAllVO.setId(lecturer.getId());
                            moduleAllVO.setModuleName(lecturer.getLecturerName());
                            moduleAllVO.setModuleLogo(lecturer.getAvatar());
                            moduleAllVO.setNewsContent(lecturer.getTitle());
                            moduleAllVO.setSource(lecturer.getSourceCode());
                            return moduleAllVO;
                        }
                ).collect(toList());
            } else if (moduleType == PortalEnum.SIX.ordinal()) {
                // 配置案例库 add by lingye
                List<PortalPlateVO> portalPlateVOList = portalApiFeignClients.getPlateVOList(id);
                listModuleAllVO = portalPlateVOList.parallelStream().map(
                        portalPlateVO -> {
                            ModuleAllVO moduleAllVO = new ModuleAllVO();
                            FavoriteVO studentCaseDetail = studentCaseClient.getStudentCaseDetail(portalPlateVO.getId());
                            moduleAllVO.setId(studentCaseDetail.getStudentCaseId());
                            moduleAllVO.setModuleName(studentCaseDetail.getStudentCaseTittle());
                            moduleAllVO.setModuleLogo(studentCaseDetail.getStudentCaseLogoUrl());
                            moduleAllVO.setCreateByName(studentCaseDetail.getAuthorFullName());
                            moduleAllVO.setCreateTime(studentCaseDetail.getSubmitTime());
                            moduleAllVO.setLikeNum(studentCaseDetail.getAdmireNum());
                            moduleAllVO.setStudyNum(studentCaseDetail.getStudyNum());
                            return moduleAllVO;
                        }
                ).collect(toList());

            } else if (moduleType == PortalEnum.SEVEN.ordinal()) {

                // 获取智能推荐内容id列表
                List<Long> ids = listProtalPlate.parallelStream().map(protalPlate -> {
                    return protalPlate.getLinkContent();
                }).collect(toList());
                PortalTemplateVo portalTemplate = portalApiPCFeignClients.getPortalTemplate(id);
                Integer num = portalTemplate != null ? portalTemplate.getNum() : 8;

                LOG.info("模块首页展示的内容的数量：{}", num);

                List<BusinessVo4Portal> businessVo4Portals = null;
                try {

                    BusinessVo4PortalParam businessVo4PortalParam = new BusinessVo4PortalParam();
                    businessVo4PortalParam.setStrategyIds(ids);
                    businessVo4PortalParam.setPageNo(pageNo);
                    businessVo4PortalParam.setPageSize(num);
                    businessVo4PortalParam.setRequestContext(ContextHolder.get());
                    LOG.info(" 参数：{}", JSON.toJSON(businessVo4PortalParam));
                    BusinessVo4PortalResponse businessVo4PortalResponse = recommendStrategyClient.businessVo4Portal(businessVo4PortalParam);
                    LOG.info("智能推荐返回的结果：{}", JSON.toJSON(businessVo4PortalResponse));
                    businessVo4Portals = businessVo4PortalResponse.getList();
                    if (CollectionUtils.isNotEmpty(businessVo4Portals)) {
                        listModuleAllVO = businessVo4Portals.parallelStream().map(businessVo4Portal -> {
                            ModuleAllVO moduleAllVO = new ModuleAllVO();
                            moduleAllVO.setId(businessVo4Portal.getId());
                            moduleAllVO.setModuleName(businessVo4Portal.getName());
                            moduleAllVO.setModuleLogo(businessVo4Portal.getImage());
                            moduleAllVO.setType(businessVo4Portal.getType());
                            // 0'课程'  1'考试'  2'调研'  3'直播'  4'投票'  5'作业'  6'证书'  7'外部链接'  8'报名'  9'签到'  10'线下课程'
                            switch (businessVo4Portal.getType()) {
                                case "course":
                                    moduleAllVO.setModuleType("0");
                                    break;
                                case "trainingProject":
                                    moduleAllVO.setModuleType("12");
                                    break;
                                case "research":
                                    moduleAllVO.setModuleType("2");
                                    break;
                                case "case":
                                    moduleAllVO.setModuleType("14");
                                    break;
                                case "exam":
                                    moduleAllVO.setModuleType("1");
                                    break;
                                case "live":
                                    moduleAllVO.setModuleType("3");
                                    try {
                                        moduleAllVO.setChannel(liveActivityClient.getChannelNo(businessVo4Portal.getId()));
                                    } catch (Exception e) {
                                        LOG.info("直播报错");
                                    }
                                    break;
                                case "assignment":
                                    moduleAllVO.setModuleType("5");
                                    break;
                                case "caseActivity":
                                    moduleAllVO.setModuleType("17");
                                    break;
                                case "album":
                                    moduleAllVO.setModuleType("15");
                                    break;
                                case "forum":
                                    moduleAllVO.setModuleType("16");
                                    break;
                                default:
                                    break;
                            }
                            return moduleAllVO;
                        }).collect(toList());
                        if(org.apache.commons.collections.CollectionUtils.isNotEmpty(listModuleAllVO)){
                            List<Long> filterData = listModuleAllVO.stream().filter(moduleItem -> "3".equals(moduleItem.getModuleType()))
                                    .map(moduleItemId->moduleItemId.getId()).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(ModuleAllVO itemTmp :  listModuleAllVO){
                                    if("3".equals(itemTmp.getModuleType()) && dataMap.containsKey(itemTmp.getId())){
                                        itemTmp.setViewType(dataMap.get(itemTmp.getId()));
                                    }
                                }
                            }
                        }
                        moduleAllVOPage.setRecords(listModuleAllVO);
                        moduleAllVOPage.setTotal(businessVo4PortalResponse.getTotal());
                        moduleAllVOPage.setCurrent(businessVo4PortalResponse.getPageNo());
                        moduleAllVOPage.setSize(businessVo4PortalResponse.getPageSize());
                    } else {
                        moduleAllVOPage.setRecords(new ArrayList<>());
                        moduleAllVOPage.setTotal(businessVo4PortalResponse.getTotal());
                        moduleAllVOPage.setCurrent(businessVo4PortalResponse.getPageNo());
                        moduleAllVOPage.setSize(businessVo4PortalResponse.getPageSize());
                    }
                } catch (Exception e) {
                    LOG.info("智能推荐接口异常：{}", e.getMessage());
                }
            } else  if (moduleType == PortalEnum.EIGHT.ordinal()) {
                //我的专辑
                List<Long> ids = listProtalPlate.parallelStream().map(protalPlate -> {
                    return protalPlate.getLinkContent();
                }).collect(toList());

                List<ApiListAlbumVo>  portalList = null;
                try {
                    portalList = albumClient.getPortalList(ids);
                    if (CollectionUtils.isNotEmpty(portalList)) {
                        listModuleAllVO = portalList.parallelStream().map(albumVo -> {
                            ModuleAllVO moduleAllVO = new ModuleAllVO();
                            moduleAllVO.setId(albumVo.getId());
                            moduleAllVO.setModuleName(albumVo.getName());
                            moduleAllVO.setModuleLogo(albumVo.getImage());
                            moduleAllVO.setStatus(albumVo.getOvered());
                            moduleAllVO.setCourseTotalTime(albumVo.getDuration().longValue());
                            moduleAllVO.setStudyNum(albumVo.getStudyNum()!=null?albumVo.getStudyNum():0);
                            moduleAllVO.setUpdateTime(albumVo.getUnLockTime());
                            moduleAllVO.setCourseNum(albumVo.getCourseNum());
                            return moduleAllVO;
                        }).collect(toList());
                    }
                } catch (Exception e) {
                    LOG.info("专辑的接口：{}", e.getMessage());
                }
            } else if (moduleType == PortalEnum.NINE.ordinal()){
                ModuleAllVO moduleAllVO = new ModuleAllVO();
                ProtalPlateVo protalPlate = new ProtalPlateVo();
                if (CollectionUtils.isNotEmpty(listProtalPlate)) {
                    protalPlate = listProtalPlate.get(0);
                    moduleAllVO.setModuleLogo(protalPlate.getImgPath());
                } else {
                    moduleAllVO.setModuleLogo("");
                }
                listModuleAllVO.add(moduleAllVO);
            }else if (moduleType == PortalEnum.FIFTEEN.getValue()){
                //直播
                if (null != listProtalPlate && listProtalPlate.size() > 0){
                    listModuleAllVO = listProtalPlate.stream().map(protalPlateVo -> {
                        ModuleAllVO moduleAllVO = new ModuleAllVO();
                        Long liveId = protalPlateVo.getLinkContent();
                        if (null != liveId){
                            LiveActivityVO live = liveActivityClient.getLive(liveId);
                            String channel = live.getChannel();
                            Integer liveStatus = liveActivityClient.getLiveStatus(channel);
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            moduleAllVO.setId(live.getId());
                            moduleAllVO.setModuleName(live.getTitle());
                            moduleAllVO.setModuleLogo(live.getLogoImage());
                            moduleAllVO.setStartTime(format.format(live.getStartTime()));
                            moduleAllVO.setEndTime(format.format(live.getEndTime()));
                            moduleAllVO.setCreateByName(live.getAnchor());
                            moduleAllVO.setStatus(liveStatus);
                            moduleAllVO.setChannel(live.getChannel());
                            moduleAllVO.setViewType(live.getViewType());
                            //设置直播进行中状态下的在学人数
                            if (null != liveStatus && liveStatus.equals(30)){
                                //直播中
                                moduleAllVO.setLikeNum(0);
                                List<LiveOnlineCountVo> liveOnlineCountVos = liveActivityClient.liveCountOnlineRealTime(channel);
                                if (null != liveOnlineCountVos && liveOnlineCountVos.size() > 0){
                                    LiveOnlineCountVo onlineCountVo = liveOnlineCountVos.get(0);
                                    Integer onlineCountVoCount = onlineCountVo.getCount();
                                    moduleAllVO.setLikeNum(onlineCountVoCount);
                                }
                            }
                        }
                        return moduleAllVO;
                    }).collect(Collectors.toList());
                }
            }else if (moduleType == PortalEnum.TWELVE.getValue()){
                //付费资源-精选内容
                try {
                    listModuleAllVO = getPayResource(listModuleAllVO,listProtalPlate);
                    LOG.info("pc首页-精品内容size={}",listModuleAllVO.size());
                }catch (Exception e){
                    LOG.error("pc端获取付费资源异常: ",e);
                }

            }
            if (moduleType == PortalEnum.SEVEN.ordinal()) {
                return Response.ok(PageTools.versaPage(moduleAllVOPage));
            } else {
                return Response.ok(listModuleAllVO);
            }
        } catch (Exception e) {
            LOG.error("模板内容展示:", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

    /**
     * 获取付费资源 的精品内容列表
     * @param portalPlateList 模板关联付费资源列表
     *
     */
    private List<ModuleAllVO> getPayResource(List<ModuleAllVO> list, List<ProtalPlateVo> portalPlateList) {
        if (org.springframework.util.CollectionUtils.isEmpty(portalPlateList)){
            return list;
        }
        //pc端最多展示4个
        if (portalPlateList.size() > 4){
            portalPlateList = portalPlateList.subList(0,4);
            LOG.info("pc端付费精选内容列表长度大于4，截取后size = {}",portalPlateList.size());
        }
        portalPlateList.forEach(portalPlateVO -> {

            ModuleAllVO moduleVO = new ModuleAllVO();
           try {
               //类型 type=12 项目
               Integer activityType = portalPlateVO.getLinkType();
               if (null != activityType){
                   moduleVO.setModuleType(String.valueOf(activityType));
               }
               Long activityId = portalPlateVO.getLinkContent();
               //目前只有一个项目类型，故不做id区分
               TrainingProjectVo trainingProjectVo = trainingProjectClient.getOne(activityId);
               moduleVO.setId(activityId);
               moduleVO.setModuleName(trainingProjectVo.getName());
               //缩略图, 1:使用内容图片, 2:使用新图片
               Integer thumbnail = portalPlateVO.getThumbnail();
               moduleVO.setModuleLogo(trainingProjectVo.getLogoImg());
               if (null != thumbnail && thumbnail.equals(2)){
                   moduleVO.setModuleLogo(portalPlateVO.getImgPath());
               }
               //价格
               Integer enableEnroll = trainingProjectVo.getEnableEnroll();
               if (null == enableEnroll || !enableEnroll.equals(1)){
                   LOG.error("pc首页配置的付费项目未开启报名,trainingId = {}",activityId);
                   return;
               }
               Enroll enroll = enrollFeignClient.selectByProjectId(activityId);
               if (null == enroll){
                   LOG.error("pc首页配置的付费项目开启报名,但是查询报名信息为空,trainingId = {}",activityId);
                   return;
               }
               moduleVO.setActualPrice(enroll.getActualPrice());
               moduleVO.setOriginalPrice(enroll.getOriginalPrice());
               list.add(moduleVO);

           }catch (Exception e){
               LOG.error("pc首页获取付费资源异常: ",e);
           }
        });
        return list;
    }


    /**
     * 课程数量不足，补充课程
     */
    public List<ModuleAllVoCourse> supplyCourse(List<ModuleAllVoCourse> listModuleAllVoCourse, Integer num, List<Long> listIds) {
        List<Long> relationIds = ContextHolder.get().getRelationIds();
        List<ModuleAllVoCourse> listCourse = coursePcClient.listCourseScope(relationIds, num, listIds);
        if (CollectionUtils.isNotEmpty(listCourse)) {
            if (listModuleAllVoCourse != null) {
                listModuleAllVoCourse.addAll(listCourse);
            } else {
                listModuleAllVoCourse = listCourse;
            }
        }
        return listModuleAllVoCourse;
    }


    public List<TrainingProjectVo> supplyTrainingProject(List<TrainingProjectVo> listTrainingProject, Integer num, List<Long> listIds) {
        List<Long> relationIds = ContextHolder.get().getRelationIds();
        List<TrainingProjectVo> listTrainingProjectSupply = trainingProjectClient.pcTrainingProjectList(relationIds, num, listIds);
        if (CollectionUtils.isNotEmpty(listTrainingProjectSupply)) {
            if (listTrainingProject != null) {
                listTrainingProject.addAll(listTrainingProjectSupply);
            } else {
                listTrainingProject = listTrainingProjectSupply;
            }
        }
        return listTrainingProject;
    }


    public ApiPortalPCLive recommendLive(ApiPortalPCLive apiPortalPCLive) {
        List<PageLiveVo> list = liveActivityClient.queryLiveListByRelationIds(ContextHolder.get().getRelationIds(), 1, 1);
        if (CollectionUtils.isNotEmpty(list)) {
            PageLiveVo pageLiveVo = new PageLiveVo();
            pageLiveVo = list.get(0);
            apiPortalPCLive = new ApiPortalPCLive();
            apiPortalPCLive.setId(pageLiveVo.getId());
            apiPortalPCLive.setTitle(pageLiveVo.getTitle());
            apiPortalPCLive.setTeacherName(pageLiveVo.getAnchor());
            apiPortalPCLive.setLogo(pageLiveVo.getLogoImage());
            apiPortalPCLive.setChannel(pageLiveVo.getChannel());
            SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
            if (pageLiveVo.getStartTime() != null) {
                apiPortalPCLive.setStartTime(sim.format(pageLiveVo.getStartTime()));
            }
            Integer state = -1;
            String channelId = pageLiveVo.getChannel();
            try {
                state = liveActivityClient.getLiveStatus(channelId);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                LOG.info("直播状态获取异常。");
            }
            apiPortalPCLive.setState(state);
        }
        return apiPortalPCLive;
    }

    @GetMapping("/pageFooterItem/get")
    @ApiOperation(value = "查询页底信息", response = PageFooterVO.class)
    public Response<PageFooterVO> selectPage(@ApiParam(name = "TerminalType", value = "传入的类型(1 PC, 2 App, 3 微信)") @RequestParam(name = "TerminalType") Integer
        TerminalType

    ) {
        PageFooterVO vos = pageFooterClient.selectPage(TerminalType);
        return Response.ok(vos);

    }


}
