package com.ym.mec.biz.service.impl;

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.*;
import com.ym.mec.biz.dal.dto.DemoGroupApplyDto;
import com.ym.mec.biz.dal.dto.EducationDemoGroupListDto;
import com.ym.mec.biz.dal.entity.*;
import com.ym.mec.biz.dal.enums.ClassGroupStudentStatusEnum;
import com.ym.mec.biz.dal.enums.ClassGroupTypeEnum;
import com.ym.mec.biz.dal.enums.YesOrNoEnum;
import com.ym.mec.biz.dal.page.StudentDemoGroupQueryInfo;
import com.ym.mec.biz.dal.page.TeacherManageDemoGroupQueryInfo;
import com.ym.mec.biz.service.DemoGroupService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.util.collection.MapUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author Joburgess
 */
@Service
public class DemoGroupServiceImpl extends BaseServiceImpl<Long, DemoGroup>  implements DemoGroupService {
	
	@Autowired
	private DemoGroupDao demoGroupDao;
	@Autowired
	private ClassGroupDao classGroupDao;
	@Autowired
	private DemoGroupClassGroupMapperDao demoGroupClassGroupMapperDao;
	@Autowired
	private DemoGroupCoursesPlanDao demoGroupCoursesPlanDao;
	@Autowired
	private CourseScheduleDao courseScheduleDao;
	@Autowired
	private ClassGroupStudentMapperDao classGroupStudentMapperDao;

	@Autowired
	private SysUserFeignService sysUserFeignService;
	@Autowired
	private SubjectDao subjectDao;

	@Override
	public BaseDAO<Long, DemoGroup> getDAO() {
		return demoGroupDao;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public void demoGroupApply(DemoGroupApplyDto demoGroupApplyDto) {
		SysUser user = sysUserFeignService.queryUserInfo();

		if(null!=demoGroupDao.findDemoGroupByTeacherId(user.getId().longValue())){
			throw new BizException("请勿多次创建试听课！");
		}

		demoGroupApplyDto.setUserId(user.getId());
		demoGroupDao.insert(demoGroupApplyDto);
		demoGroupCoursesPlanDao.batchInsertByDates(demoGroupApplyDto.getCourseDates(),
				demoGroupApplyDto.getId(),
				demoGroupApplyDto.getSingleClassMinutes());
	}

	@Override
	public DemoGroup getDemoGroupByTeacherId() {
		SysUser user = sysUserFeignService.queryUserInfo();
		return demoGroupDao.findDemoGroupByTeacherId(user.getId().longValue());
	}

	@Override
	public PageInfo queryStudentDemoGroups(StudentDemoGroupQueryInfo queryInfo) {
		PageInfo pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
		Map<String, Object> params = new HashMap<String, Object>();
		MapUtil.populateMap(params, queryInfo);

		List dataList = null;
		int count = demoGroupDao.countDemoGroupList(params);
		if (count > 0) {
			pageInfo.setTotal(count);
			params.put("offset", pageInfo.getOffset());
			dataList = demoGroupDao.findDemoGroupList(params);
		}
		if (count == 0) {
			dataList = new ArrayList<>();
		}
		pageInfo.setRows(dataList);
		return pageInfo;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public void demoGroupSubscribe(Long demoGroupId,Long coursePlanId) {
		createCourseScheduleAndUpdateOrganId(demoGroupId,coursePlanId);
	}

	/**
	 * @Author: Joburgess
	 * @Date: 2019/9/25
	 * 创建上课计划及跟新所属分部列表
	 */
	public void createCourseScheduleAndUpdateOrganId(Long demoGroupId,Long coursePlanId){
		DemoGroup demoGroup=demoGroupDao.get(demoGroupId);

		DemoGroupCoursesPlan demoGroupCoursesPlan1 = demoGroupCoursesPlanDao.get(coursePlanId);
		if(demoGroupCoursesPlan1.getStatus()==YesOrNoEnum.YES){
			throw new BizException("该时段课程已被预约");
		}

		SysUser user = sysUserFeignService.queryUserInfo();

		//创建班级
		ClassGroup classGroup=new ClassGroup();
		classGroup.setName(demoGroup.getName());
		classGroup.setType(ClassGroupTypeEnum.DEMO);
		classGroup.setDelFlag(YesOrNoEnum.NO);
		classGroupDao.insert(classGroup);

		//创建试听课班级映射
		DemoGroupClassGroupMapper demoGroupClassGroupMapper=new DemoGroupClassGroupMapper();
		demoGroupClassGroupMapper.setDemoGroupId(demoGroup.getId());
		demoGroupClassGroupMapper.setClassGroupId(classGroup.getId());
		demoGroupClassGroupMapperDao.insert(demoGroupClassGroupMapper);

		//创建班级学生映射
		ClassGroupStudentMapper classGroupStudentMapper=new ClassGroupStudentMapper();
		classGroupStudentMapper.setClassGroupId(classGroup.getId());
		classGroupStudentMapper.setUserId(user.getId());
		classGroupStudentMapper.setStatus(ClassGroupStudentStatusEnum.NORMAL);
		classGroupStudentMapperDao.insert(classGroupStudentMapper);

		//创建课程
		DemoGroupCoursesPlan demoGroupCoursesPlan=demoGroupCoursesPlanDao.get(coursePlanId);
//		List<CourseSchedule> courseScheduleByDemoGroup = demoGroupDao.createCourseSchedulesByDemoGroup(
//				demoGroup,
//				demoGroupCoursesPlan.getCoursesStartTime(),
//				classGroup.getId().longValue());
		CourseSchedule courseScheduleByDemoGroup = demoGroupDao.createCourseScheduleByDemoGroupPlan(
				demoGroup,
				coursePlanId,
				classGroup.getId().longValue());
//		String[] classSubjects = courseScheduleDao.findClassSubjects(Arrays.asList(new Integer[]{classGroup.getId()}));
		StringBuilder className=new StringBuilder(subjectDao.get(demoGroup.getSubjectId().intValue()).getName());
		className.append("-");
		className.append(CourseSchedule.CourseScheduleType.DEMO.getMsg());
		courseScheduleByDemoGroup.setName(className.toString());
		ArrayList<CourseSchedule> courseSchedules = new ArrayList<>();
		courseSchedules.add(courseScheduleByDemoGroup);
		courseScheduleDao.batchAddCourseSchedules(courseSchedules);

		//更新所属分部列表
		List<Integer> organIds = demoGroupDao.organIdListByDemoGroupId(demoGroup.getId());
		organIds.add(demoGroupDao.getOrganIdByUserId(demoGroup.getUserId().longValue()));
		HashSet<Integer> hashSet = new HashSet<>(organIds);
		String organIdsString = StringUtils.join(hashSet, ",");
		demoGroup.setOrganIdList(organIdsString);
		demoGroupDao.update(demoGroup);

		//修改课程预约状态
		demoGroupCoursesPlan.setStatus(YesOrNoEnum.YES);
		demoGroupCoursesPlanDao.update(demoGroupCoursesPlan);
	}

	@Override
	public PageInfo findTeacherDemoGroups(TeacherManageDemoGroupQueryInfo queryInfo) {
		PageInfo pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
		Map<String, Object> params = new HashMap<>();
		MapUtil.populateMap(params, queryInfo);

		List dataList = null;
		int count = demoGroupDao.countTeacherDemoGroups(params);
		if (count > 0) {
			pageInfo.setTotal(count);
			params.put("offset", pageInfo.getOffset());
			dataList = demoGroupDao.findTeacherDemoGroups(params);
		}
		if (count == 0) {
			dataList = new ArrayList<>();
		}
		pageInfo.setRows(dataList);
		return pageInfo;
	}

	@Override
	public List<EducationDemoGroupListDto> findDemoGroupStartClassTimesWithWeekByTeacherId(Long teacherID) {
		return demoGroupDao.findDemoGroupStartClassTimesWithWeekByTeacherId(teacherID);
	}
}