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

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ym.mec.biz.dal.dao.ClassGroupStudentMapperDao;
import com.ym.mec.biz.dal.dao.CourseScheduleTeacherSalaryDao;
import com.ym.mec.biz.dal.dao.MusicGroupDao;
import com.ym.mec.biz.dal.dao.TeacherDefaultMusicGroupSalaryDao;
import com.ym.mec.biz.dal.entity.CourseSchedule.CourseScheduleType;
import com.ym.mec.biz.dal.entity.CourseScheduleTeacherSalary;
import com.ym.mec.biz.dal.entity.MusicGroup;
import com.ym.mec.biz.dal.entity.TeacherDefaultMusicGroupSalary;
import com.ym.mec.biz.dal.enums.SalarySettlementTypeEnum;
import com.ym.mec.biz.dal.enums.TeachTypeEnum;
import com.ym.mec.biz.service.TeacherDefaultMusicGroupSalaryService;
import com.ym.mec.common.constant.CommonConstants;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.util.date.DateUtil;

@Service
public class TeacherDefaultMusicGroupSalaryServiceImpl extends BaseServiceImpl<Long, TeacherDefaultMusicGroupSalary> implements
		TeacherDefaultMusicGroupSalaryService {

	@Autowired
	private TeacherDefaultMusicGroupSalaryDao teacherDefaultMusicGroupSalaryDao;

	@Autowired
	private CourseScheduleTeacherSalaryDao courseScheduleTeacherSalaryDao;
	
	@Autowired
	private ClassGroupStudentMapperDao classGroupStudentMapperDao;

	@Autowired
	private MusicGroupDao musicGroupDao;

	@Override
	public BaseDAO<Long, TeacherDefaultMusicGroupSalary> getDAO() {
		return teacherDefaultMusicGroupSalaryDao;
	}

	@Override
	public List<TeacherDefaultMusicGroupSalary> getTeacherSalaryByUserIdAndType(int userId, String classGroupType, SalarySettlementTypeEnum settlementType) {
		return teacherDefaultMusicGroupSalaryDao.getTeacherSalaryByUserIdAndType(userId, classGroupType);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void batchUpset(List<TeacherDefaultMusicGroupSalary> salaries, Date startDate) {
		if (salaries != null && salaries.size() > 0) {
			TeacherDefaultMusicGroupSalary salary = salaries.get(0);
			Integer userId = salary.getUserId();
			// 获取老师默认乐团课课酬
			/*List<TeacherDefaultMusicGroupSalary> origSalaryList = teacherDefaultMusicGroupSalaryDao.getTeacherSalaryByUserIdAndType(userId, null);

			Map<CourseScheduleType, TeacherDefaultMusicGroupSalary> map = new HashMap<CourseScheduleType, TeacherDefaultMusicGroupSalary>();
			if (origSalaryList != null && origSalaryList.size() > 0) {
				for (TeacherDefaultMusicGroupSalary ms : origSalaryList) {
					map.put(ms.getCourseScheduleType(), ms);
				}
			}*/

			Map<CourseScheduleType, TeacherDefaultMusicGroupSalary> salaryMap = new HashMap<CourseScheduleType, TeacherDefaultMusicGroupSalary>();
			for (TeacherDefaultMusicGroupSalary ms : salaries) {
				// 修改了哪些课酬
				/*TeacherDefaultMusicGroupSalary oldMS = map.get(ms.getCourseScheduleType());

				if (oldMS == null || oldMS.getAssistantTeacher30MinSalary() == null || oldMS.getMainTeacher30MinSalary() == null
						|| oldMS.getAssistantTeacher90MinSalary() == null || oldMS.getMainTeacher90MinSalary() == null
						|| oldMS.getAssistantTeacher30MinSalary().doubleValue() != ms.getAssistantTeacher30MinSalary().doubleValue()
						|| oldMS.getMainTeacher30MinSalary().doubleValue() != ms.getMainTeacher30MinSalary().doubleValue()
						|| oldMS.getAssistantTeacher90MinSalary().doubleValue() != ms.getAssistantTeacher90MinSalary().doubleValue()
						|| oldMS.getMainTeacher90MinSalary().doubleValue() != ms.getMainTeacher90MinSalary().doubleValue()) {
					salaryMap.put(ms.getCourseScheduleType(), ms);
				}*/
				salaryMap.put(ms.getCourseScheduleType(), ms);
			}
			
			Map<Integer,Integer> classGroupStudentNumMap = new HashMap<Integer, Integer>();

			if (salaryMap.size() > 0) {

				// 删除当前教师所有的结算类型的数据
				teacherDefaultMusicGroupSalaryDao.delByTeacherId(userId);
				// 批量新增
				teacherDefaultMusicGroupSalaryDao.batchAdd(salaries);

				String typeList = salaryMap.keySet().stream().map(e -> e.getCode()).collect(Collectors.joining(","));
				// 查询所有需要修改的课酬
				List<CourseScheduleTeacherSalary> updateTeacherSalaryList = courseScheduleTeacherSalaryDao.queryUserNoSettlementListByTypeAndStartClassDate(
						userId, typeList, startDate);

				if (updateTeacherSalaryList != null && updateTeacherSalaryList.size() > 0) {
					Set<String> musicGroupIdList = updateTeacherSalaryList.stream().map(ts -> ts.getMusicGroupId()).collect(Collectors.toSet());
					// 查询包含的乐团信息
					Map<String, MusicGroup> musicGroupMap = musicGroupDao.queryListByIds(StringUtils.join(musicGroupIdList, ",")).stream()
							.collect(Collectors.toMap(MusicGroup::getId, mg -> mg));

					List<CourseScheduleTeacherSalary> list = new ArrayList<CourseScheduleTeacherSalary>();
					// 批量修改课程课酬
					for (CourseScheduleTeacherSalary ts : updateTeacherSalaryList) {
						MusicGroup musicGroup = musicGroupMap.get(ts.getMusicGroupId());
						// 课酬结算标准
						if (musicGroup != null) {
							TeacherDefaultMusicGroupSalary tdms = salaryMap.get(ts.getCourseSchedule().getType());
							if (tdms != null) {

								BigDecimal duration = new BigDecimal(DateUtil.minutesBetween(ts.getCourseSchedule().getStartClassTime(), ts.getCourseSchedule()
										.getEndClassTime()));
								int mins = 0;
								if(tdms.getCourseScheduleType() == CourseScheduleType.HIGH_ONLINE || tdms.getCourseScheduleType() == CourseScheduleType.MUSIC_NETWORK) {
									if (!classGroupStudentNumMap.containsKey(ts.getClassGroupId())) {
										// 查询 班级人数
										String[] strs = classGroupStudentMapperDao.findStudentNumByClassGroupId(ts.getClassGroupId());
										classGroupStudentNumMap.put(ts.getClassGroupId(), strs.length);
									}
									String salaryRuleJson = tdms.getSalaryRuleJson();
									if (StringUtils.isNotBlank(salaryRuleJson)) {
										JSONObject obj = JSON.parseObject(salaryRuleJson);
										if(obj == null){
											throw new BizException("课酬设置不完整");
										}
										Integer studentNum = classGroupStudentNumMap.get(ts.getClassGroupId());
										if(studentNum == null || studentNum == 0){
											studentNum = 1;
										}
										ts.setExpectSalary(new BigDecimal(obj.getDouble(studentNum + "")));
										list.add(ts);
									}
									
								} else if (musicGroup.getSettlementType() == SalarySettlementTypeEnum.GRADIENT_SALARY) {// 3.0课酬
									mins = 90;
									// 判断是助教、主教
									if (ts.getTeacherRole() == TeachTypeEnum.BISHOP) {
										if (tdms.getCourseScheduleType() == CourseScheduleType.CLASSROOM || tdms.getCourseScheduleType() == CourseScheduleType.HIGH) {
											ts.setExpectSalary(tdms.getMainTeacher90MinSalary());
										}else{
											ts.setExpectSalary(duration.divide(new BigDecimal(mins), CommonConstants.DECIMAL_PLACE, BigDecimal.ROUND_DOWN).multiply(tdms.getMainTeacher90MinSalary()));
										}
									} else {
										if (tdms.getCourseScheduleType() == CourseScheduleType.CLASSROOM || tdms.getCourseScheduleType() == CourseScheduleType.HIGH) {
											ts.setExpectSalary(tdms.getAssistantTeacher90MinSalary());
										}else{
											ts.setExpectSalary(duration.divide(new BigDecimal(mins), CommonConstants.DECIMAL_PLACE, BigDecimal.ROUND_DOWN).multiply(tdms.getAssistantTeacher90MinSalary()));
										}
									}
									list.add(ts);
								} else if (musicGroup.getSettlementType() == SalarySettlementTypeEnum.TEACHER_DEFAULT) {// 默认课酬
									mins = 30;
									BigDecimal minsDecimal = new BigDecimal(mins);
									// 判断是助教、主教
									if (ts.getTeacherRole() == TeachTypeEnum.BISHOP) {
										if (tdms.getCourseScheduleType() == CourseScheduleType.CLASSROOM || tdms.getCourseScheduleType() == CourseScheduleType.HIGH) {
											ts.setExpectSalary(tdms.getMainTeacher30MinSalary());
										}else{
											ts.setExpectSalary(duration.divide(minsDecimal, CommonConstants.DECIMAL_PLACE, BigDecimal.ROUND_DOWN).multiply(tdms.getMainTeacher30MinSalary()));
										}
									} else {
										if (tdms.getCourseScheduleType() == CourseScheduleType.CLASSROOM || tdms.getCourseScheduleType() == CourseScheduleType.HIGH) {
											ts.setExpectSalary(tdms.getAssistantTeacher30MinSalary());
										}else{
											ts.setExpectSalary(duration.divide(minsDecimal, CommonConstants.DECIMAL_PLACE, BigDecimal.ROUND_DOWN).multiply(tdms.getAssistantTeacher30MinSalary()));
										}
									}
									list.add(ts);
								}
							}
						}
					}
					if (list.size() > 0) {
						courseScheduleTeacherSalaryDao.batchUpdateTeacherExpectSalarys(list);
					}
				}
			}
		}
	}
}