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

import com.ssj.bean.course.domain.CourseSeriesDetail;
import com.ssj.bean.course.domain.CourseSeriesSetting;
import com.ssj.dao.course.dao.CourseSeriesSettingDao;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.util.StringUtil;
import com.ssj.service.course.req.CourseSettingSave;
import com.ssj.service.course.res.CourseSeriesSettingRes;
import com.ssj.service.course.service.CourseSeriesJoinService;
import com.ssj.service.course.service.CourseSeriesSettingService;
import com.ssj.service.course.service.ICSDetailService;
import org.springframework.beans.factory.annotation.Autowired;
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:35:15 
 * 类说明 
 */
@Transactional
@Service
public class CourseSeriesSettingServiceImpl  extends BaseServiceImpl<CourseSeriesSetting, String> implements  CourseSeriesSettingService {
    @Autowired
	private CourseSeriesSettingDao  dao;
    @Autowired
    private CourseSeriesJoinService  courseSeriesJoinService;
	@Autowired
	private  ICSDetailService  cSDetailService;
	@Override
	public PagingAndSortingRepository<CourseSeriesSetting, String> getDao() {
		return dao;
	}
	@Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
	public List<CourseSeriesSetting> fingByCourseSeriesIdAndLibId(
			String courseSeriesId, String libId) {
		return dao.fingByCourseSeriesIdAndLibId(courseSeriesId, libId);
	}
	@Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
	public CourseSeriesSettingRes findSettingByLibId(String courseSeriesId,
			String libId) {
		CourseSeriesSettingRes res = new  CourseSeriesSettingRes();
		List<CourseSeriesSetting> list =this.fingByCourseSeriesIdAndLibId(courseSeriesId, libId);
		 List<String> urlList = new ArrayList<>();
	        list.forEach(entity -> {
	            if(StringUtil.isNotBlank(entity.getTeacherId())){
	                urlList.add(entity.getTeacherId());
	            }
	            res.setCourseSeriesId(courseSeriesId);
	            res.setDays(entity.getDays());
	            res.setLibId(libId);
	            res.setStartDate(DateHelper.format(entity.getOpenTime(), "yyyy-MM-dd"));
	            res.setPrice(entity.getPrice());
	            if(StringUtil.isNotBlank(entity.getWeeks())){
	            	res.setWeeks(entity.getWeeks().split(","));
	            }
	        });
	        res.setTeacherIds(urlList);
		return res;
	}
	@Override
	public void saveCousreSeriesSetting(CourseSettingSave req) {
		dao.deleteByByCourseSeriesIdAndLibId(req.getCourseSeriesId(), req.getLibId());
		List<String> teacherIds  = req.getTeacherIds();
		Date openTime = DateHelper.parseDate(req.getStartDate(), "yyyy-MM-dd");
		Date startTime = openTime;
		
		List<CourseSeriesDetail> list =cSDetailService.findBySeriesId(req.getCourseSeriesId());
		List<String> weeks =req.getWeeks();
		Collections.sort(weeks);
		
		int day = DateHelper.getday(openTime)-1	;//周四
		// 计算今天是周几，  看是否有提交的 周几上课 
		Integer few =-1;
    	if(few==-1){
    		for (int j = 0; j < weeks.size(); j++) {
    			 few=	Integer.parseInt(weeks.get(j))-day>=0?j:-1;
    			 if(few>-1){
    				 break;
    			 }
    		}
    	}
    	if(few ==-1)few =0;
    	Integer we =Integer.parseInt(weeks.get(few));//第一个
    	Integer oldwe =day;
		
		StringBuffer  stringbuff =new StringBuffer();
		for (int i = 0; i < list.size(); i++) {
			if(weeks.size()==1){
				if(i==0){
					openTime=DateHelper.getNextDay(openTime,(we-oldwe>0?we-oldwe:we-oldwe+7));
				}else{
					openTime=DateHelper.getNextDay(openTime,(we+7-oldwe));
				}

			}else{
				openTime=DateHelper.getNextDay(openTime, we >=oldwe ? (we-oldwe) :(we+7-oldwe));
			}
			stringbuff.append(DateHelper.format(openTime,"yyyy-MM-dd"));
			if(i<list.size()-1){
				stringbuff.append(",");
			}
			courseSeriesJoinService.updateJoinDate(list.get(i).getId(),  req.getLibId(), list.get(i).getCourseIndex(), openTime);
			oldwe =we;
			few ++;
			few=few %weeks.size();
			we =Integer.parseInt(weeks.get(few));
		}
		
		for (String string : teacherIds) {
			CourseSeriesSetting  setting = new  CourseSeriesSetting();
			setting.setCourseSeriesId(req.getCourseSeriesId());
			setting.setLibId(req.getLibId());
			setting.setDays(req.getDays());
			setting.setOpenTime(startTime);
			setting.setPrice(req.getPrice());
			setting.setTeacherId(string);
			setting.setEndTime(openTime);
			setting.setWeeks(String.join(",",weeks));
			setting.setCourseSize(list.size());
			setting.setCourseDate(stringbuff.toString());
			this.save(setting);
			
		}
		//修改课程最后时间以及课程数
	}
	
	
	
	@Override
	public void saveCousreSeriesSetting() {
		List<CourseSeriesSetting> listse =this.findAll();
		for (CourseSeriesSetting req : listse) {
			Date openTime = req.getOpenTime();
			List<CourseSeriesDetail> list =cSDetailService.findBySeriesId(req.getCourseSeriesId());
			if(StringUtil.isEmpty(req.getWeeks())){
				continue;
			}
			List<String> weeks =Arrays.asList(req.getWeeks().split(","));
			Collections.sort(weeks);
			
			int day = DateHelper.getday(openTime)-1	;//周四
			// 计算今天是周几，  看是否有提交的 周几上课 
			Integer few =-1;
			if(few==-1){
				for (int j = 0; j < weeks.size(); j++) {
					few=	Integer.parseInt(weeks.get(j))-day>=0?j:-1;
					if(few>-1){
						break;
					}
				}
			}
			if(few ==-1)few =0;
			Integer we =Integer.parseInt(weeks.get(few));//第一个
			Integer oldwe =day;
			List<String> vipIds=courseSeriesJoinService.findByVipIdAndCourseSeriesIdAndLibId(req.getLibId(), req.getCourseSeriesId());
			StringBuffer  stringbuff =new StringBuffer();
			for (int i = 0; i < list.size(); i++) {
				openTime=DateHelper.getNextDay(openTime, we >=oldwe ? (we-oldwe) :(we+7-oldwe));
				stringbuff.append(DateHelper.format(openTime,"yyyy-MM-dd"));
				if(i<list.size()-1){
					stringbuff.append(",");
				}
				courseSeriesJoinService.saveOrUpdateJoinDate(list.get(i).getId(),  req.getLibId(), list.get(i).getCourseIndex(), openTime,vipIds,req.getCourseSeriesId());
				oldwe =we;
				few ++;
				few=few %weeks.size();
				we =Integer.parseInt(weeks.get(few));
			}
			
		}
		//修改课程最后时间以及课程数
	}
	@Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
	public CourseSeriesSetting fingByCourseSeriesIdAndLibIdLimit(
			String courseSeriesId, String libId) {
		return dao.fingByCourseSeriesIdAndLibIdLimit(courseSeriesId, libId);
	}
	@Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
	public CourseSeriesSetting findSetByUserIdAndLibId(String userId, String courseSeriesId, String libId) {
		
		return dao.findSetByUserIdAndLibId(userId,courseSeriesId,libId);
	}
	@Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
	public int findTeacherHasLesson(String timesNow, String libId, String userId) {
		
		return dao.findTeacherHasLesson(timesNow,libId,userId);
	}
	@Override
	public void updateSettingOneDay(String libId, String newTime, String seriesId,Date openTime) {
		dao.updateSettingOneDay(libId,newTime,seriesId,openTime);
	}


}
