package com.yizhi.application.protal.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.plugins.Page;

import com.google.common.collect.Lists;
import com.yizhi.application.Certificate.CertificateUtills.PushCertificateUtil;
import com.yizhi.application.protal.constant.SiteEnum;
import com.yizhi.application.protal.constant.TerminalEnum;
import com.yizhi.application.vo.PortalHomeSearchOtherVO;
import com.yizhi.assignment.application.feign.AssignmentStudentClient;
import com.yizhi.assignment.application.vo.entity.Assignment;
import com.yizhi.certificate.application.feign.CertificateClient;
import com.yizhi.certificate.application.vo.domain.CertificateVo;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.core.application.task.AbstractTaskHandler;
import com.yizhi.core.application.task.TaskExecutor;
import com.yizhi.course.application.feign.CourseClient;
import com.yizhi.course.application.vo.ApiSeachCourseVo;
import com.yizhi.course.application.vo.CourseDetailsVo;
import com.yizhi.course.application.vo.CourseVo;
import com.yizhi.course.application.vo.HomePageCoursePageVo;
import com.yizhi.course.application.vo.domain.CourseEntityVo;
import com.yizhi.exam.application.feign.ExamClient;
import com.yizhi.exam.application.vo.domain.Exam;
import com.yizhi.live.application.feign.LiveActivityClient;
import com.yizhi.live.application.vo.LiveActivityResultVO;
import com.yizhi.live.application.vo.LiveActivityVO;
import com.yizhi.research.application.feign.ResearchClient;
import com.yizhi.research.application.vo.domain.ResearchVo;
import com.yizhi.site.application.feign.ClassifyManageFeignClients;
import com.yizhi.site.application.feign.InformationManageFeignClients;
import com.yizhi.site.application.feign.PortalManageFeignClients;
import com.yizhi.site.application.feign.api.EventTrackApiClients;
import com.yizhi.site.application.feign.api.PortalApiFeignClients;
import com.yizhi.site.application.feign.api.PortalBlockFeignClients;
import com.yizhi.site.application.vo.domain.*;
import com.yizhi.site.application.vo.site.*;
import com.yizhi.system.application.feign.DictionaryFeignClients;
import com.yizhi.system.application.system.remote.CompanyClient;
import com.yizhi.system.application.system.remote.OrganizationClient;
import com.yizhi.system.application.system.remote.SiteClient;
import com.yizhi.system.application.vo.CompanyVO;
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.model.BaseModel;
import com.yizhi.training.application.vo.api.TrainingProjectListVo;
import com.yizhi.training.application.vo.domain.TrainingProjectVo;
import com.yizhi.training.application.vo.manage.TpPlanActivityVo;
import com.yizhi.util.application.constant.ReturnCode;
import com.yizhi.util.application.date.DateUtil;
import com.yizhi.util.application.domain.Response;
import com.yizhi.util.application.enums.i18n.Constants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

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

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

    @Autowired
    private PortalApiFeignClients portalApi;
    @Autowired
    private TrainingProjectClient projectClient;
    @Autowired
    private TpPlanActivityClient projectActivityClient;
    @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 CompanyClient companyClient;
    @Autowired
    private SiteClient siteClient;
    @Autowired
    PortalBlockFeignClients portalBlockClients;
    @Autowired
    private PortalManageFeignClients portalManageFeignClients;

    @Autowired
    LiveActivityClient liveActivityClient;

    @Autowired
    OrganizationClient organizationClient;
    @Autowired
    private PushCertificateUtil pushCertificateUtil;
    @Autowired
    private ClassifyManageFeignClients classifyManageFeignClients;
    @Autowired
    private InformationManageFeignClients informationManageFeignClients;
    @Autowired
    private EventTrackApiClients eventTrackApiClients;

    @Autowired
    private DictionaryFeignClients dictionaryFeignClients;
    @Autowired
    private TaskExecutor taskExecutor;

    @ApiOperation(value = "获取登陆页面", notes = "获取登陆页面", response = PortalHomeOtherVO.class)
    @GetMapping("/public/login/view")
    public Response<String> loginPageView(@ApiParam(name = "companyCode", value = "公司编码", required = true) String companyCode,
                                          @ApiParam(name = "siteCode", value = "站点编码", required = true) String siteCode,
                                          @ApiParam(name = "type", value = "站点类型", required = true) Integer type) {
        if (companyCode == null || siteCode == null || type == null) {
            return Response.fail("公司和站点错误");
        }
        CompanyVO findByCode = null;
        try {
            findByCode = companyClient.findByCode(companyCode);
        } catch (Exception e) {
            LOG.error("获取公司信息失败:" + e.getMessage());
        }
        if (findByCode == null) {
            return Response.fail("该公司不存在");
        }
        Long companyId = findByCode.getId();
//		Long companyId = 0L;
        SiteVO findByName = null;
        try {
            findByName = siteClient.findByName(siteCode, companyId);
        } catch (Exception e) {
            LOG.error("获取站点信息失败:" + e.getMessage());
        }
        if (findByName == null) {
            return Response.fail("该站点不存在");
        }
        Long siteId = findByName.getId();
//		Long siteId = 0L;
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("bgimgPath", "");
        retMap.put("loginNameDesc", "");
        retMap.put("loginPwdDesc", "");
        PortalLoginVo loginPageView = portalApi.loginPageView(siteId, type);
        if (loginPageView != null) {
            retMap.put("bgimgPath", loginPageView.getBgimgPath());
            retMap.put("loginNameDesc", loginPageView.getLoginNameDesc());
            retMap.put("loginPwdDesc", loginPageView.getLoginPwdDesc());
        }

        return Response.ok(retMap);
    }

    @ApiOperation(value = "app底部菜单栏", notes = "app底部菜单栏", response = PortalBlockVO.class)
    @GetMapping("/bottomMenu/list")
    public Response<PortalBlockVO> listBottomMenu(@ApiParam(name = "terminalName", value = "终端名称, PC：PC; APP： MOBILE; 微信: WECHAT", required = true)
                                                  @RequestParam String terminalName) {
        String terminalKey = TerminalEnum.getTerminalKey(terminalName);
        if (StringUtils.isBlank(terminalKey)) {
            return Response.fail("终端名称错误");
        }
        RequestContext context = ContextHolder.get();
        HomeTerminalVo htvo = new HomeTerminalVo();
        htvo.setContext(context);
        htvo.setTerminalName(terminalKey);
        Long terminalId = portalApi.getTerminalId(htvo);
        if (terminalId == null) {
            return Response.fail("该终端还未启动配置");
        }
        return Response.ok(portalBlockClients.getByTerminalId(terminalId, 1, context.getAccountId(), context.getAccountName()));
    }

    @ApiOperation(value = "首页除模板外的所有信息", notes = "首页除模板外的所有信息", response = PortalHomeOtherVO.class)
    @GetMapping("/home/other/list")
    public Response<PortalHomeOtherVO> listHomeOther(
            @ApiParam(name = "terminalName", value = "终端名称, PC：PC; APP： MOBILE; 微信: WECHAT", required = true) String terminalName) {
        try {
            String terminalKey = TerminalEnum.getTerminalKey(terminalName);
            if (StringUtils.isBlank(terminalKey)) {
                return Response.fail("终端名称错误");
            }
            RequestContext context = ContextHolder.get();
            HomeTerminalVo htvo = new HomeTerminalVo();
            htvo.setContext(context);
            htvo.setTerminalName(terminalKey);
            PortalHomeOtherVO vo = portalApi.listHomeOther(htvo);

            taskExecutor.asynExecute(new AbstractTaskHandler() {
                @Override
                public void handle() {
                    LOG.info("************ 小程序首页打开 记录埋点:{}", context.getAccountId());
                    // if(request.getHeader("Cookie")!=null&&Objects.equals(redisCache.get(request.getHeader("Cookie").replace("JSESSIONID=","")),"2")){
                    eventTrackApiClients.addEvent("open_index", context.getAccountId());
                    //  }
                }
            });

            return Response.ok(vo);
        } catch (Exception e) {
            LOG.error("门户logo:", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

    @ApiOperation(value = "首页搜索接口", notes = "首页搜索接口", response = PortalHomeSearchOtherVO.class)
    @GetMapping("/home/other/search")
    public Response<PortalHomeSearchOtherVO> listHomeSearch(
            @ApiParam(name = "searchName", required = true) String searchName) {
        try {
            SiteComponyIdVO siteComponyIdVO = new SiteComponyIdVO();
            siteComponyIdVO.setCompanyId(ContextHolder.get().getCompanyId());
            siteComponyIdVO.setSiteId(ContextHolder.get().getSiteId());
            siteComponyIdVO.setCreateById(ContextHolder.get().getAccountId());
            siteComponyIdVO.setCreateByName(ContextHolder.get().getAccountName());
            siteComponyIdVO.setOrgId(ContextHolder.get().getOrgId());
            siteComponyIdVO.setSiteId(ContextHolder.get().getSiteId());
            PortalHomeSearchOtherVO vo = new PortalHomeSearchOtherVO();
            List<ClassificationVO>  classificationVOList = classifyManageFeignClients.getClassification(siteComponyIdVO);
            List<InformationVo>  informationVoList = informationManageFeignClients.listbyName(searchName,ContextHolder.get().getSiteId());
            if(CollectionUtil.isNotEmpty(informationVoList)&&CollectionUtil.isNotEmpty(classificationVOList)){
                List<Long> classNameList = informationVoList.stream().map(InformationVo::getTypeOne).collect(Collectors.toList());
                vo.setClassificationVOList(classificationVOList.stream().filter(c->classNameList.contains(c.getId())).collect(Collectors.toList()));
                vo.getClassificationVOList().stream().forEach(classificationVO -> {
                    //classificationVO.getData().forEach(typeTwo->{
                        classificationVO.setInformationVoList(informationVoList.stream().filter(informationVo -> Objects.equals(informationVo.getTypeOne(),classificationVO.getId())).collect(Collectors.toList()));
                    //});
                });
                classificationVOList = classificationVOList.stream().filter(c->!classNameList.contains(c.getId())).collect(Collectors.toList());
            }
            RequestContext context = ContextHolder.get();
            List<ClassificationVO>  classificationVONewList = Lists.newArrayList();
            if(CollectionUtil.isNotEmpty(classificationVOList)){
                classificationVOList.stream().forEach(classificationVO -> {
                    //classificationVO.getData().forEach(typeTwo->{
                        if(classificationVO.getName().indexOf(searchName)>=0){
                            InfomationParamReleaseVO releaseVO =new InfomationParamReleaseVO();
                            releaseVO.setCompanyCode(context.getCompanyCode());
                            releaseVO.setCompanyId(context.getCompanyId());
                            releaseVO.setSiteCode(context.getSiteCode());
                            releaseVO.setSiteId(context.getSiteId());
                            releaseVO.setAccountId(context.getAccountId());
                            releaseVO.setAdmin(context.isAdmin());
                            releaseVO.setOrgId(context.getOrgId());
                            releaseVO.setOrgIds(context.getOrgIds());
                            releaseVO.setOrgName(context.getOrgName());
                            releaseVO.setTypeId(classificationVO.getId());
                            releaseVO.setTypeTwoId(classificationVO.getId());
                            Page<InformationVo> page = informationManageFeignClients.releaseList(releaseVO);
                            classificationVO.setInformationVoList(page!=null?page.getRecords():Lists.newArrayList());

                            ClassificationVO classification = new ClassificationVO();
                            BeanUtil.copyProperties(classificationVO,classification);
                            if(CollectionUtil.isNotEmpty(classificationVONewList)){
                                Optional<ClassificationVO> optionalClassificationVO = classificationVONewList.stream().filter(c->Objects.equals(c.getId(),classificationVO.getId())).findFirst();
                                if(optionalClassificationVO!=null&&optionalClassificationVO.isPresent()){
                                    classification = optionalClassificationVO.get();
                                    if(CollectionUtil.isEmpty(vo.getClassificationVOList())){
                                        vo.setClassificationVOList(Lists.newArrayList());
                                    }
                                    vo.getClassificationVOList().add(classification);
                                }
                            }
                        }
                    //});
                });
            }
            dictionaryFeignClients.insertBySearchName(searchName);
           return Response.ok(vo);
        } catch (Exception e) {
            LOG.error("首页搜索接口:", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

    @ApiOperation(value = "首页历史接口", notes = "首页历史接口", response = PortalHomeSearchOtherVO.class)
    @GetMapping("/home/other/history")
    public Response<PortalHomeSearchOtherVO> listHomeHistory() {
        try {
            PortalHomeSearchOtherVO vo = new PortalHomeSearchOtherVO();
            List<EventTrackVo> eventTrackVoList = eventTrackApiClients.queryListByType(6,ContextHolder.get().getAccountId());
            List<ClassificationVO>  classificationVOList = Lists.newArrayList();
            String toDay = DateUtil.format(new Date(),"yyyy-MM-dd");
            if(CollectionUtil.isNotEmpty(eventTrackVoList)){
                eventTrackVoList.stream().forEach(e->{
                    e.setRemark1(DateUtil.format(e.getCreateTime(),"yyyy-MM-dd"));

                });
                List<String> dateList = eventTrackVoList.stream().map(EventTrackVo::getRemark1).distinct().collect(Collectors.toList());
                dateList.stream().forEach(d->{
                    ClassificationVO classificationVO = new ClassificationVO();
                    List<Long> idList = eventTrackVoList.stream().filter(e->Objects.equals(e.getRemark1(),d)).map(EventTrackVo::getBusinessId).distinct().collect(Collectors.toList());
                    Date createTime = DateUtil.parse(d,"yyyy-MM-dd");
                    String name = "";
                    if(Objects.equals(toDay,d)){
                        name = "今天";
                    }else{
                        name = DateUtil.format(createTime,"MM-dd");
                    }
                     name = name+"   浏览"+idList.size()+"条内容";
                    classificationVO.setName(name);
                    classificationVO.setCreateTime(createTime);
                    classificationVO.setInformationVoList(informationManageFeignClients.listbyIds(idList));
                    classificationVOList.add(classificationVO);
                });
                vo.setClassificationVOList(classificationVOList);
            }
            return Response.ok(vo);
        } catch (Exception e) {
            LOG.error("首页历史接口:", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

    @ApiOperation(value = "门户模板信息", notes = "门户模板信息", response = TemplateListVO.class)
    @GetMapping("/home/template/list")
    public Response<List<ApiTemplateListVO>> listHomeTemplate(
            @ApiParam(name = "terminalName", value = "终端名称, PC：PC; APP： MOBILE; 微信: WECHAT", required = true) @RequestParam("terminalName") String terminalName) {
        try {

            // 1 假数据  2 feign 接口数据
            String terminalKey = TerminalEnum.getTerminalKey(terminalName);
            if (StringUtils.isBlank(terminalKey)) {
                return Response.fail("终端名称错误");
            }
            RequestContext context = ContextHolder.get();
            LOG.info("打印content："+context);
            Long accountId = context.getAccountId();
            HomeTerminalVo htvo = new HomeTerminalVo();
            htvo.setContext(context);
            htvo.setTerminalName(terminalKey);

//			--------------我的培训-----------------------------   
            List<MyProjectAndCourseVO> myProjectList = null;
            //我的培训
            if (context.getRelationIds() != null) {
                Page page = new Page(1, Integer.MAX_VALUE);
                BaseModel<Page> model = new BaseModel<Page>();
                model.setContext(context);
                model.setObj(page);
                LOG.info("model param :{}",model);
                Page<TrainingProjectVo> apiMyPageList = null;
                try {
                    apiMyPageList = projectClient.apiPageListNoCondition(model);

                    LOG.info("apiMyPageList:{}",apiMyPageList);
                    LOG.info("apiMyPageListRecords:{}",apiMyPageList.getRecords());
                } catch (Exception e) {
                    LOG.error("我的培训异常:" + e);
                }
                if (apiMyPageList != null) {
                    List<TrainingProjectVo> trainList = apiMyPageList.getRecords();
                    if (trainList.size() > 2) {
                        myProjectList = formatProjectList(trainList);
                    }
                }
            }
//			--------------我的课程------------------------------------------
            // 可见范围
            List<Long> courseIds = new ArrayList<>();
            try {
                courseIds = courseClient.findCourseList(0,16);
            } catch (Exception e) {
                LOG.info("获取可见范围异常"+e.getLocalizedMessage());
            }



            List<ApiTemplateListVO> list = new ArrayList<ApiTemplateListVO>();
            List<ApiTemplateMiddlerVO> voList = portalApi.listHomeTemplate(htvo);
            if (voList == null || voList.size() == 0) {
                return Response.ok();
            }

            List<ApiFeatureVO> featureList = null;
            List<MyProjectAndCourseVO> projectList = null;
            List<MyProjectAndCourseVO> courseList = null;
            List<MyProjectAndCourseVO> liveList = null;
            MyProjectAndCourseVO setVo = null;
            List<Long> homeCourseIds = new ArrayList<>();
            for (ApiTemplateMiddlerVO vo : voList) {
                PortalTemplateVo pt = vo.getPortalTemplate();
                List<TemplateNewsVO> newsList = vo.getNewsList();
                List<PopCourseListVO> popularCourseList = vo.getPopularCourseList();
                List<ProtalPlateVo> ppList = vo.getPpList();
                LOG.info("ppList 的结果是:" + ppList);
                // 类型
                Integer moduleType = pt.getModuleType();
                ApiTemplateListVO avo = new ApiTemplateListVO();
                BeanUtils.copyProperties(pt, avo, "createTime", "createById", "createByName", "updateTime", "updateById", "updateByName");
                featureList = new ArrayList<ApiFeatureVO>();
                projectList = new ArrayList<MyProjectAndCourseVO>();
                courseList = new ArrayList<MyProjectAndCourseVO>();


                for (ProtalPlateVo pp : ppList) {
                    if (moduleType == 1) {
                        // 项目活动id
                        Long reId = pp.getLinkContent();
                        if (reId == null) {
                            continue;
                        }
                        if (pp.getIsRecommend() == 0) {
                            continue;
                        }
                        // 根据项目活动id获取 相关对应信息
                        ApiFeatureVO fvo = new ApiFeatureVO();

                        com.yizhi.training.application.vo.domain.TpPlanActivityVo activity = null;
                        try {
                             activity = projectActivityClient.getOne(reId);
                        } catch (Exception e) {
                            LOG.error("培训异常:" + e.getLocalizedMessage());
                        }
                        if (activity == null) {
                            continue;
                        }
                        if (activity.getDeleted() == 1) {
                            continue;
                        }
                        TpPlanActivityVo manageActivityVo = new TpPlanActivityVo();
                        BeanUtils.copyProperties(activity,manageActivityVo);
                        fvo = formatActivity(fvo, manageActivityVo, context, pp);
                        featureList.add(fvo);
                    } else if (moduleType == 2) {
                        // 培训
                        if (myProjectList == null || myProjectList.size() < 3) {
                            //少于三个则此模块不显示
                            continue;
                        }
                        TrainingProjectVo one = null;

                        if (pp.getLinkContent() == null) {
                            continue;
                        }
                        try {
                            one = projectClient.getOne(pp.getLinkContent());
                            if (one == null) {
                                continue;
                            }
                            if (one.getDeleted() == 1) {
                                continue;
                            }
                            setVo = new MyProjectAndCourseVO();
                            setVo.setImgPath(pp.getImgPath());
                            setVo.setTitle(one.getName());
                            setVo.setContent(pp.getDirections());
                            setVo.setStartTime(one.getStartTime());
                            setVo.setEndTime(one.getEndTime());
                            setVo.setRelaId(pp.getLinkContent());
                            setVo.setKind(SiteEnum.DETAIL.getValue());
                            setVo.setType(SiteEnum.TRAIN.getValue());
                            for (MyProjectAndCourseVO myProjectAndCourseVO : myProjectList) {
                                if (myProjectAndCourseVO.getRelaId().equals(setVo.getRelaId())) {
                                    projectList.add(setVo);
                                    myProjectList.remove(myProjectAndCourseVO);
                                    continue;
                                }
                            }
                        } catch (Exception e) {
                            LOG.error("培训异常:" + e.getLocalizedMessage());
                        }
                    } else if (moduleType == 3) {
                        if (pp.getLinkContent() != null&&courseIds.contains(pp.getLinkContent())){
                            // 把可见范围的id 放到初始化的课程列表中
                            homeCourseIds.add(pp.getLinkContent());
                        }
                    } else if (moduleType == 5) {
                        //直播
                        liveList = new ArrayList<MyProjectAndCourseVO>();
                        setVo = new MyProjectAndCourseVO();

                        LiveActivityVO live = null;
                        try {
                                LiveActivityResultVO liveActivity = liveClient.get(pp.getLinkContent());
                                live = liveActivity.getLiveActivity();

                                setVo.setContent(pp.getDirections());
                                setVo.setTitle(live.getTitle());
                                setVo.setAuthor(live.getAnchor());
                                setVo.setScore(live.getScope().toString());
                                setVo.setStartTime(live.getStartTime());
                                setVo.setEndTime(live.getEndTime());
                                setVo.setRelaId(pp.getLinkContent());
                                setVo.setImgPath(pp.getImgPath());
                                setVo.setKind(SiteEnum.DETAIL.getValue());
                                setVo.setType(SiteEnum.LIVE.getValue());
                                setVo.setChannel(live.getChannel());
                                liveList.add(setVo);
                        } catch (Exception e) {
                            LOG.error("直播异常:" + e);
                        }
                        if (live == null) {
                            continue;
                        }
                    }
                }

                if (moduleType == 1) {
                    avo.setFeatureList(featureList);
                    avo.setImageUrl(pt.getIcon());
                } else if (moduleType == 2) {
                    if (myProjectList != null) {
                        //添加我的培训
                        projectList.addAll(myProjectList);
                    }
                    avo.setProjectList(projectList);
                    avo.setImageUrl(pt.getIcon());
                } else if (moduleType == 3) {

                    List<MyProjectAndCourseVO> myCourseList = new ArrayList<>();
                    Integer size = homeCourseIds.size();
                    if (CollectionUtils.isNotEmpty(homeCourseIds)) {
                        if (size>=8){
                            //获取8个课程的列表
                            homeCourseIds.subList(0,8);
                            myCourseList = formatCourseList(courseClient.findHomeCourseList(homeCourseIds));

                        } else {
                            List<Long> courseIdList = null;
                            int courseIdSize = courseIds.size();
                            if(courseIdSize >= 16){
                            	courseIdList =courseIds.subList(0,16);
                            } else {
                            	courseIdList =courseIds.subList(0,courseIdSize);
                            }

                            homeCourseIds.addAll(courseIdList);
                            Integer maxNum=8;
							List list1 = removeDuplicateWithOrder(homeCourseIds);
							if (list1.size() < 8) {
								maxNum = list1.size();
							}
                            myCourseList = formatCourseList(courseClient.findHomeCourseList(list1.subList(0,maxNum)));
                        }
                    } else {

                        //我的课程
                        if (context.getRelationIds() != null) {
                            ApiSeachCourseVo ascvo = new ApiSeachCourseVo();
                            ascvo.setAccountId(context.getAccountId());
                            ascvo.setCompanyId(context.getCompanyId());
                            ascvo.setSiteId(context.getSiteId());
                            ascvo.setPageNo(1);
                            ascvo.setPageSize(8);
                            ascvo.setIds(context.getRelationIds());
                            List<HomePageCoursePageVo> hotCourseList = null;
                            try {
                                hotCourseList = courseClient.getCourseList(ascvo);
                            } catch (Exception e) {
                                LOG.error("我的课程异常:" + e.getLocalizedMessage());
                            }
                            if ( CollectionUtils.isNotEmpty(hotCourseList)) {
                                myCourseList = formatCourseList(hotCourseList);
                            }
                        }
                    }
                    avo.setCourseList(myCourseList);
                    avo.setPopularCourseList(popularCourseList);
                    avo.setImageUrl(pt.getIcon());
                } else if (moduleType == 4) {
                    avo.setNewsList(newsList);
                    avo.setImageUrl(pt.getIcon());
                } else if (moduleType == 5) {
                    avo.setLiveList(liveList);
                    avo.setImageUrl(pt.getIcon());
                }
                list.add(avo);
            }
            return Response.ok(list);
        } catch (Exception e) {
            LOG.error("门户导航栏:", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

    //项目活动 数据格式化
    private ApiFeatureVO formatActivity(ApiFeatureVO fvo, TpPlanActivityVo activity, RequestContext context, ProtalPlateVo pp) {
//		type   活动类型： 0课程 1考试 2调研 3直播 4投票 5作业 6证书 7外部链接
        Integer type = activity.getType();
        Long relationId = activity.getRelationId();
        if (type == 0) {
            LOG.info("获取课程信息开始");
            fvo.setImgPath(pp.getImgPath());
            fvo.setKind(SiteEnum.DETAIL.getValue());
            fvo.setType(SiteEnum.COURSE.getValue());

            CourseDetailsVo courseDetailsVo = null;
            try {
                courseDetailsVo = courseClient.get(relationId, context.getAccountId());
                // 自动发放证书（异步调用）
                CourseVo courseVo = courseDetailsVo.getCourseVo();
                if(Boolean.TRUE.equals(courseVo.getGrantCertificate()) && courseDetailsVo.getStudentStatus().intValue()==1){
                    // Arrays.asList() 数组转list
                    String[] certificateStr = courseVo.getCertificateStr().split(",");
                    List<Long> cIds = new ArrayList<>();
                    for(String str:certificateStr){
                        cIds.add(Long.valueOf(str));
                    }
                    pushCertificateUtil.pushCertificate(1,courseVo.getId(),courseVo.getName(),cIds);
                }
            } catch (Exception e) {
                LOG.info("课程异常:" + e);
            }
            if (courseDetailsVo == null) {
                LOG.info("获取不到{}的培训活动({relationId})的关联课程明细信息", context.getAccountId(), relationId);
                return fvo;
            }
            CourseVo courseVo = courseDetailsVo.getCourseVo();
            if (courseVo == null) {
                LOG.info("获取不到{}的培训活动({relationId})的关联课程信息", context.getAccountId(), relationId);
                return fvo;
            }
            fvo.setRelaId(courseVo.getId());
            fvo.setTitle(courseVo.getName());

        } else if (type == 1) {
            Exam exam = null;
            try {
                exam = examClient.selectExamById(relationId);
            } catch (Exception e) {
                LOG.error("考试异常:" + e);
            }
            if (exam != null) {
                fvo.setRelaId(exam.getId());
                fvo.setTitle(exam.getName());
                fvo.setImgPath(pp.getImgPath());
                fvo.setKind(SiteEnum.DETAIL.getValue());
                fvo.setType(SiteEnum.EXAM.getValue());
            }
        } else if (type == 2) {
            ResearchVo research = null;
            try {
                research = researchClient.viewOne(relationId);
            } catch (Exception e) {
                LOG.error("调研异常:" + e);
            }
            if (research != null) {
                fvo.setRelaId(research.getId());
                fvo.setTitle(research.getName());
                fvo.setImgPath(pp.getImgPath());
                fvo.setKind(SiteEnum.DETAIL.getValue());
                fvo.setType(SiteEnum.SURVEY.getValue());
            }
        } else if (type == 3) {
            LiveActivityVO live = null;
            try {
                LiveActivityResultVO liveActivity = liveClient.get(pp.getLinkContent());
                live = liveActivity.getLiveActivity();
            } catch (Exception e) {
                LOG.error("直播异常:" + e);
            }
            if (live != null) {
                fvo.setRelaId(live.getId());
                fvo.setTitle(live.getTitle());
                fvo.setImgPath(pp.getImgPath());
                fvo.setKind(SiteEnum.DETAIL.getValue());
                fvo.setType(SiteEnum.LIVE.getValue());
            }
        } else if (type == 4) {
//            VoteVO vote = null;
//            try {
//                vote = voteClient.viewVote(String.valueOf(relationId));
//            } catch (Exception e) {
//                LOG.error("投票异常:" + e);
//            }
//            if (vote != null) {
//                fvo.setRelaId(vote.getId());
//                fvo.setTitle(vote.getVoteName());
//                fvo.setImgPath(pp.getImgPath());
//                fvo.setLinkUrl(vote.getLinkUrl());
//                fvo.setKind(SiteEnum.DETAIL.getValue());
//                fvo.setType(SiteEnum.VOTE.getValue());
//            }
        } else if (type == 5) {
            Assignment assignment = null;
            try {
                assignment = assignmentClient.toAssignmentActivity(relationId);
            } catch (Exception e) {
                LOG.error("作业异常:" + e);
            }
            if (assignment != null) {
                fvo.setRelaId(assignment.getId());
                fvo.setTitle(assignment.getName());
                fvo.setImgPath(pp.getImgPath());
                fvo.setKind(SiteEnum.DETAIL.getValue());
                fvo.setType(SiteEnum.HOMEWORK.getValue());
            }
        } else if (type == 6) {
            CertificateVo certificate = null;
            try {
                certificate = certificateClient.getCertificate(relationId);
            } catch (Exception e) {
                LOG.error("证书异常:" + e);
            }
            if (certificate != null) {
                fvo.setRelaId(certificate.getId());
                fvo.setTitle(certificate.getTitle());
                fvo.setImgPath(pp.getImgPath());
                fvo.setKind(SiteEnum.DETAIL.getValue());
                fvo.setType(SiteEnum.CERTIFICATE.getValue());
            }
        } else if (type == 7) {
            fvo.setTitle(activity.getName());
            fvo.setImgPath(pp.getImgPath());
            fvo.setLinkUrl(activity.getAddress());
            fvo.setKind(SiteEnum.DETAIL.getValue());
            fvo.setType(SiteEnum.OUTERCHAIN.getValue());
        }
        else if (type == 11) {
            CourseEntityVo course = null;
            try {
            	course = courseClient.view(relationId);
            } catch (Exception e) {
                LOG.error("营销课程异常:" + e);
            }
            if (course != null) {
                fvo.setRelaId(course.getId());
                fvo.setTitle(course.getName());
                fvo.setImgPath(pp.getImgPath());
                fvo.setKind(SiteEnum.DETAIL.getValue());
                fvo.setType(SiteEnum.MARKET.getValue());
            }
        }
        else if (type == 12) {
        	TrainingProjectVo training = null;
            try {
            	training = projectClient.getOne(relationId);
            } catch (Exception e) {
                LOG.error("培训项目异常:" + e);
            }
            if (training != null) {
                fvo.setRelaId(training.getId());
                fvo.setTitle(training.getName());
                fvo.setImgPath(pp.getImgPath());
                fvo.setKind(SiteEnum.DETAIL.getValue());
                fvo.setType(SiteEnum.CERTIFICATE.getValue());
            }
        }
        return fvo;
    }


    public List<MyProjectAndCourseVO> formateProject(List<TrainingProjectListVo> myProjectList) {
        List<MyProjectAndCourseVO> list = new ArrayList<MyProjectAndCourseVO>();
        MyProjectAndCourseVO vo = null;
        for (TrainingProjectListVo tvo : myProjectList) {
            vo = new MyProjectAndCourseVO();
            vo.setRelaId(tvo.getId());
            vo.setTitle(tvo.getName());
            vo.setImgPath(tvo.getLogoImg());
            vo.setStartTime(tvo.getStartTime());
            vo.setEndTime(tvo.getEndTime());
            vo.setKind(SiteEnum.DETAIL.getValue());
            vo.setType(SiteEnum.TRAIN.getValue());
            list.add(vo);
        }
        return list;
    }


    public List<MyProjectAndCourseVO> formatProjectList(List<TrainingProjectVo> trainList) {
        List<MyProjectAndCourseVO> list = new ArrayList<MyProjectAndCourseVO>();
        MyProjectAndCourseVO vo = null;
        for (TrainingProjectVo tp : trainList) {
            vo = new MyProjectAndCourseVO();
            vo.setRelaId(tp.getId());
            vo.setImgPath(tp.getLogoImg());
            vo.setTitle(tp.getName());
            vo.setContent(tp.getDescription());
            vo.setStartTime(tp.getStartTime());
            vo.setEndTime(tp.getEndTime());
            vo.setKind(SiteEnum.DETAIL.getValue());
            vo.setType(SiteEnum.TRAIN.getValue());
            list.add(vo);
        }
        return list;
    }

    public List<MyProjectAndCourseVO> formatCourseList(List<HomePageCoursePageVo> hotCourseList) {
        List<MyProjectAndCourseVO> list = new ArrayList<MyProjectAndCourseVO>();
        MyProjectAndCourseVO vo = null;
        for (HomePageCoursePageVo hp : hotCourseList) {
            vo = new MyProjectAndCourseVO();
            vo.setRelaId(hp.getCourseId());
            vo.setImgPath(hp.getImage());
            vo.setTitle(hp.getName());
            vo.setAuthor(hp.getAuthorUnit());
            if (hp.getLevel() == null) {
                vo.setScore("0");
            } else {
                vo.setScore(String.valueOf(hp.getLevel()));
            }
//            vo.setStudyNum(hp.getStudyNum().longValue());
//            vo.setViewCount(hp.getViewCount());
			vo.setStudyNum(hp.getStudyNum()!=null?hp.getStudyNum().longValue():0);
//            vo.setStudyNum(hp.getViewCount().longValue());
//			vo.setStartTime(hp.getStartTime());
            vo.setKind(SiteEnum.DETAIL.getValue());
            vo.setType(SiteEnum.COURSE.getValue());
            // 课程有效字段
            vo.setValid(hp.getValid());
            list.add(vo);
        }
        return list;
    }

    /**
     *  去重课程
     * 删除ArrayList中重复元素，保持顺序
     * @return
     */
    public static List removeDuplicateWithOrder(List list) {
        Set set = new HashSet();
        List newList = new ArrayList();
        for (Iterator iter = list.iterator(); iter.hasNext();) {
            Object element = iter.next();
            if (set.add(element)){
                newList.add(element);
            }
        }
        list.clear();
        list.addAll(newList);
        return list;
    }

    /**
     * 用于微信端  是否展示今日任务模块
     * @return
     */
    @GetMapping("/task/get")
    @ApiOperation(value = "获取今日任务模块数据",  response = TaskPortalVo.class)
    public Response<TaskPortalVo> getTaskPortal(){
        return Response.ok(portalManageFeignClients.getTaskPortal());
    }
    
    @GetMapping("/getReport")
    @ApiOperation(value = "获取首页配置的平台报告",response = RelationReportVo.class)
    public Response<RelationReportVo> getReport(@ApiParam(name = "terminalType",value = "终端类型 1PC 2APP 3移动")@RequestParam("terminalType") Integer terminalType) {
    	try {
			RelationReportVo report = portalApi.getReport(terminalType);
			return Response.ok(report);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Response.fail(Constants.MSG_BIZ_FAIL);
		}
    }
}
