package com.cirle.scientific.service.impl;

import com.cirle.scientific.constants.RedisKeyConstants;
import com.cirle.scientific.dao.*;
import com.cirle.scientific.dto.*;
import com.cirle.scientific.po.*;
import com.cirle.scientific.pojo.Result;
import com.cirle.scientific.service.HomeService;
import com.cirle.scientific.service.LiveService;
import com.cirle.scientific.service.MemberService;
import com.cirle.scientific.service.RecommendService;
import com.cirle.scientific.utils.DateFormater;
import com.cirle.scientific.utils.SolrUtils;
import com.cirle.scientific.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@Transactional
public class HomeServiceImpl implements HomeService {

    @Autowired
    private RecommendService recommendService;

    @Autowired
    private QkjIntegralDetailDao qkjIntegralDetailDao;

    @Autowired
    private QkjIntegralGoodsDao qkjIntegralGoodsDao;

    @Autowired
    private MemberService memberService;

    @Autowired
    private LiveService liveService;

	@Autowired
	QkjMemberTaskInfoDao qkjMemberTaskInfoDao;

	@Autowired
	private QkjTqcourseDao tqcourseDao;

	@Autowired
	private QkjArticleDao articleDao;

	@Autowired
	private QkjCourseWareDao courseWareDao;

	@Autowired
	private QkjBrandProductDao brandProductDao;

	@Autowired
	private QkjConferenceDao conferenceDao;

	@Autowired
	private QkjBrandProductDetailDao productDetailDao;

	@Autowired
	private QkjLiveDao liveDao;

	@Autowired
	private MemberDao memberDao;

	@Autowired
	QkjTagsDao qkjTagsDao;

	@Autowired
	StringRedisTemplate stringRedisTemplate;

	@Override
	public Result<HomeDataDTO> getHomeData(String memCard, Integer status) {

		HomeDataDTO homeData = makeHomeData(status);
		if (StringUtils.isNotBlank(memCard)) {
			QkjMemberTaskInfo byMemCard = qkjMemberTaskInfoDao.findByMemCard(memCard);
			if(byMemCard != null){
				homeData.setUserJf(byMemCard.getMemTotalPoints());
			}
		}
		return Result.success(homeData);
	}

	@Override
	public Result<HomeDataDTO> getHomeData(String memCard) {
		return getHomeData(memCard, null);
	}

	@Override
    public String search(String searchKw, int start, int size) {
		Map<String, String> sortMap = new LinkedHashMap<String, String>();
		sortMap.put("obj_type", "asc");
		String rdlist = SolrUtils.searchDoc("default:'" + searchKw.trim() + "'", sortMap, (start - 1) * size, size);
		return rdlist;
    }

	private HomeDataDTO makeHomeData(){
		return makeHomeData(null);
	}
    private HomeDataDTO makeHomeData(Integer status){
		HomeDataDTO dto = new HomeDataDTO();
		//顶部轮播图
		dto.setSwriperRecommends(recommendService.findByPosIdLimit(1L, status, 1, 10));

		//积分商城
		List<QkjIntegralDetail> list = qkjIntegralDetailDao.findByNewChange(0, 10);
        if (list != null && !list.isEmpty()) {
        		List<QkjIntegralDetailDto> integralDetailDtos = list.stream().map(item -> {
                QkjIntegralDetailDto copy = new QkjIntegralDetailDto();
                if (item.getGoodsId() != null) {
                    QkjIntegralGoods qkjIntegralGoods = qkjIntegralGoodsDao.findById(item.getGoodsId().longValue()).get();
                    if (qkjIntegralGoods != null) {
                        copy.setTitle(qkjIntegralGoods.getGoodsName());
                    }
                    QkjMember member = memberService.findByMemCard(item.getMemCard());
                    if(member != null){
                    	copy.setMemNickname(member.getMemNickname());
                    }
                }
                return copy;
            }).collect(Collectors.toList());
        		dto.setIntegralDetailDtos(integralDetailDtos);
        		dto.setIntegralDetailCount(qkjIntegralDetailDao.count());
        }

		//积分商城下不系列广告位
		dto.setSeriesRecommends(recommendService.findByPosId(2L, status));
		for(QkjPositionsDTO post : dto.getSeriesRecommends().getChildren()){
			for(QkjRecommendDTO rcmd : post.getRcmdData()){
				rcmd = makeRcmdDto(rcmd);
			}
		}
		return dto;
	}

	@Override
	public QkjPeopleCounDTO peopleCount(HttpServletRequest request) {
		QkjPeopleCounDTO qkjPeopleCounDTO = new QkjPeopleCounDTO();
		//在线人数:真实在线人数+随机数+固定人数
		int online;
		//注册人数
		Integer people = memberDao.findPeople();
		qkjPeopleCounDTO.setRegisterPerson(people);
		//1-10随机数
		int i = (int)(Math.random()*10+1);
		online = i + people/2;
		//在线人数不能超过注册人数
		if(online > people){
			online = people/2;
		}
		String userCard = stringRedisTemplate.opsForValue().get(RedisKeyConstants.redisOnlinePerson);
		if(userCard!= null){
			qkjPeopleCounDTO.setOnlinePerson(Integer.valueOf(userCard));
		}else{
			qkjPeopleCounDTO.setOnlinePerson(1);
		}
		return qkjPeopleCounDTO;
	}

	private QkjRecommendDTO makeRcmdDto(QkjRecommendDTO rcmd){
		if(rcmd.getRcmdType() == 1){
			//精品课
			QkjTqcourse tqcourse = tqcourseDao.findById(Long.parseLong(rcmd.getRcmdObjId())).get();
			if(tqcourse != null){
				rcmd.setPrice(tqcourse.getPrice());
				rcmd.setPoint(tqcourse.getPoint());
				if(tqcourse.getPointFlag() == 0){
					rcmd.setPoint(0);
				}
				rcmd.setIsSell(tqcourse.getIsSell());
				if(tqcourse.getZq() == 2){
					rcmd.setZqFlag(1);
					List<QkjTqcourse> tqcourses = tqcourseDao.findTqListForZq(tqcourse.getId().intValue(),0,100);
					int purchasedMembers = 0;
					for(QkjTqcourse tq : tqcourses){
						purchasedMembers += tq.getPurchasedMembers()+tq.getStudyNum();
					}
					rcmd.setTime("共"+tqcourses.size()+"套 · "+StringUtil.getTenThousandOfANumber(purchasedMembers)+"人次学习");
				}else{
					rcmd.setZqFlag(0);
					rcmd.setTime("共"+tqcourse.getTotalClassHours()+"讲 · "+StringUtil.getTenThousandOfANumber(tqcourse.getPurchasedMembers()+tqcourse.getStudyNum())+"人次学习");
				}
			}
		}else if(rcmd.getRcmdType() == 2){
			//直播
			QkjLive live = liveService.getLiveInfo(Long.parseLong(rcmd.getRcmdObjId()));
			if(live != null){
				rcmd.setPrice(live.getPrice());
				rcmd.setPoint(live.getPoint());
				if(live.getPointFlag() == 0){
					rcmd.setPoint(0);
				}
				rcmd.setIsSell(live.getIsSell());
				if(live.getLiveType() == 2){
					rcmd.setZqFlag(1);
					int joinMembers = 0;
					List<QkjLive> lives = liveDao.findSonList(live.getId().intValue(), 0, 100);
					for(QkjLive l : lives){
						joinMembers += l.getPurchasedMembers()+l.getJoinMembers();
					}
					rcmd.setTime("共"+lives.size()+"套 "+StringUtil.getTenThousandOfANumber(joinMembers)+"人次学习");
				}else{
					rcmd.setObjStatus(live.getLiveStatus());
					rcmd.setZqFlag(0);
					if(live.getLiveStatus() == 0){
						rcmd.setTime(StringUtil.getTenThousandOfANumber(live.getRemindMembers())+"人预约");
						rcmd.setTime1(DateFormater.formatDate(live.getLiveBeginTime(),"MM月dd日 HH:mm"));
					}else{
						rcmd.setTime(StringUtil.getTenThousandOfANumber(live.getPurchasedMembers()+live.getJoinMembers())+"人次学习");
					}
				}
			}
		}else if(rcmd.getRcmdType() == 3){
			//咨询文章
			QkjArticle tqcourse = articleDao.findById(Long.parseLong(rcmd.getRcmdObjId())).get();
			rcmd.setIsSell(1);
			if(tqcourse != null){
				rcmd.setTime("作者："+tqcourse.getAuthor()+" ·"+StringUtil.getTenThousandOfANumber(tqcourse.getClick())+"次阅读");
			}
			rcmd.setArtType(tqcourse.getType());
			rcmd.setArtContent(tqcourse.getContent());
			//保存课件标签
			List<QkjTags> tags = qkjTagsDao.findTagsByObjIdAndObjType(tqcourse.getId(), 4);
			if (tags != null && !tags.isEmpty()) {
				rcmd.setTags(tags);
			}
		}else if(rcmd.getRcmdType() == 4){
			//会议
			QkjConference live = conferenceDao.findById(Long.parseLong(rcmd.getRcmdObjId())).get();
			if(live != null){
				rcmd.setPrice(live.getPrice());
				rcmd.setPoint(live.getPoint());
				if(live.getPointFlag() == 0){
					rcmd.setPoint(0);
				}
				rcmd.setIsSell(live.getIsSell());
				if(live.getType() == 1){
					rcmd.setZqFlag(1);
					int peopleCount = 0;
					List<QkjConference> conferences = conferenceDao.findSonList(live.getId());
					for (QkjConference info : conferences){
						peopleCount+=info.getPeopleCount();
					}
					rcmd.setTime1(live.getProvince()+"·"+live.getCity()+"   "+ (live.getBigenTime()==null?"":DateFormater.formatDate(live.getBigenTime(),"yyyy年MM月dd日")));
					rcmd.setTime("共"+live.getConferSonCount()+"场 · "+StringUtil.getTenThousandOfANumber(peopleCount)+"次学习");
				}else{
					rcmd.setTime1(live.getProvince()+"·"+live.getCity()+"   "+ (live.getBigenTime()==null?"":DateFormater.formatDate(live.getBigenTime(),"yyyy年MM月dd日")));
					rcmd.setTime(StringUtil.getTenThousandOfANumber(live.getPeopleCount())+"次学习");
				}
			}
		}else if(rcmd.getRcmdType() == 5){
			//广告

		}else if(rcmd.getRcmdType() == 6){
			//品牌专区
			rcmd.setIsSell(1);
			int count = 0;
			List<QkjBrandProductDetail> detailList = productDetailDao.findByProductId(Long.parseLong(rcmd.getRcmdObjId()));
			QkjBrandProduct qkjBrandProduct = brandProductDao.findById(Long.parseLong(rcmd.getRcmdObjId())).get();
			if (qkjBrandProduct != null && !StringUtils.isEmpty(qkjBrandProduct.getSubTitle()) ){
				rcmd.setSubTitle(qkjBrandProduct.getSubTitle());
			}
			for(QkjBrandProductDetail detail : detailList){
				//类型 1-直播 2-精品课 3-资讯文章 4-会议 5-课件
				if(detail.getObjType() == 1){
					QkjLive live = liveService.getLiveInfo(detail.getObjId().longValue());
					if(live.getLiveType() == 2){
						int joinMembers = 0;
						List<QkjLive> lives = liveDao.findSonList(live.getId().intValue(), 0, 100);
						for(QkjLive l : lives){
							joinMembers += l.getPurchasedMembers();
						}
						count += joinMembers;
					}else{
						count += live.getPurchasedMembers();
					}
				}else if(detail.getObjType() == 2){
					QkjTqcourse live = tqcourseDao.findById(detail.getObjId().longValue()).get();
					if(live.getZq() == 2){
						List<QkjTqcourse> tqcourses = tqcourseDao.findTqListForZq(live.getId().intValue(),0,100);
						int purchasedMembers = 0;
						for(QkjTqcourse tq : tqcourses){
							purchasedMembers += tq.getPurchasedMembers()+tq.getStudyNum();
						}
						count += purchasedMembers;
					}else{
							count += live.getPurchasedMembers()+live.getStudyNum();
					}
				}else if(detail.getObjType() == 3){
					QkjArticle live = articleDao.findById(detail.getObjId().longValue()).get();
					count += live.getClick();
				}else if(detail.getObjType() == 4){
					QkjConference live = conferenceDao.findById(detail.getObjId().longValue()).get();
					if(live.getType() == 1){
						int peopleCount = 0;
						List<QkjConference> conferences = conferenceDao.findSonList(live.getId());
						for (QkjConference info : conferences){
							peopleCount+=info.getPeopleCount();
						}
						count += peopleCount;
					}else{
						count += live.getPeopleCount();
					}
				}else if(detail.getObjType() == 5){
					QkjCourseWare live = courseWareDao.findById(detail.getObjId().longValue()).get();
					count += live.getDownloadMembers();
				}
			}
			rcmd.setTime(StringUtil.getTenThousandOfANumber(count)+"人次学习");
			//rcmd.setRcmdTitle();
		}else if(rcmd.getRcmdType() == 7){
			//课件
			QkjCourseWare tqcourse = courseWareDao.findById(Long.parseLong(rcmd.getRcmdObjId())).get();
			if(tqcourse != null) {
				rcmd.setPrice(tqcourse.getPrice());
				rcmd.setPoint(tqcourse.getPoint());
				if(tqcourse.getPointFlag() == 0){
					rcmd.setPoint(0);
				}
				rcmd.setTime(StringUtil.getTenThousandOfANumber(tqcourse.getDownloadMembers()) + "次下载");
			}
			//保存课件标签
			List<QkjTags> tags = qkjTagsDao.findTagsByObjIdAndObjType(tqcourse.getId(), 7);
			if (tags != null && !tags.isEmpty()) {
				rcmd.setTags(tags);
			}

		}
		return rcmd;
	}

}
