package com.yizhi.application.portal.controller;

import com.alibaba.fastjson.JSON;
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.portal.constant.SiteEnum;
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.CertificateListVO;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.core.application.enums.InternationalEnums;
import com.yizhi.course.application.feign.CourseClient;
import com.yizhi.course.application.feign.OfflineCourseClient;
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.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.StudentCaseStudyVO;
import com.yizhi.live.application.feign.LiveActivityClient;
import com.yizhi.live.application.vo.LiveActivityVO;
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.feign.InformationManageFeignClients;
import com.yizhi.site.application.feign.PortalManageFeignClients;
import com.yizhi.site.application.feign.PortalManagePCFeignClients;
import com.yizhi.site.application.feign.api.PortalApiFeignClients;
import com.yizhi.site.application.feign.api.PortalApiPCFeignClients;
import com.yizhi.site.application.vo.domain.InformationVo;
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.system.application.system.remote.SiteClient;
import com.yizhi.system.application.vo.SiteVO;
import com.yizhi.training.application.feign.TpPlanActivityClient;
import com.yizhi.training.application.feign.TrainingProjectClient;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lly
 * @date 2019年2月22日15:30:59
 */
@Api(tags = "管理端 站点首页设置")
@RestController
@RequestMapping("/manage/portal")
public class PortalController {

    private static final Logger LOGGER = LoggerFactory.getLogger(PortalController.class);

    @Autowired
    private PortalApiPCFeignClients portalApiPCFeignClient;
    @Autowired
    private PortalApiFeignClients portalApiFeignClients;

    @Autowired
    private PortalManageFeignClients portalManageFeignClients;

    @Autowired
    private TpPlanActivityClient projectActivityClient;


    @Autowired
    private TrainingProjectClient projectClient;

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

    @Autowired
    private OfflineCourseClient offlineCourseClient;

    @Autowired
    private LecturerClient lecturerClient;

    @Autowired
    private TpPlanActivityClient tpPlanActivityClient;
    @Autowired
    private StudentCaseClient studentCaseClient;

    @Autowired
    private PortalManagePCFeignClients portalManagePCFeignClients;

    @Autowired
    private RecommendStrategyClient recommendStrategyClient;

    @Autowired
    private AlbumClient albumClient;

    @Autowired
    private RemotePostsClient postClient;
    @Autowired
    private SiteClient remoteSiteClient;
    @Resource
    PracticeConfigStudentClient practiceConfigStudentClient;
    @Autowired
    private InformationManageFeignClients informationManageFeignClients;


    @ApiOperation(value = "轮播图、导航、公告列表", response = PortalPreviewVO.class)
    @GetMapping(value = {"/view"})
    public Response<PortalPlateVO> getPortalView(
            @ApiParam(name = "terminalId", value = "终端ID", required = true) @RequestParam(name = "terminalId") Long terminalId) {
        PortalPreviewVO portalPreviewVO = portalManageFeignClients.getPortalView(terminalId);

        return Response.ok(portalPreviewVO);
    }


    @ApiOperation(value = "管理端微信模块列表", response = PortalTemplateVO.class)
    @GetMapping("/module/list")
    public Response<List<PortalTemplateVO>> findModuleList(
            @ApiParam(name = "terminalId", value = "terminalId", required = true) @RequestParam(value = "terminalId") Long terminalId) {
        try {
            List<PortalTemplateVo> portalTemplateList = portalManageFeignClients.getManageModuleList(terminalId);
            List<TemplateVO> portalTemplateVOList = null;
            if (CollectionUtils.isNotEmpty(portalTemplateList)) {
                portalTemplateVOList = portalTemplateList.parallelStream().map(portalTemplate -> {
                    if (portalTemplate != null) {
                        TemplateVO portalTemplateVO = new TemplateVO();
                        portalTemplateVO.setId(portalTemplate.getId());
                        portalTemplateVO.setModuleName(portalTemplate.getModuleName());
                        portalTemplateVO.setType(portalTemplate.getModuleType());
                        return portalTemplateVO;
                    } else {
                        return null;
                    }
                }).collect(Collectors.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<List<PortalManageVO>> moduleListSelect(
            @ApiParam(name = "id", value = "模块id", required = true) @RequestParam(value = "id") Long id) {
        RequestContext context = ContextHolder.get();
        //模板关联的活动信息
        List<PortalPlateVO> portalPlateVOList = portalApiFeignClients.getPlateVOList(id);
        LOGGER.info("parameter portalPlateVOList:" + portalPlateVOList);

        PortalManageVO portalManageVO = new PortalManageVO();
        if (CollectionUtils.isEmpty(portalPlateVOList)) {
            PortalTemplateVo portalTemplate = portalManageFeignClients.getTemplateById(id);
            portalManageVO.setModuleType(portalTemplate.getModuleType());
            portalManageVO.setHomeId(portalTemplate.getHomeId());
            portalManageVO.setModuleName(portalTemplate.getModuleName());
            portalManageVO.setSiteId(portalTemplate.getSiteId());
            portalManageVO.setTemplateId(id);
            portalManageVO.setSort(portalTemplate.getSort());
            return Response.ok(portalManageVO);
        }


        PortalPlateVO portalPlateVO = portalPlateVOList.get(0);

        Integer type = Integer.valueOf(portalPlateVO.getType());
        portalManageVO.setModuleType(type);
        portalManageVO.setHomeId(portalPlateVO.getHomeId());
        portalManageVO.setModuleName(portalPlateVO.getModuleName());
        portalManageVO.setSiteId(portalPlateVO.getSiteId());
        portalManageVO.setTemplateId(portalPlateVO.getTemplateId());
        portalManageVO.setSort(portalPlateVO.getSort());

        List<PortalPlateVO> portalPlateVOS = new ArrayList<PortalPlateVO>(8);
        List<TemplatePlateVO> templatePlateVOS = new ArrayList<TemplatePlateVO>(8);

        switch (type) {
            case 1:
                // 推荐、精选
                try {
                    portalPlateVOS = getRecommendData(portalPlateVOList);
                    templatePlateVOS = getTemplateList(portalPlateVOS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 2:
                // 项目培训
                try {
                    portalPlateVOS = getTrainingProject(portalPlateVOList);
                    templatePlateVOS = getTemplateList(portalPlateVOS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 3:
                //课程
                try {
                    portalPlateVOS = getCourse(portalPlateVOList);
                    templatePlateVOS = getTemplateList(portalPlateVOS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 4:
                try {
                    portalPlateVOS = getLecturerList(portalPlateVOList);
                    templatePlateVOS = getTemplateList(portalPlateVOS);
                    LOGGER.info("讲师库:" + templatePlateVOS);
                } catch (Exception e) {
                    LOGGER.info("讲师库" + e.getMessage());
                }
                break;
            case 5:
                try {
                    //直播
                    portalPlateVOS = getLive(portalPlateVOList);
                    templatePlateVOS = getTemplateList(portalPlateVOS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 6:
                try {
                    portalPlateVOS = getCaseList(portalPlateVOList);
                    templatePlateVOS = getTemplateList(portalPlateVOS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 7:
                try {
                    templatePlateVOS = geDroolList(portalPlateVOList);
                } catch (Exception e) {
                    LOGGER.info("异常返回：{}", e.getMessage());
                }
                break;
            case 8:
                try {
                    templatePlateVOS = getAlbumList(portalPlateVOList);
                } catch (Exception e) {
                    LOGGER.info("专辑异常返回：{}", e.getMessage());
                }
                break;
            case 9:
                try {
                    templatePlateVOS = getForum(portalPlateVOList);
                } catch (Exception e) {
                    LOGGER.info("论坛：{}", e.getMessage());
                }
                break;
            case 10:
                try {
                    templatePlateVOS = new ArrayList<TemplatePlateVO>(16);
                    templatePlateVOS = getSiteStudent(portalPlateVOList, templatePlateVOS);
                } catch (Exception e) {
                    LOGGER.info("专区：{}", e.getMessage());
                }
                break;
            case 11:
                try {
                    //新闻资讯
                    templatePlateVOS = getNews(portalPlateVOList);

                } catch (Exception e) {
                    LOGGER.error("新闻资讯模板内容获取异常: ", e);
                }
                break;
            case 20:
                try {
                    templatePlateVOS = getCommunity(portalPlateVOList);
                } catch (Exception e) {
                    LOGGER.error("社群模板内容获取异常: ", e);
                }
                break;
            case 12:
                try {
                    //付费资源模块
                    templatePlateVOS = getPayResource(portalPlateVOList);

                }catch (Exception e){
                    LOGGER.error("付费资源模板内容获取异常: ",e);
                }
                break;


        }
        if (CollectionUtils.isNotEmpty(templatePlateVOS)) {
            portalManageVO.setTemplateList(templatePlateVOS);
        }

        return Response.ok(portalManageVO);

    }

    /**
     * 获取付费资源列表内容
     * @param portalPlateVOList 模板内容
     */
    private List<TemplatePlateVO> getPayResource(List<PortalPlateVO> portalPlateVOList) {

        List<TemplatePlateVO> list = new ArrayList<>();
        if (CollectionUtils.isEmpty(portalPlateVOList)){
            return list;
        }
        if (portalPlateVOList.size() > 8){
            portalPlateVOList = portalPlateVOList.subList(0,8);
            LOGGER.info("门户装修-付费资源-获取到模板内容列表长度大于8，截取长度size={}",portalPlateVOList.size());
        }
        portalPlateVOList.forEach(portalPlateVO -> {
            TemplatePlateVO templatePlateVO = new TemplatePlateVO();
            //类型 type=12 项目
            Integer activityType = portalPlateVO.getActivityType();
            if (null != activityType){
                templatePlateVO.setType(String.valueOf(activityType));
            }
            Long activityId = portalPlateVO.getActivityId();
            //目前只有一个项目类型，故不做id区分
            TrainingProjectVo projectVo = projectClient.getOne(activityId);
            templatePlateVO.setId(activityId);
            templatePlateVO.setTemplateId(portalPlateVO.getTemplateId());
            templatePlateVO.setModuleName(portalPlateVO.getModuleName());
            templatePlateVO.setSiteId(portalPlateVO.getSiteId());
            templatePlateVO.setLinkContentName(portalPlateVO.getName());
            templatePlateVO.setSort(portalPlateVO.getSort());
            templatePlateVO.setHomeId(portalPlateVO.getHomeId());
            //项目名称
            templatePlateVO.setTitle(projectVo.getName());
            //缩略图, 1:使用内容图片, 2:使用新图片
            Integer thumbnail = portalPlateVO.getThumbnail();
            templatePlateVO.setThumbnail(thumbnail);
            templatePlateVO.setImgPath(projectVo.getLogoImg());
            if (null != thumbnail && thumbnail.equals(2)){
                templatePlateVO.setImgPath(portalPlateVO.getImage());
            }

            list.add(templatePlateVO);

        });
        return list;
    }

    /**
     * 获取新闻资讯 模块列表
     */
    private List<TemplatePlateVO> getNews(List<PortalPlateVO> portalPlateVOList) {

        List<TemplatePlateVO> templatePlateVOList = new ArrayList<>();

        if (null == portalPlateVOList || portalPlateVOList.isEmpty()) {
            return templatePlateVOList;
        }
        portalPlateVOList.forEach(portalPlateVO -> {
            TemplatePlateVO templatePlateVO = new TemplatePlateVO();
            Long newsId = portalPlateVO.getActivityId();
            //获取新闻资讯详情；
            InformationVo info = informationManageFeignClients.informationView(newsId);
            BeanUtils.copyProperties(portalPlateVO, templatePlateVO);
            templatePlateVO.setId(info.getId());
            templatePlateVO.setSort(portalPlateVO.getSort());
            templatePlateVO.setImgPath(info.getLogoPath());
            templatePlateVO.setHomeId(portalPlateVO.getHomeId());
            //新闻标题
            templatePlateVO.setTitle(info.getFileName());
            templatePlateVO.setLinkContentName(info.getFileName());
            Date createTime = info.getReleaseTime();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String createTimeStr = format.format(createTime);
            templatePlateVO.setCreateByName(createTimeStr);
            templatePlateVOList.add(templatePlateVO);
        });
        return templatePlateVOList;
    }


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

        List<PortalPlateVO> portalPlateVOs = new ArrayList<>(8);

        for (PortalPlateVO ppVO : portalPlateVOList) {

            TpPlanActivityVo activity = projectActivityClient.getOne(ppVO.getId());


            //	0.课程 1考试 2调研 3直播 4投票 5作业 6证书 7外部链接 8报名 9签到 10线下课程 11营销课程  12培训项目 13门户外链，不是培训项目的外链
            Integer type = ppVO.getActivityType();
            Long id = ppVO.getActivityId();
            LOGGER.info("精选模块activityType" + type);
            //关联的活动没有类型就不处理
            if (type == null) {
                continue;
            }
            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());
                            }
                        }
                    } catch (Exception e) {
                        LOGGER.info("课程异常：" + 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.info("考试异常：" + 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.info("调研异常：" + 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());
                            if (ppVO.getThumbnail() == 1) {
                                ppVO.setImage(live.getLogoImage());
                            }
                        }
                    } catch (NumberFormatException e) {
                        LOGGER.info("直播异常：" + 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:
                    CertificateListVO 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:
                    //15专辑
                    Album album = null;
                    try {
                        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);
                    ppVO.setType(SiteEnum.POST.getValue());
                    try {
                        Map<Long, String> names = postClient.getNames(ids);
                        LOGGER.info("返回的结果：{}", JSON.toJSON(names));
                        String postName = names.get(id);
                        ppVO.setName(postName);
                    } catch (Exception e) {
                        LOGGER.error("帖子异常:{}", e.getMessage());
                    }
                    break;

                case 28:
                    try {
                        BizResponse<PracticeVo> response = practiceConfigStudentClient.getPractice(id);
                        PracticeVo practiceVo = response.getData();
                        LOGGER.info("智能陪练获取到陪练id= {},practiceVo = {}", id, practiceVo);
                        if (null != practiceVo) {
                            String name = practiceVo.getName();
                            ppVO.setName(name);
                            String image = ppVO.getImage();
                            if (StringUtils.isEmpty(image)) {
                                String logoUrl = practiceVo.getLogoUrl();
                                ppVO.setImage(logoUrl);
                            }
                        }
                        ppVO.setType(SiteEnum.MY_PRACTICE.getValue());

                    } catch (Exception e) {
                        LOGGER.error("智能演练获取异常:{}", e);
                    }
                    break;
                default:
                    break;
            }
            portalPlateVOs.add(ppVO);
        }
        return portalPlateVOs;
    }

    /**
     * 获取项目培训列表
     *
     * @param portalPlateVOList
     * @return
     */
    public List<PortalPlateVO> getTrainingProject(List<PortalPlateVO> portalPlateVOList) {
        LOGGER.info("返回列表：" + portalPlateVOList);
        return portalPlateVOList.parallelStream().map(portalPlateVO -> {
            TrainingProjectVo project = projectClient.getOne(portalPlateVO.getId());
            LOGGER.info("项目返回+++++++：" + project);

            if (project != null) {
                portalPlateVO.setName(project.getName());
                portalPlateVO.setImage(portalPlateVO.getThumbnail() == 0 ? project.getLogoImg() : portalPlateVO.getImage());
                portalPlateVO.setStartTime(project.getStartTime());
                portalPlateVO.setEndTime(project.getEndTime());
            }
            return portalPlateVO;

        }).collect(Collectors.toList());
    }

    /**
     * 获取首页课程
     *
     * @param portalPlateVOList
     * @return
     */
    public List<PortalPlateVO> getCourse(List<PortalPlateVO> portalPlateVOList) {

        LOGGER.info("返回列表" + portalPlateVOList);


        return portalPlateVOList.parallelStream().map(portalPlateVO -> {
            if (portalPlateVO.getThumbnail() == 0) {
                CourseEntityVo course = courseClient.view(portalPlateVO.getId());
                if (course != null) {
                    portalPlateVO.setImage(course.getImage());
                    portalPlateVO.setCourseNo(course.getCode());
                }
            }
            return portalPlateVO;

        }).collect(Collectors.toList());
    }

    /**
     * 格式返回数据
     *
     * @param homeCourseList
     * @return
     */
    public List<PortalPlateVO> getPortalVOS(List<HomePageCoursePageVo> homeCourseList, Long templateId) {

        return homeCourseList.parallelStream().map(coursePageVo -> {
            if (coursePageVo != null) {
                PortalPlateVO portalPlateVO = new PortalPlateVO();
                portalPlateVO.setId(coursePageVo.getCourseId());
                portalPlateVO.setCourseNo(coursePageVo.getCode());
                portalPlateVO.setName(coursePageVo.getName());
                portalPlateVO.setImage(coursePageVo.getImage());
                portalPlateVO.setScore(coursePageVo.getLevel() == null ? "0" : String.valueOf(coursePageVo.getLevel()));
                portalPlateVO.setStudyCount(coursePageVo.getStudyNum() != null ? coursePageVo.getStudyNum() : 0);
                portalPlateVO.setType(SiteEnum.COURSE.getValue());
                portalPlateVO.setValid(coursePageVo.getValid());
                portalPlateVO.setTemplateId(templateId);
                return portalPlateVO;
            } else {
                return null;
            }

        }).collect(Collectors.toList());
    }

    /**
     * 直播列表
     *
     * @param portalPlateVOList
     * @return
     */
    private List<PortalPlateVO> getLive(List<PortalPlateVO> portalPlateVOList) {


        List<PortalPlateVO> portalPlateVOs = portalPlateVOList.parallelStream().map(portalPlateVO -> {
            PortalPlateVO ppVO = new PortalPlateVO();
            //调用直播feign查询直播
            Long liveId = portalPlateVO.getId();
            LiveActivityVO liveVo = liveClient.getLive(liveId);
            ppVO.setId(portalPlateVO.getId());
            ppVO.setType(SiteEnum.LIVE.getValue());
            ppVO.setName(liveVo.getTitle());
            ppVO.setStartTime(liveVo.getStartTime());
            ppVO.setEndTime(liveVo.getEndTime());
            ppVO.setImage(portalPlateVO.getImage());
            ppVO.setDirections(portalPlateVO.getDirections());
            ppVO.setThumbnail(portalPlateVO.getThumbnail());
            //排序
            ppVO.setSort(portalPlateVO.getSort());
            //直播类型
            ppVO.setViewType(liveVo.getViewType());
            //直播号
            ppVO.setCourseNo(liveVo.getChannel());
            ppVO.setCreateByName(liveVo.getAnchor());
            return ppVO;
        }).collect(Collectors.toList());

        return portalPlateVOs;
    }

    /**
     * 微信配置首页的拖拽
     *
     * @param sourceId
     * @param targetId
     * @return
     */
    @ApiOperation(value = "微信配置首页的拖拽")
    @PostMapping("/sortTemplate")
    public Response sortTemplate(
            @ApiParam(name = "sourceId", value = "当前id", required = true) @RequestParam(value = "sourceId", required = true) Long sourceId,
            @ApiParam(name = "targetId", value = "目标id", required = false) @RequestParam(value = "targetId", required = false) Long targetId,
            @ApiParam(name = "type", value = "0：上；1：下", required = false) @RequestParam(value = "targetId", required = false) Integer type
    ) {
        LOGGER.info("sourceId:" + sourceId);
        Boolean flag = false;
        try {
            flag = portalManageFeignClients.sortTemplate(sourceId, targetId, type);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (flag) {
            return Response.ok();
        } else {
            return Response.fail();
        }
    }

    @ApiOperation(value = "微信配置模块上下移动")
    @GetMapping("/transferTemplate")
    public Response transferTemplate(
            @ApiParam(name = "sourceId", value = "当前id", required = true) @RequestParam(value = "sourceId", required = true) Long sourceId,
            @ApiParam(name = "type", value = "0：上；1：下", required = true) @RequestParam(value = "type", required = true) Integer type
    ) {
        Boolean flag = false;
        try {
            flag = portalManageFeignClients.transferTemplate(sourceId, type);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (flag) {
            return Response.ok();
        } else {
            return Response.fail();
        }
    }

    ;

    /**
     * 获取模块的列表
     *
     * @param portalPlateVOS
     * @return
     */
    public List<TemplatePlateVO> getTemplateList(List<PortalPlateVO> portalPlateVOS) {
        List<TemplatePlateVO> templatePlateVOS = new ArrayList<TemplatePlateVO>(8);

        try {
            templatePlateVOS = portalPlateVOS.parallelStream().map(p -> {
                TemplatePlateVO templatePlateVO = new TemplatePlateVO();
                BeanUtils.copyProperties(p, templatePlateVO);
                templatePlateVO.setSort(p.getSort());
                templatePlateVO.setImgPath(p.getImage());
                templatePlateVO.setLinkContentName(p.getName());
                templatePlateVO.setTitle(p.getTitle() != null ? p.getTitle() : "");
                templatePlateVO.setCreateByName(p.getCreateByName() != null ? p.getCreateByName() : "");
                templatePlateVO.setDirections(p.getDirections());
                return templatePlateVO;
            }).collect(Collectors.toList());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return templatePlateVOS;

    }

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


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

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

        return portalPlateVOs;
    }

    /**
     * 获取案例列表
     *
     * @param portalPlateVOList
     * @return
     */
    public List<PortalPlateVO> getCaseList(List<PortalPlateVO> portalPlateVOList) {


        List<PortalPlateVO> portalPlateVOs = portalPlateVOList.parallelStream().map(portalPlateVO -> {
            PortalPlateVO ppVO = new PortalPlateVO();
            StudentCaseStudyVO studentCaseDetails = studentCaseClient.getStudentCaseDetails(portalPlateVO.getId());

            ppVO.setId(portalPlateVO.getId());
            ppVO.setName(studentCaseDetails.getTitle());
            ppVO.setTitle(studentCaseDetails.getTitle() != null ? studentCaseDetails.getTitle() : "");
            ppVO.setImage(studentCaseDetails.getLogoUrl());
            ppVO.setCreateByName(studentCaseDetails.getAuthorName());

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

        return portalPlateVOs;
    }

    /**
     * 智能推荐
     *
     * @param portalPlateVOList
     * @return
     */
    public List<TemplatePlateVO> geDroolList(List<PortalPlateVO> portalPlateVOList) {

        List<Long> ids = portalPlateVOList.parallelStream().map(portalPlateVO -> {
            return portalPlateVO.getId();
        }).collect(Collectors.toList());
        Integer num = portalPlateVOList.get(0).getNum();
        List<TemplatePlateVO> templatePlateVOS = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(ids)) {
            List<BusinessVo4Portal> businessVo4Portals = null;
            try {
                BusinessVo4PortalParam businessVo4PortalParam = new BusinessVo4PortalParam();
                businessVo4PortalParam.setPageNo(1);
                businessVo4PortalParam.setPageSize(num);
                businessVo4PortalParam.setStrategyIds(ids);
                LOGGER.info(" 参数：{}", JSON.toJSON(businessVo4PortalParam));
                BusinessVo4PortalResponse businessVo4PortalResponse = recommendStrategyClient.businessVo4Manage(businessVo4PortalParam);
                LOGGER.info(" 智能推荐返回结果：{}", JSON.toJSON(businessVo4PortalResponse));
                businessVo4Portals = businessVo4PortalResponse.getList();
            } catch (Exception e) {
                LOGGER.info(" 智能推荐返回异常：{}", e.getMessage());
            }
            templatePlateVOS = businessVo4Portals.parallelStream().map(p -> {
                TemplatePlateVO templatePlateVO = new TemplatePlateVO();
                templatePlateVO.setImgPath(p.getImage());
                templatePlateVO.setId(p.getId());
                templatePlateVO.setLinkContentName(p.getName());
                return templatePlateVO;
            }).collect(Collectors.toList());
        }

        return templatePlateVOS;
    }

    public List<TemplatePlateVO> getAlbumList(List<PortalPlateVO> portalPlateVOList) {

        List<Long> ids = portalPlateVOList.parallelStream().map(portalPlateVO -> {
            return portalPlateVO.getId();
        }).collect(Collectors.toList());

        List<TemplatePlateVO> templatePlateVOS = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(ids)) {
            List<ApiListAlbumVo> portalList = albumClient.getPortalList(ids);
            templatePlateVOS = portalList.parallelStream().map(p -> {
                TemplatePlateVO templatePlateVO = new TemplatePlateVO();
                templatePlateVO.setImgPath(p.getImage());
                templatePlateVO.setId(p.getId());
                templatePlateVO.setLinkContentName(p.getName());
                return templatePlateVO;
            }).collect(Collectors.toList());
        }

        return templatePlateVOS;
    }

    /**
     * 获取论模块内容
     *
     * @param portalPlateVOList
     * @return
     */
    public List<TemplatePlateVO> getForum(List<PortalPlateVO> portalPlateVOList) {

        PortalPlateVO portalPlateVO = portalPlateVOList.get(0);
        List<TemplatePlateVO> templatePlateVOS = new ArrayList<>();
        TemplatePlateVO templatePlateVO = new TemplatePlateVO();
        templatePlateVO.setImgPath(portalPlateVO.getImage());
        templatePlateVO.setId(portalPlateVO.getId());
        templatePlateVO.setLinkContentName(portalPlateVO.getName());
        templatePlateVOS.add(templatePlateVO);
        return templatePlateVOS;
    }

    /**
     * 获取专区模块内容
     *
     * @param records
     * @param templatePlateVOS
     * @return
     */
    public List<TemplatePlateVO> getSiteStudent(List<PortalPlateVO> records, List<TemplatePlateVO> templatePlateVOS) {
        if (CollectionUtils.isNotEmpty(records)) {
            //获取实时数据
            List<Long> collect = records.parallelStream().map(a -> a.getActivityId()).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect)) {
                List<SiteVO> siteVOS = remoteSiteClient.selectByIds(collect);
                if (CollectionUtils.isNotEmpty(siteVOS)) {
                    Map<Long, SiteVO> siteVOMap = siteVOS.parallelStream().collect(Collectors.toMap(SiteVO::getId, a -> a));
                    records.forEach(a -> {
                        if (siteVOMap != null) {
                            TemplatePlateVO vo = new TemplatePlateVO();
                            BeanUtils.copyProperties(a, vo);
                            SiteVO siteVO = siteVOMap.get(a.getActivityId());
                            if (siteVO != null) {
                                vo.setImgPath(siteVO.getLogo());
                                vo.setLinkContentName(siteVO.getName());
                                vo.setStatus(siteVO.getEnabled() ? 1 : 0);
                                vo.setDirections(siteVO.getCode());
                                //使用上传图片
                                if (a.getThumbnail() != null && a.getThumbnail() == 1) {
                                    vo.setImgPath(a.getImage());
                                }
                            }
                            templatePlateVOS.add(vo);
                        }
                    });
                }
            }
        }
        return templatePlateVOS;
    }

    /**
     * 获取社群模块内容
     *
     * @param portalPlateVOList
     * @return
     */
    public List<TemplatePlateVO> getCommunity(List<PortalPlateVO> portalPlateVOList) {

        PortalPlateVO portalPlateVO = portalPlateVOList.get(0);
        List<TemplatePlateVO> templatePlateVOS = new ArrayList<>();
        TemplatePlateVO templatePlateVO = new TemplatePlateVO();
        templatePlateVO.setImgPath(portalPlateVO.getImage());
        templatePlateVO.setId(portalPlateVO.getId());
        templatePlateVO.setLinkContentName(portalPlateVO.getName());
        templatePlateVOS.add(templatePlateVO);
        return templatePlateVOS;
    }

    /**
     * 用于启用关闭今日任务
     *
     * @param id
     * @param dispaly
     * @return
     */
    @ApiOperation(value = "用于启用关闭今日任务", response = Boolean.class)
    @GetMapping("/task/update")
    public Response taskPortalUpdate(@ApiParam("从TaskPortalVo取id") @RequestParam("id") Long id,
                                     @ApiParam("1:启用 0：关闭") @RequestParam("dispaly") Integer dispaly) {
        if (dispaly != 1 || dispaly != 0) {
            Response.fail(InternationalEnums.PORTALCONTROLLER.getCode());
        }
        return Response.ok(portalManageFeignClients.taskPortalUpdate(id, dispaly));
    }


}
