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.Objects;
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.Transactional;

import com.alibaba.fastjson.JSON;
import com.ym.mec.biz.dal.dao.CourseScheduleTeacherSalaryDao;
import com.ym.mec.biz.dal.dao.TeacherDao;
import com.ym.mec.biz.dal.dao.TeacherDefaultVipGroupSalaryDao;
import com.ym.mec.biz.dal.dao.VipGroupActivityDao;
import com.ym.mec.biz.dal.dao.VipGroupDao;
import com.ym.mec.biz.dal.dto.VipGroupSalarySettlementDto;
import com.ym.mec.biz.dal.entity.CourseSchedule.CourseScheduleType;
import com.ym.mec.biz.dal.entity.CourseScheduleTeacherSalary;
import com.ym.mec.biz.dal.entity.Teacher;
import com.ym.mec.biz.dal.entity.TeacherDefaultVipGroupSalary;
import com.ym.mec.biz.dal.entity.VipGroup;
import com.ym.mec.biz.dal.entity.VipGroupActivity;
import com.ym.mec.biz.dal.enums.JobNatureEnum;
import com.ym.mec.biz.dal.enums.SalarySettlementTypeEnum;
import com.ym.mec.biz.dal.enums.TeachModeEnum;
import com.ym.mec.biz.service.TeacherDefaultVipGroupSalaryService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.service.impl.BaseServiceImpl;

@Service
public class TeacherDefaultVipGroupSalaryServiceImpl extends BaseServiceImpl<Long, TeacherDefaultVipGroupSalary> implements TeacherDefaultVipGroupSalaryService {

	@Autowired
	private TeacherDefaultVipGroupSalaryDao teacherDefaultVipGroupSalaryDao;

	@Autowired
	private CourseScheduleTeacherSalaryDao courseScheduleTeacherSalaryDao;

	@Autowired
	private VipGroupDao vipGroupDao;

	@Autowired
	private VipGroupActivityDao vipGroupActivityDao;
	
	@Autowired
	private TeacherDao teacherDao;

	@Override
	public BaseDAO<Long, TeacherDefaultVipGroupSalary> getDAO() {
		return teacherDefaultVipGroupSalaryDao;
	}

	@Override
	public TeacherDefaultVipGroupSalary findByTeacherAndCategory(Integer userId, Integer categoryId) {
		TeacherDefaultVipGroupSalary byTeacherAndCategory = teacherDefaultVipGroupSalaryDao.findByTeacherAndCategory(userId, categoryId);
		if (Objects.isNull(byTeacherAndCategory)) {
			byTeacherAndCategory = new TeacherDefaultVipGroupSalary();
			byTeacherAndCategory.setOfflineClassesSalary(new BigDecimal(0));
			byTeacherAndCategory.setOnlineClassesSalary(new BigDecimal(0));
		}
		return byTeacherAndCategory;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void upSet(List<TeacherDefaultVipGroupSalary> teacherDefaultVipGroupSalaries, Date startDate) {
		if (teacherDefaultVipGroupSalaries != null && teacherDefaultVipGroupSalaries.size() > 0) {

			TeacherDefaultVipGroupSalary salary = teacherDefaultVipGroupSalaries.get(0);
			Integer userId = salary.getUserId();
			Teacher teacher = teacherDao.get(userId);
			if(teacher == null){
				throw new BizException("老师信息在系统中找不到");
			}
			// 获取老师默认VIP课课酬
			List<TeacherDefaultVipGroupSalary> origSalaryList = teacherDefaultVipGroupSalaryDao.queryByUserId(userId);

			Map<Integer, TeacherDefaultVipGroupSalary> map = new HashMap<Integer, TeacherDefaultVipGroupSalary>();
			if (origSalaryList != null && origSalaryList.size() > 0) {
				for (TeacherDefaultVipGroupSalary ms : origSalaryList) {
					map.put(ms.getVipGroupCategoryId(), ms);
				}
			}

			Map<Integer, TeacherDefaultVipGroupSalary> salaryMap = new HashMap<Integer, TeacherDefaultVipGroupSalary>();
			for (TeacherDefaultVipGroupSalary ms : teacherDefaultVipGroupSalaries) {
				// 修改了哪些课酬
				/*TeacherDefaultVipGroupSalary oldMS = map.get(ms.getVipGroupCategoryId());

				if (oldMS == null || oldMS.getOfflineClassesSalary() == null
						|| oldMS.getOfflineClassesSalary().doubleValue() != ms.getOfflineClassesSalary().doubleValue()
						|| oldMS.getOnlineClassesSalary() == null || oldMS.getOnlineClassesSalary().doubleValue() != ms.getOnlineClassesSalary().doubleValue()) {
					salaryMap.put(ms.getVipGroupCategoryId(), ms);
				}*/
				if(teacher.getJobNature() == JobNatureEnum.FULL_TIME){
					ms.setOnlineClassesSalary(new BigDecimal(0));
				}
				salaryMap.put(ms.getVipGroupCategoryId(), ms);
			}

			if (salaryMap.size() > 0) {

				// 根据教师编号删除
				teacherDefaultVipGroupSalaryDao.delByTeacherId(salary.getUserId());
				// 新增
				teacherDefaultVipGroupSalaryDao.batchAdd(teacherDefaultVipGroupSalaries);

				String typeList = CourseScheduleType.VIP.getCode();
				// 查询所有需要修改的课酬
				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());
					// 查询包含的VIP信息
					List<VipGroup> vipGroupList = vipGroupDao.queryByIds(StringUtils.join(musicGroupIdList, ","));
					if (vipGroupList == null || vipGroupList.size() == 0) {
						return;
					}

					Map<Long, VipGroup> vipGroupMap = vipGroupList.stream().collect(Collectors.toMap(VipGroup::getId, mg -> mg));

					// 查询活动
					Map<Integer, VipGroupActivity> vipGroupActivityMap = vipGroupActivityDao
							.queryByIds(StringUtils.join(vipGroupList.stream().map(vg -> vg.getVipGroupActivityId()).collect(Collectors.toList()), ","))
							.stream().collect(Collectors.toMap(VipGroupActivity::getId, va -> va));

					// 批量修改课程课酬
					List<CourseScheduleTeacherSalary> list = new ArrayList<CourseScheduleTeacherSalary>();

					for (CourseScheduleTeacherSalary ts : updateTeacherSalaryList) {
						VipGroup vipGroup = vipGroupMap.get(Long.parseLong(ts.getMusicGroupId()));
						// 课酬结算标准
						if (vipGroup != null) {

							VipGroupActivity vipGroupActivity = vipGroupActivityMap.get(vipGroup.getVipGroupActivityId());
							if (vipGroupActivity == null) {
								continue;
							}

							VipGroupSalarySettlementDto vipGroupSalarySettlementDto = JSON.parseObject(vipGroupActivity.getSalarySettlementJson(),
									VipGroupSalarySettlementDto.class);

							if (vipGroupSalarySettlementDto == null) {
								continue;
							}

							TeacherDefaultVipGroupSalary tdms = salaryMap.get(vipGroup.getVipGroupCategoryId());
							TeacherDefaultVipGroupSalary origTdms = map.get(vipGroup.getVipGroupCategoryId());
							if (tdms != null && origTdms != null) {
								if (vipGroupSalarySettlementDto.getOnlineSalarySettlement() != null
										&& vipGroupSalarySettlementDto.getOnlineSalarySettlement().getSalarySettlementType() == SalarySettlementTypeEnum.TEACHER_DEFAULT
										&& (ts.getCourseSchedule().getTeachMode() == TeachModeEnum.ONLINE)) {// 线上课
									if (teacher.getJobNature() != JobNatureEnum.FULL_TIME
											&& ts.getExpectSalary().compareTo(origTdms.getOfflineClassesSalary()) == 0
											&& tdms.getOfflineClassesSalary().compareTo(origTdms.getOfflineClassesSalary()) != 0) {
										ts.setExpectSalary(tdms.getOfflineClassesSalary());
										list.add(ts);
									}
								} else if (vipGroupSalarySettlementDto.getOfflineSalarySettlement() != null
										&& vipGroupSalarySettlementDto.getOfflineSalarySettlement().getSalarySettlementType() == SalarySettlementTypeEnum.TEACHER_DEFAULT
										&& ts.getCourseSchedule().getTeachMode() == TeachModeEnum.OFFLINE
										&& ts.getExpectSalary().compareTo(origTdms.getOfflineClassesSalary()) == 0
										&& tdms.getOfflineClassesSalary().compareTo(origTdms.getOfflineClassesSalary()) != 0) {// 线下课
									ts.setExpectSalary(tdms.getOfflineClassesSalary());
									list.add(ts);
								}
							}
						}
					}
					if (list.size() > 0) {
						courseScheduleTeacherSalaryDao.batchUpdateTeacherExpectSalarys(list);
					}
				}
			}
		}
	}
}
