package com.yizhi.application.protal.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.yizhi.album.application.feign.AlbumClient;
import com.yizhi.album.application.vo.domain.Album;
import com.yizhi.assignment.application.feign.AssignmentClient;
import com.yizhi.assignment.application.vo.AssignmentSelectVo;
import com.yizhi.certificate.application.feign.CertificateClient;
import com.yizhi.certificate.application.vo.domain.CertificateVo;
import com.yizhi.core.application.cache.CacheNamespace;
import com.yizhi.core.application.cache.RedisCache;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.course.application.feign.CourseClient;
import com.yizhi.course.application.feign.CoursePcClient;
import com.yizhi.course.application.feign.OfflineCourseClient;
import com.yizhi.course.application.vo.CourseStudentStatusVO;
import com.yizhi.course.application.vo.OfflineCourseVo;
import com.yizhi.course.application.vo.domain.CourseEntityVo;
import com.yizhi.exam.application.feign.ExamClient;
import com.yizhi.exam.application.vo.ExamViewVO;
import com.yizhi.forum.application.feign.remote.RemotePostsClient;
import com.yizhi.live.application.feign.LiveActivityClient;
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.sign.application.feign.SignManageClient;
import com.yizhi.site.application.feign.PortalManagePCFeignClients;
import com.yizhi.site.application.feign.api.PortalApiPCFeignClients;
import com.yizhi.site.application.vo.domain.ProtalPlateVo;
import com.yizhi.site.application.vo.domain.RelationLinkVo;
import com.yizhi.site.application.vo.site.ModuleAllVO;
import com.yizhi.site.application.vo.site.PortalPlateVO;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
//import com.yizhi.application.vo.VoteVO;


@Component
public class PortalUtil {


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

    @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 AlbumClient albumClient;
    @Autowired
    private RemotePostsClient postClient;
    @Autowired
    private SiteClient remoteSiteClient;
    @Autowired
    private RedisCache redisCache;
    private final static Long EXPIRE_TIME = 60 * 1L;


    /**
     * 获取推荐
     *
     * @param mId
     * @param type
     * @param thumbnail
     * @param imgUrl
     * @return
     */
    public ModuleAllVO getRecommend(Long mId, Integer type, Integer thumbnail, String imgUrl, List<RelationLinkVo> listRelationLink) {
        ModuleAllVO mv = new ModuleAllVO();
        switch (type) {
            case 0:
                System.out.println(mId);
                mv = getCourse(mId, type, thumbnail, imgUrl);
                break;
            case 1:
                mv = getExam(mId, type, thumbnail, imgUrl, listRelationLink);
                break;
            case 2:
                mv = getResearch(mId, type, thumbnail, imgUrl, listRelationLink);
                break;
            case 3:
                mv = getLive(mId, type, thumbnail, imgUrl);
                break;
            case 4:
//                   mv=getVote(mId, type, thumbnail, imgUrl);
                break;
            case 5:
                mv = getAssignment(mId, type, thumbnail, imgUrl, listRelationLink);
                break;
            case 6:
                mv = getCertificate(mId, type, thumbnail, imgUrl);
                break;
            case 7:
                mv = getTpPlanActivity(mId, type, thumbnail, imgUrl, listRelationLink);
                break;
            case 10:
                mv = getOfflineCourseVo(mId, type, thumbnail, imgUrl);
                break;
            case 11:
                mv = getMarketingCourse(mId, type, thumbnail, imgUrl);
                break;
            case 12:
                mv = getTraining(mId, type, thumbnail, imgUrl);
                break;
            case 13:
                mv = getUrl(mId, type, thumbnail, imgUrl);
                break;
            case 16:
                mv = getPostList(mId, type, thumbnail, imgUrl);
                break;
            case 15:
                mv = getAlbumList(mId, type, thumbnail, imgUrl);
                break;
            default:
                break;
        }
        return mv;
    }


    public ModuleAllVO getCourse(Long mId, Integer type, Integer thumbnail, String imgUrl) {
        ModuleAllVO mv = new ModuleAllVO();
        CourseEntityVo course = null;
        try {
            course = courseClient.view(mId);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            LOG.info(e.getMessage() + "课程服务异常");
        }
        if (course != null) {
            mv.setId(course.getId());
            mv.setModuleName(course.getName());
            if (thumbnail == 1) {//本身的图片
                mv.setModuleLogo(course.getImage());
            } else {//上传的图片
                mv.setModuleLogo(imgUrl);
            }
            // 推荐课程学时
            List<Long> courseIdList = new ArrayList<>();
            courseIdList.add(course.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());
            }
        }
        return mv;
    }

    public ModuleAllVO getExam(Long mId, Integer type, Integer thumbnail, String imgUrl, List<RelationLinkVo> listRelationLink) {
        ModuleAllVO mv = new ModuleAllVO();
        ExamViewVO exam = null;
        try {
            exam = examClient.selectExam(mId);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            LOG.info(e.getMessage() + "考试服务异常");
        }
        if (exam != null) {
            mv.setId(exam.getId());
            mv.setModuleName(exam.getName());
            if (thumbnail == 1) {//本身也没有图片，采用默认的图片
                if (CollectionUtils.isNotEmpty(listRelationLink)) {
                    for (int i = 0; i < listRelationLink.size(); i++) {
                        if (listRelationLink.get(i).getId() == 102) {  //考试
                            mv.setModuleLogo(listRelationLink.get(i).getUrl());
                        }
                    }
                }
            } else {//上传的图片
                mv.setModuleLogo(imgUrl);
            }
        }
        return mv;
    }

    public ModuleAllVO getResearch(Long mId, Integer type, Integer thumbnail, String imgUrl, List<RelationLinkVo> listRelationLink) {
        ModuleAllVO mv = new ModuleAllVO();
        ResearchVo research = null;
        try {
            research = researchClient.viewOne(mId);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            LOG.info(e.getMessage() + "调研服务异常");
        }
        if (research != null) {
            mv.setId(research.getId());
            mv.setModuleName(research.getName());
            if (thumbnail == 1) {//本身也没有图片，采用默认的图片
                if (CollectionUtils.isNotEmpty(listRelationLink)) {
                    for (int i = 0; i < listRelationLink.size(); i++) {
                        if (listRelationLink.get(i).getId() == 101) {  //考试
                            mv.setModuleLogo(listRelationLink.get(i).getUrl());
                        }
                    }
                }
            } else {//上传的图片
                mv.setModuleLogo(imgUrl);
            }
        }
        return mv;
    }

    public ModuleAllVO getLive(Long mId, Integer type, Integer thumbnail, String imgUrl) {
        ModuleAllVO mv = new ModuleAllVO();
        LiveActivityVO live = null;
        try {
            live = liveActivityClient.queryLive(mId);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            LOG.info(e.getMessage() + "直播服务异常");
        }
        if (live != null) {
            mv.setId(live.getId());
            mv.setModuleName(live.getTitle());
            mv.setChannel(live.getChannel());
            if (thumbnail == 1) {
                mv.setModuleLogo(live.getLogoImage());
            } else {
                mv.setModuleLogo(imgUrl);
            }
        }
        return mv;
    }

    //public ModuleAllVO getVote(Long mId,Integer type,Integer thumbnail,String imgUrl) {
//	ModuleAllVO mv=new ModuleAllVO();
//		String voteId=mId.toString();
//		VoteVO vote=null;
//		try {
//			vote = voteClient.viewVote(voteId);
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			LOG.info(e.getMessage()+"投票服务异常");
//		}
//		if(vote!=null) {
//			mv.setId(vote.getId());
//			mv.setModuleName(vote.getVoteName());
//			if(thumbnail==1) {
//				mv.setModuleLogo(vote.getAdvertPictureUrl());
//			}
//			else {
//				mv.setModuleLogo(imgUrl);
//			}
//		}
//		return mv;
//	}
    public ModuleAllVO getAssignment(Long mId, Integer type, Integer thumbnail, String imgUrl, List<RelationLinkVo> listRelationLink) {
        ModuleAllVO mv = new ModuleAllVO();
        AssignmentSelectVo assignment = null;
        try {
            assignment = assignmentClient.query(mId);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            LOG.info(e.getMessage() + "作业服务异常");
        }
        if (assignment != null) {
            mv.setId(assignment.getId());
            mv.setModuleName(assignment.getName());
            if (thumbnail == 1) {//本身也没有图片，采用默认的图片
                if (CollectionUtils.isNotEmpty(listRelationLink)) {
                    for (int i = 0; i < listRelationLink.size(); i++) {
                        if (listRelationLink.get(i).getId() == 103) {  //作业
                            mv.setModuleLogo(listRelationLink.get(i).getUrl());
                        }
                    }
                }
            } else {//上传的图片
                mv.setModuleLogo(imgUrl);
            }
        }
        return mv;
    }

    public ModuleAllVO getCertificate(Long mId, Integer type, Integer thumbnail, String imgUrl) {
        ModuleAllVO mv = new ModuleAllVO();//证书
        CertificateVo certificate = null;
        try {
            certificate = certificateClient.getCertificate(mId);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            LOG.info(e.getMessage() + "证书服务异常");
        }
        if (certificate != null) {
            mv.setId(certificate.getId());
            mv.setModuleName(certificate.getTitle());
            if (thumbnail == 1) {
                mv.setModuleLogo(certificate.getLogourl());
            } else {
                mv.setModuleLogo(imgUrl);
            }
        }
        return mv;
    }

    public ModuleAllVO getTpPlanActivity(Long mId, Integer type, Integer thumbnail, String imgUrl, List<RelationLinkVo> listRelationLink) {
        ModuleAllVO mv = new ModuleAllVO();//外链是挂在培训项目下边的没有名字没有logo
        TpPlanActivityVo tpPlanActivity = null;
        try {
            tpPlanActivity = tpPlanActivityClient.getOne(mId);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            LOG.info(e.getMessage() + "外链服务异常");
        }
        if (tpPlanActivity != null) {
            mv.setId(tpPlanActivity.getId());
            mv.setModuleName(tpPlanActivity.getName());
            if (thumbnail == 1) {//本身也没有图片，采用默认的图片
                if (CollectionUtils.isNotEmpty(listRelationLink)) {
                    for (int i = 0; i < listRelationLink.size(); i++) {
                        if (listRelationLink.get(i).getId() == 104) {  //外链
                            mv.setModuleLogo(listRelationLink.get(i).getUrl());
                        }
                    }
                }
            } else if (thumbnail == 2) {
                mv.setModuleLogo(imgUrl);
            }
        }
        return mv;
    }

    public ModuleAllVO getOfflineCourseVo(Long mId, Integer type, Integer thumbnail, String imgUrl) {
        ModuleAllVO mv = new ModuleAllVO();//线下课程
        OfflineCourseVo offlineCourseVo = null;
        try {
            offlineCourseVo = offlineCourseClient.get(mId);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            LOG.info(e.getMessage() + "线下课程服务异常");
        }
        if (offlineCourseVo != null) {
            mv.setId(offlineCourseVo.getId());
            mv.setModuleName(offlineCourseVo.getName());
            if (thumbnail == 1) {
                mv.setModuleLogo(offlineCourseVo.getImage());
            } else {
                mv.setModuleLogo(imgUrl);
            }
        }
        return mv;
    }

    public ModuleAllVO getMarketingCourse(Long mId, Integer type, Integer thumbnail, String imgUrl) {
        ModuleAllVO mv = new ModuleAllVO();
        CourseEntityVo course = null;
        try {
            course = courseClient.view(mId);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            LOG.info(e.getMessage() + "课程服务异常");
        }
        if (course != null) {
            mv.setId(course.getId());
            mv.setModuleName(course.getName());
            if (thumbnail == 1) {// 本身的图片
                mv.setModuleLogo(course.getImage());
            } else {// 上传的图片
                mv.setModuleLogo(imgUrl);
            }
        }
        return mv;
    }

    public ModuleAllVO getTraining(Long mId, Integer type, Integer thumbnail, String imgUrl) {
        ModuleAllVO mv = new ModuleAllVO();// 培训项目
        TrainingProjectVo training = null;
        try {
            training = trainingProjectClient.getOne(mId);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            LOG.info(e.getMessage() + "培训项目服务异常");
        }
        if (training != null) {
            mv.setId(training.getId());
            mv.setModuleName(training.getName());
            if (thumbnail == 1) {
                mv.setModuleLogo(training.getLogoImg());
            } else {
                mv.setModuleLogo(imgUrl);
            }
        }
        return mv;
    }


    public ModuleAllVO getUrl(Long mId, Integer type, Integer thumbnail, String imgUrl) {
        ModuleAllVO mv = new ModuleAllVO();// 门户下的外链
        ProtalPlateVo protalPlate = null;
        try {
            protalPlate = portalManagePCFeignClients.getUrl(mId);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            LOG.info(e.getMessage() + "门户外链服务异常");
        }
        if (protalPlate != null) {
            mv.setId(protalPlate.getSelectActivity());
            mv.setModuleName(protalPlate.getLinkContentName());
            mv.setSiteUrl(protalPlate.getSelectActivityName());
            if (thumbnail == 1) {
                mv.setModuleLogo(protalPlate.getImgPath());
            } else {
                mv.setModuleLogo(imgUrl);
            }
        }
        return mv;
    }


    /**
     * 推荐专辑
     *
     * @param mId
     * @param type
     * @param thumbnail
     * @param imgUrl
     * @return
     */
    public ModuleAllVO getAlbumList(Long mId, Integer type, Integer thumbnail, String imgUrl) {
        ModuleAllVO mv = new ModuleAllVO();
        try {
            Album album = albumClient.get(mId);
            if (album != null) {
                mv.setId(album.getId());
                mv.setModuleName(album.getName());
                mv.setType(type.toString());
                if (thumbnail == 1) {
                    mv.setModuleLogo(album.getImage());
                } else {
                    mv.setModuleLogo(imgUrl);
                }
            }
        } catch (Exception e) {
            LOG.info("专辑调用异常：", e.getMessage());
        }
        return mv;
    }

    public ModuleAllVO getPostList(Long mId, Integer type, Integer thumbnail, String imgUrl) {
        ModuleAllVO mv = new ModuleAllVO();

        List<Long> ids = new ArrayList<>();
        ids.add(mId);

        try {
            Map<Long, String> names = postClient.getNames(ids);
            mv.setId(mId);
            if (!names.isEmpty()) {
                String postName = names.get(mId);
                LOG.info("帖子的名称：{}", postName);
                mv.setModuleName(postName);
                mv.setType(type.toString());
                mv.setModuleLogo(imgUrl);
            }
        } catch (Exception e) {
            LOG.info("专辑调用异常：", e.getMessage());
        }
        return mv;
    }

    /**
     * 获取专区的数据
     *
     * @param listModuleAllVO
     */
    public void getSiteStudentPC(List<ModuleAllVO> listModuleAllVO, Long id) {
        RequestContext context = ContextHolder.get();
        String key = CacheNamespace.SITE_STUDENT_RECORDS + context.getSiteId() + "_" + id;
        List<ProtalPlateVo> protalPlates = null;
        Object o = redisCache.get(key);
        if (o != null) {
            protalPlates = JSON.parseArray(o.toString(), ProtalPlateVo.class);
        } else {
            protalPlates = portalApiPCFeignClients.templateContentView(id);
        }
        //数据处理
        dealData(protalPlates, listModuleAllVO, key);

    }

    /**
     * 数据处理
     *
     * @param records
     * @param listModuleAllVO
     * @param key
     */
    private void dealData(List<ProtalPlateVo> records, List<ModuleAllVO> listModuleAllVO, String key) {
        //获取当前学员可访问的站点
        Set<Long> accessSiteIds = remoteSiteClient.frontList();
        if (CollectionUtils.isNotEmpty(records)) {
            //获取实时数据
            //获取有权限访问的站点id
            List<Long> collect = new ArrayList<>(records.size());
            records.parallelStream().forEach(a -> {
                //移除无权限的站点
                if (accessSiteIds.contains(a.getLinkContent())) {
                    collect.add(a.getLinkContent());
                }
            });
            //获取实时数据
            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));
                    for (ProtalPlateVo a : records) {
                        if (!accessSiteIds.contains(a.getLinkContent())) {
                            continue;
                        }
                        ModuleAllVO moduleAllVO = new ModuleAllVO();
                        moduleAllVO.setBizId(a.getLinkContent());
                        moduleAllVO.setId(a.getId());
                        moduleAllVO.setModuleName(a.getLinkContentName());
                        moduleAllVO.setModuleLogo(a.getImgPath());
                        //用于标识站点domain
                        moduleAllVO.setDirections(a.getDirections());
                        moduleAllVO.setThumbnail(a.getThumbnail());
                        if (siteVOMap != null) {
                            SiteVO siteVO = siteVOMap.get(a.getLinkContent());
                            if (siteVO != null) {
                                moduleAllVO.setModuleLogo(a.getThumbnail() == 0 ? siteVO.getLogo() : a.getImgPath());
                                moduleAllVO.setModuleName(siteVO.getName());
                                moduleAllVO.setDirections(siteVO.getDomain());
                            }
                        }
                        listModuleAllVO.add(moduleAllVO);
                    }
                    redisCache.set(key, JSON.toJSONString(records), EXPIRE_TIME);
                }
            }
        }
    }

    /**
     * 微信端获取专区的数据
     *
     * @param records
     */
    public List<PortalPlateVO> getSiteStudent(List<PortalPlateVO> records) {
        //获取当前学员可访问的站点
        Set<Long> accessSiteIds = remoteSiteClient.frontList();
        List<PortalPlateVO> finalRecords = null;
        if (CollectionUtils.isNotEmpty(records)) {
            finalRecords = new ArrayList<>(records.size());
            //获取实时数据
            //获取有权限访问的站点id
            List<Long> collect = new ArrayList<>(records.size());
            records.parallelStream().forEach(a -> {
                //移除无权限的站点
                if (accessSiteIds.contains(a.getActivityId())) {
                    collect.add(a.getActivityId());
                }
            });
            //获取实时数据
            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));
                    for (PortalPlateVO a : records) {
                        if (!accessSiteIds.contains(a.getActivityId())) {
                            continue;
                        }
                        //用于标识站点domain
                        if (siteVOMap != null) {
                            SiteVO siteVO = siteVOMap.get(a.getActivityId());
                            if (siteVO != null) {
                                //使用站点本身图片
                                if (a.getThumbnail() != null && a.getThumbnail() == 0) {
                                    a.setImage(siteVO.getLogo());
                                }
                                a.setName(siteVO.getName());
                                a.setDirections(siteVO.getDomain());
                            }

                        }
                        finalRecords.add(a);
                    }
                }
            }
        }
        return finalRecords;
    }
}
