package com.ssj.service.course.service.impl;

import com.ssj.bean.course.domain.CourseSeriesDetail;
import com.ssj.bean.course.domain.CourseSeriesDetailFeedback;
import com.ssj.bean.course.domain.CourseSeriesJoin;
import com.ssj.bean.course.domain.CourseSeriesSetting;
import com.ssj.bean.weixin.libmy.domain.LibVip;
import com.ssj.bean.weixin.libmy.domain.TbLibJoin;
import com.ssj.bean.weixin.user.domain.User;
import com.ssj.dao.course.dao.CourseQueryDao;
import com.ssj.dao.course.dao.CourseSeriesJoinDao;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.service.course.req.CourseSeriesAddReq;
import com.ssj.service.course.req.CourseSeriesAddVip;
import com.ssj.service.course.res.CourseSeriesCalendarRes;
import com.ssj.service.course.res.CourseSeriesRes;
import com.ssj.service.course.res.CourseSeriesTimeRes;
import com.ssj.service.course.service.CourseSeriesDetailFeedbackService;
import com.ssj.service.course.service.CourseSeriesJoinService;
import com.ssj.service.course.service.CourseSeriesSettingService;
import com.ssj.service.course.service.ICSDetailService;
import com.ssj.service.weixin.library.service.ILibJoinService;
import com.ssj.service.weixin.library.service.ILibVipService;
import com.ssj.service.weixin.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author  ZhangCaibao
 * @version 2018年10月18日 下午3:24:57
 * 类说明
 */
@Transactional
@Service
public class CourseSeriesJoinServiceImpl extends BaseServiceImpl<CourseSeriesJoin, String> implements CourseSeriesJoinService {
	@Autowired
	private  CourseSeriesJoinDao  dao;
	@Autowired
	private  CourseQueryDao  queryDao;
	@Autowired
	private  ICSDetailService  cSDetailService;
	@Autowired
	private  CourseSeriesSettingService  courseSeriesSettingService;
	@Autowired
	private ILibJoinService  joinService;
	@Autowired
	private UserService userService;
	@Autowired
	private  CourseSeriesDetailFeedbackService  courseSeriesDetailFeedbackService;
	@Autowired
	private ILibVipService vipService;
	@Override
	public PagingAndSortingRepository<CourseSeriesJoin, String> getDao() {
		return dao;
	}
	@Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
	public int findCourseSeriesJoinBycourseDetailsIdAndLibId(
			String courseDetailsId, String libId, String vipId) {
		return dao.findCourseSeriesJoinBycourseDetailsIdAndLibId(courseDetailsId, libId, vipId);
	}
	@Override
	public void saveCousreSeriesJoin(CourseSeriesAddReq req,String userId) {
		List<String> vipIds  = req.getVipIds();

		List<CourseSeriesDetail> list =cSDetailService.findBySeriesId(req.getCourseSeriesId());
		CourseSeriesSetting courseSeriesSetting =courseSeriesSettingService.fingByCourseSeriesIdAndLibIdLimit(req.getCourseSeriesId(), req.getLibId());
		//int days =courseSeriesSetting.getDays();
		String[] weeks=courseSeriesSetting.getWeeks().split(",");
		List<String> resultList = new ArrayList<>(weeks.length);
		Collections.addAll(resultList,weeks);
		Collections.sort(resultList);



		for (String vipId : vipIds) {
			Date openTime = courseSeriesSetting.getOpenTime();
			int day = DateHelper.getday(openTime)-1	;//周四
			// 计算今天是周几，  看是否有提交的 周几上课
			Integer few =-1;
			if(few==-1){
				for (int j = 0; j < resultList.size(); j++) {
					few=	Integer.parseInt(resultList.get(j))-day>=0?j:-1;
					if(few>-1){
						break;
					}
				}
			}
			if(few==-1)few=0;
			Integer we =Integer.parseInt(resultList.get(few));//第一个
			Integer oldwe =day;

			int type =dao.findCourseSeriesJoinBycourseDetailsIdAndLibId(req.getCourseSeriesId(), req.getLibId(), vipId);
			if(type == 0){
				List<CourseSeriesJoin> joinList =new ArrayList<CourseSeriesJoin>();
				for (int i = 0; i < list.size(); i++) {
					CourseSeriesJoin join = new  CourseSeriesJoin();
					join.setCourseSeriesId(req.getCourseSeriesId());
					join.setCreateTime(new Date());
					join.setLibId(req.getLibId());
					join.setUserId(userId);
					openTime=DateHelper.getNextDay(openTime, we >=oldwe ? (we-oldwe) :(we+7-oldwe));
					join.setOpenTime(openTime);
					join.setVipId(vipId);
					join.setCourseDetailsId(list.get(i).getId());
					join.setState(0);
					join.setNum(list.get(i).getCourseIndex());
					joinList.add(join);
					oldwe =we;
					few ++;
					few=few %resultList.size();
					we =Integer.parseInt(resultList.get(few));
				}
				this.save(joinList);

			}
		}

	}
	@Override
	public void saveCousreSeriesJoin(CourseSeriesAddVip req,String userId) {

		LibVip  libVip= new LibVip();
		libVip.setCreateTime(new Date());
		libVip.setStat("1");//生成的会员卡设置为有效状态 1--有效 2--无效',
		libVip.setLevel(1);
		libVip.setUserId(userId);
		User user=userService.getById(userId);
		TbLibJoin libjoin = joinService.getById(req.getLibId());
		libVip.setBanben(libjoin !=null ? (libjoin.getLeagueCode()!=null &&libjoin.getLeagueCode().startsWith("SZ")?2:1):1);
		libVip.setImgUrl(user!=null?user.getPhoto():null);
		libVip.setActivateTime(new Date());
		libVip.setChildName(req.getChildName());libVip.setParentName(req.getParentName());
		libVip.setPhone(req.getPhone());libVip.setGrade(req.getGrade());libVip.setSchool(req.getSchool());
		vipService.save(libVip);
		String vipId =libVip.getId();
		List<CourseSeriesDetail> list =cSDetailService.findBySeriesId(req.getCourseSeriesId());
		CourseSeriesSetting courseSeriesSetting =courseSeriesSettingService.fingByCourseSeriesIdAndLibIdLimit(req.getCourseSeriesId(), req.getLibId());
		String[] weeks=courseSeriesSetting.getWeeks().split(",");
		List<String> resultList = new ArrayList<>(weeks.length);
		Collections.addAll(resultList,weeks);
		Collections.sort(resultList);

		Date openTime = courseSeriesSetting.getOpenTime();
		int day = DateHelper.getday(openTime)-1	;//周四
		// 计算今天是周几，  看是否有提交的 周几上课
		Integer few =-1;
		if(few==-1){
			for (int j = 0; j < resultList.size(); j++) {
				few=	Integer.parseInt(resultList.get(j))-day>=0?j:-1;
				if(few>-1){
					break;
				}
			}
		}
		if(few==-1)few=0;
		Integer we =Integer.parseInt(resultList.get(few));//第一个
		Integer oldwe =day;

		List<CourseSeriesJoin> joinList =new ArrayList<CourseSeriesJoin>();
		for (int i = 0; i < list.size(); i++) {
			CourseSeriesJoin join = new  CourseSeriesJoin();
			join.setCourseSeriesId(req.getCourseSeriesId());
			join.setCreateTime(new Date());
			join.setLibId(req.getLibId());
			join.setUserId(userId);
			openTime=DateHelper.getNextDay(openTime, we >=oldwe ? (we-oldwe) :(we+7-oldwe));
			join.setOpenTime(openTime);
			join.setVipId(vipId);
			join.setCourseDetailsId(list.get(i).getId());
			join.setState(0);
			join.setNum(list.get(i).getCourseIndex());
			joinList.add(join);
			oldwe =we;
			few ++;
			few=few %resultList.size();
			we =Integer.parseInt(resultList.get(few));
		}
		this.save(joinList);



	}

	@Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
	public CourseSeriesCalendarRes findCourseSeriesJoinByUserId(String userId,String vipId,String id,String libId) {
		CourseSeriesCalendarRes res=new CourseSeriesCalendarRes();
		List<CourseSeriesTimeRes> courseSeriesTimes=new ArrayList<CourseSeriesTimeRes>();
		List<CourseSeriesRes> courseSeriesList=new ArrayList<CourseSeriesRes>();

		List<Map<String,Object>> courseSeriesJoinMaps=queryDao.findCourseSeriesJoinByUserId(userId,vipId,id,libId);
		for (Map<String, Object> map : courseSeriesJoinMaps) {
			CourseSeriesTimeRes time=new CourseSeriesTimeRes();
			String openTime=(map.get("open_time").toString());
			String[] openTimes=openTime.split(",");
			time.setId(map.get("course_series_id").toString());
			time.setLibId(map.get("lib_id").toString());
			time.setColor(map.get("color")!=null ? map.get("color").toString() : "#FF80A8");
			time.setOpenTimes(Arrays.asList(openTimes));
			courseSeriesTimes.add(time);
		}

		List<Map<String,Object>> courseSeriesMaps= queryDao.findCourseSeriesByUserId(userId,vipId);
		if(StringUtils.isNotEmpty(id) && StringUtils.isNotEmpty(libId)){
			for (Map<String, Object> map : courseSeriesMaps) {
				String cld=map.get("lib_id").toString();
				String cd=map.get("id").toString();
				if(id.equals(cd) && libId.equals(cld)){
					CourseSeriesRes courseSeries=new CourseSeriesRes();
					courseSeries.setLibId(map.get("lib_id").toString());
					courseSeries.setId(map.get("id").toString());
					courseSeries.setCoverUrl(map.get("cover_url")!=null?map.get("cover_url").toString():"");
					courseSeries.setClassPnum(map.get("class_pnum")!=null?map.get("class_pnum").toString():"");
					courseSeries.setCourseName( map.get("course_name")!=null?map.get("course_name").toString():"");
					courseSeries.setCoursePlan( map.get("course_plan")!=null?map.get("course_plan").toString():"");
					courseSeries.setCourseSummary( map.get("course_summary")!=null?map.get("course_summary").toString():"");
					courseSeries.setCourseTarget( map.get("course_target")!=null?map.get("course_target").toString():"");
					courseSeries.setTeacherName( map.get("name")!=null?map.get("name").toString():"");


					List<Map<String,Object>> details =cSDetailService.findSeriesDetailsByUserId(courseSeries.getId(),userId,vipId, cld);
					List<Map<String, Object>> detailMaps=new ArrayList<Map<String,Object>>();
					for (Map<String,Object> courseSeriesDetail : details) {
						Map<String, Object> tMap=new HashMap<String, Object>();
						tMap.put("id", courseSeriesDetail.get("id").toString());
						tMap.put("seriesId", courseSeriesDetail.get("series_id")!=null ? courseSeriesDetail.get("series_id").toString() :"");
						tMap.put("courseUnit", courseSeriesDetail.get("course_unit")!=null ? courseSeriesDetail.get("course_unit").toString() :"");
						tMap.put("courseContent", courseSeriesDetail.get("course_content")!=null ?
								courseSeriesDetail.get("course_content").toString().replaceAll("\r","").replaceAll("\n", "").split("；") :"");
						tMap.put("courseModel", courseSeriesDetail.get("course_model")!=null ? courseSeriesDetail.get("course_model").toString() :"");
						tMap.put("courseDuration", courseSeriesDetail.get("course_duration")!=null ?courseSeriesDetail.get("course_duration").toString():"");
						tMap.put("courseNum", courseSeriesDetail.get("course_num")!=null ? courseSeriesDetail.get("course_num").toString() :"");
						tMap.put("courseIndex", courseSeriesDetail.get("course_index")!=null ? courseSeriesDetail.get("course_index").toString():"");
						tMap.put("openTime",courseSeriesDetail.get("open_time")!=null?  courseSeriesDetail.get("open_time").toString() :"");
						detailMaps.add(tMap);
					}
					courseSeries.setDetails(detailMaps);
					courseSeriesList.add(courseSeries);
				}
			}
		}else{
			for (Map<String, Object> map : courseSeriesMaps) {
				CourseSeriesRes courseSeries=new CourseSeriesRes();
				String cld=map.get("lib_id").toString();
				courseSeries.setLibId(map.get("lib_id").toString());
				courseSeries.setId(map.get("id").toString());
				courseSeries.setCoverUrl(map.get("cover_url")!=null?map.get("cover_url").toString():"");
				courseSeries.setClassPnum(map.get("class_pnum")!=null?map.get("class_pnum").toString():"");
				courseSeries.setCourseName( map.get("course_name")!=null?map.get("course_name").toString():"");
				courseSeries.setCoursePlan( map.get("course_plan")!=null?map.get("course_plan").toString():"");
				courseSeries.setCourseSummary( map.get("course_summary")!=null?map.get("course_summary").toString():"");
				courseSeries.setCourseTarget( map.get("course_target")!=null?map.get("course_target").toString():"");
				courseSeries.setTeacherName( map.get("name")!=null?map.get("name").toString():"");

				List<Map<String,Object>> details =cSDetailService.findSeriesDetailsByUserId(courseSeries.getId(),userId,vipId,  cld);
				List<Map<String, Object>> detailMaps=new ArrayList<Map<String,Object>>();
				for (Map<String,Object> courseSeriesDetail : details) {
					Map<String, Object> tMap=new HashMap<String, Object>();
					tMap.put("id", courseSeriesDetail.get("id").toString());
					tMap.put("seriesId", courseSeriesDetail.get("series_id")!=null ? courseSeriesDetail.get("series_id").toString() :"");
					tMap.put("courseUnit", courseSeriesDetail.get("course_unit")!=null ? courseSeriesDetail.get("course_unit").toString() :"");
					tMap.put("courseContent", courseSeriesDetail.get("course_content")!=null ?
							courseSeriesDetail.get("course_content").toString().replaceAll("\r","").replaceAll("\n", "").split("；") :"");
					tMap.put("courseModel", courseSeriesDetail.get("course_model")!=null ? courseSeriesDetail.get("course_model").toString() :"");
					tMap.put("courseDuration", courseSeriesDetail.get("course_duration")!=null ?courseSeriesDetail.get("course_duration").toString():"");
					tMap.put("courseNum", courseSeriesDetail.get("course_num")!=null ? courseSeriesDetail.get("course_num").toString() :"");
					tMap.put("courseIndex", courseSeriesDetail.get("course_index")!=null ? courseSeriesDetail.get("course_index").toString():"");
					tMap.put("openTime",courseSeriesDetail.get("open_time")!=null?  courseSeriesDetail.get("open_time").toString() :"");
					detailMaps.add(tMap);
				}
				courseSeries.setDetails(detailMaps);
				courseSeriesList.add(courseSeries);
			}
		}

		res.setCourseSeriesDetails(courseSeriesList);
		res.setCourseSeriesTimes(courseSeriesTimes);
		return res;
	}
	@Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
	public List<Map<String, Object>> findCourseSeriesFeedbackByUserId(String userId,String vipId) {
		return queryDao.findCourseSeriesFeedbackByUserId(userId,vipId);
	}
	@Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
	public Page<Map<String, Object>> findFeedbackPageByUserId(Map<String, Object> searchParams, Pageable pageable) {
		Page<Map<String, Object>> page=queryDao.findFeedbackPageByUserId(searchParams, pageable);
		List<Map<String,Object>> list=page.getContent();
		for (Map<String, Object> map : list) {
			Integer state=(Integer) map.get("state");
			String courseDetailsId=map.get("course_details_id").toString();
			String vipId=map.get("vip_id").toString();
			if(2==state){//已反馈，去查反馈数据
				CourseSeriesDetailFeedback feedback=courseSeriesDetailFeedbackService.findyDetailIdAndVipId(courseDetailsId,vipId);
				if(feedback==null){
					feedback=new CourseSeriesDetailFeedback();
				}
				Map<String,Object> feedbackMap=new LinkedHashMap<String, Object>();
				feedbackMap.put("id", feedback.getLibFeedbackId());
				feedbackMap.put("activeScore", feedback.getActiveScore());
				feedbackMap.put("courseDetailsId", feedback.getCourseDetailsId());
				feedbackMap.put("courseSeriesId", feedback.getCourseSeriesId());
				feedbackMap.put("createTime", feedback.getCreateTime());
				feedbackMap.put("evaluate", feedback.getEvaluate());
				feedbackMap.put("isSend", feedback.getIsSend());
				feedbackMap.put("libId", feedback.getLibId());
				feedbackMap.put("pleasedScore", feedback.getPleasedScore());
				feedbackMap.put("saying", feedback.getSaying());
				feedbackMap.put("userId", feedback.getUserId());
				feedbackMap.put("vipId", feedback.getVipId());
				map.put("feedback", feedbackMap);
			}else{
				map.put("feedback", new CourseSeriesDetailFeedback());
			}
		}
		return page;
	}
	@Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
	public List<Map<String, Object>> findVipIsBuy(String userId,String courseDetailsId,String libId) {
		return queryDao.findVipIsBuy(userId, courseDetailsId, libId);
	}
	@Override
	public void updateBeginTime(String libId, String courseDetailId) {
		dao.updateBeginTime(libId,courseDetailId);
	}
	@Override
	public void courseUpdateTime(String courseDetailId, String libId) {

		dao.courseUpdateTime(courseDetailId,libId);
	}
	@Override
	public void updateStateSend(String courseDetailsId, String vipId, String libId) {

		dao.updateStateSend(courseDetailsId,vipId,libId);
	}
	@Override
	public void updateJoinDate(String courseDetailsId, String libId,int num ,Date date) {
		dao.updateJoinDate(courseDetailsId, libId, num, date);
	}

	@Override
	public void updateJoinDate2(String courseDetailsId, String libId, int num) {
		dao.updateJoinDate2(courseDetailsId,libId,num);
	}

	@Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
	public List<Map<String, Object>> findCourseRecordList(String userId,String vipId) {
		return queryDao.findCourseRecordList(userId, vipId);
	}
	@Override
	public void saveOrUpdateJoinDate(String courseDetailsId, String libId,
									 int num, Date date,List<String> vipIds,String courseSeriesId) {
		for (String vipId : vipIds) {
			CourseSeriesJoin seriesjoin=dao.findBycourseDetailsIdAndLibIdAndNum(courseDetailsId, libId,vipId);
			if(seriesjoin==null){
				seriesjoin  =new CourseSeriesJoin();
				seriesjoin.setCourseDetailsId(courseDetailsId);
				seriesjoin.setLibId(libId);
				seriesjoin.setVipId(vipId);
				seriesjoin.setState(0);
			}
			seriesjoin.setCourseSeriesId(courseSeriesId);
			seriesjoin.setCreateTime(new Date());
			seriesjoin.setNum(num);
			seriesjoin.setOpenTime(date);
			this.save(seriesjoin);
		}
	}
	@Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
	public List<String> findByVipIdAndCourseSeriesIdAndLibId(String libId,String courseSeriesId){
		return dao.findByVipIdAndCourseSeriesIdAndLibId(libId, courseSeriesId);
	}
	@Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
	public void delByAnyReq(String libId, String courseSeriesId, String vipId) {
		dao.delByAnyReq(libId,courseSeriesId,vipId);
	}
	@Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
	public CourseSeriesJoin findOneDataByAny(String libId, String courseSeriesId) {

		return dao.findOneDataByAny(libId,courseSeriesId);
	}
	@Override
	public void updateDetailsData(String courseDetailId, String newTime,String libId,int num) {
		dao.updateDetailsData(courseDetailId,newTime,libId,num);
	}
	@Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
	public int findStudentCount(String libId, String courseSeriesId) {

		return dao.findStudentCount(libId,courseSeriesId);
	}
	@Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
	public List<CourseSeriesJoin> findbyLibJoinList(String seriesId, String libId) {

		return dao.findbyLibJoinList(libId,seriesId);
	}

	@Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
	public List<CourseSeriesJoin> findbyLibAndVip(String libId, String seriesId, String vipId, int num, Date openTime) {
		return dao.findbyLibAndVip(libId,seriesId,vipId,num,openTime);
	}

	@Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
	public CourseSeriesJoin findOneDataByDetail(String libId, String detailId) {
		return dao.findOneDataByDetail(libId,detailId);
	}

	@Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
	public CourseSeriesJoin findOneDataByDetailAndTime(String libId, String detailId, Date openTime) {
		return dao.findOneDataByDetailAndTime(libId,detailId,openTime);
	}
}