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

import com.ym.mec.biz.dal.dao.PracticeGroupDao;
import com.ym.mec.biz.dal.dao.TeacherCourseRewardDao;
import com.ym.mec.biz.dal.dao.TeacherDao;
import com.ym.mec.biz.dal.dto.TeacherCourseSalaryDetail4WebDto;
import com.ym.mec.biz.dal.entity.CourseSchedule;
import com.ym.mec.biz.dal.entity.PracticeGroup;
import com.ym.mec.biz.dal.entity.Teacher;
import com.ym.mec.biz.dal.entity.TeacherCourseReward;
import com.ym.mec.biz.dal.enums.GroupType;
import com.ym.mec.biz.dal.page.CourseSalaryQueryInfo4Web;
import com.ym.mec.biz.service.TeacherCourseRewardService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.util.collection.MapUtil;
import com.ym.mec.util.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class TeacherCourseRewardServiceImpl extends BaseServiceImpl<Long, TeacherCourseReward> implements TeacherCourseRewardService {

    @Autowired
    private TeacherCourseRewardDao teacherCourseRewardDao;
    @Autowired
    private PracticeGroupDao practiceGroupDao;
    @Autowired
    private TeacherDao teacherDao;

    private final static Set<Integer> SPECIAL_ORGAN_IDS = new HashSet<>(Arrays.asList(new Integer[]{15, 16}));

    @Override
    public BaseDAO<Long, TeacherCourseReward> getDAO() {
        return teacherCourseRewardDao;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
    public void addConvertReward(Integer studentId, Integer teacherId) {
        List<CourseSchedule> studentAndTeacherTrialPractices = practiceGroupDao.findStudentAndTeacherTrialPractices(studentId, teacherId);
        if (CollectionUtils.isEmpty(studentAndTeacherTrialPractices)) {
            return;
        }
        studentAndTeacherTrialPractices.sort(Comparator.comparing(CourseSchedule::getStartClassTime));

        Date now = new Date();
        if (DateUtil.daysBetween(studentAndTeacherTrialPractices.get(studentAndTeacherTrialPractices.size() - 1).getEndClassTime(), now) > 7) {
            return;
        }

        TeacherCourseReward teacherCourseRewardWithGroup = teacherCourseRewardDao.findTeacherCourseRewardWithGroup(teacherId, studentAndTeacherTrialPractices.get(0).getMusicGroupId(), studentAndTeacherTrialPractices.get(0).getGroupType());
        if (Objects.nonNull(teacherCourseRewardWithGroup)) {
            return;
        }
        PracticeGroup practiceGroup = practiceGroupDao.get(Long.valueOf(studentAndTeacherTrialPractices.get(0).getMusicGroupId()));
        Teacher teacher = teacherDao.get(teacherId);
        BigDecimal rewardMoney;
        if (SPECIAL_ORGAN_IDS.contains(teacher.getTeacherOrganId())) {
            rewardMoney = new BigDecimal(40);
        } else {
            rewardMoney = new BigDecimal(30);
        }
        rewardMoney = rewardMoney.multiply(new BigDecimal(studentAndTeacherTrialPractices.size()));
        TeacherCourseReward teacherCourseReward = new TeacherCourseReward();
        teacherCourseReward.setMusicGroupId(practiceGroup.getId().toString());
        teacherCourseReward.setGroupType(GroupType.PRACTICE.getCode());
        String courseScheduleIdList = StringUtils.join(studentAndTeacherTrialPractices.stream().map(CourseSchedule::getId).collect(Collectors.toList()), ",");
        teacherCourseReward.setCourseScheduleIdList(courseScheduleIdList);
        teacherCourseReward.setCourseGroupName(practiceGroup.getName());
        teacherCourseReward.setOrganId(practiceGroup.getOrganId());
        teacherCourseReward.setTeacherId(teacherId);
        teacherCourseReward.setExpectRewardAmount(rewardMoney);
        teacherCourseReward.setCreateTime(now);
        teacherCourseReward.setUpdateTime(now);
        teacherCourseRewardDao.insert(teacherCourseReward);
    }

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

        List<TeacherCourseSalaryDetail4WebDto> dataList = new ArrayList<>();
        int count = teacherCourseRewardDao.countTeacherCourseRewards(params);
        if (count > 0) {
            pageInfo.setTotal(count);
            params.put("offset", pageInfo.getOffset());
            List<TeacherCourseReward> teacherCourseRewards = teacherCourseRewardDao.findTeacherCourseRewards(params);
            for (TeacherCourseReward teacherCourseReward : teacherCourseRewards) {
                TeacherCourseSalaryDetail4WebDto t = new TeacherCourseSalaryDetail4WebDto();
                t.setCourseName(teacherCourseReward.getCourseGroupName());
                t.setCourseTimes(teacherCourseReward.getCourseScheduleIdList().split(",").length);
                t.setMemo(teacherCourseReward.getMemo());
                t.setActualSalary(teacherCourseReward.getExpectRewardAmount());
                t.setReduceSalary(teacherCourseReward.getExpectRewardAmount().subtract(teacherCourseReward.getActualRewardAmount()));
                t.setFinalSalary(t.getActualSalary().subtract(t.getReduceSalary()));
                dataList.add(t);
            }
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }

    @Override
    public List<TeacherCourseReward> findBySettlementStatus(int settlementStatus) {
        return teacherCourseRewardDao.findBySettlementStatus(settlementStatus);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchUpdate(List<TeacherCourseReward> teacherCourseRewards) {
        teacherCourseRewardDao.batchUpdate(teacherCourseRewards);
    }
}
