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.CourseScheduleTeacherSalaryDao;
import com.ym.mec.biz.dal.dao.TeacherSalaryModifyLogDao;
import com.ym.mec.biz.dal.entity.CourseScheduleTeacherSalary;
import com.ym.mec.biz.dal.entity.TeacherSalaryModifyLog;
import com.ym.mec.biz.service.CourseScheduleTeacherSalaryService;
import com.ym.mec.biz.service.TeacherSalaryModifyLogService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class TeacherSalaryModifyLogServiceImpl extends BaseServiceImpl<Long, TeacherSalaryModifyLog>  implements TeacherSalaryModifyLogService {
	
	@Autowired
	private TeacherSalaryModifyLogDao teacherSalaryModifyLogDao;
	@Autowired
	private CourseScheduleTeacherSalaryDao courseScheduleTeacherSalaryDao;
	@Autowired
	private SysUserFeignService sysUserFeignService;

	@Override
	public BaseDAO<Long, TeacherSalaryModifyLog> getDAO() {
		return teacherSalaryModifyLogDao;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void add(TeacherSalaryModifyLog modifyLog) {
		SysUser sysUser = sysUserFeignService.queryUserInfo();
		if (sysUser == null) {
			throw new BizException("用户信息获取失败");
		}
		//获取之前的课酬信息
		CourseScheduleTeacherSalary salary = courseScheduleTeacherSalaryDao.queryByCourseScheduleIdAndUserId(modifyLog.getCourseScheduleId(), modifyLog.getTeacherId());
		if(modifyLog.getCurrentExpectSalary().compareTo(modifyLog.getCurrentReduceSalary()) < 0){
			throw new BizException("应发金额不应小于扣款金额");
		}
		modifyLog.setPreExpectSalary(salary.getExpectSalary());
		modifyLog.setPreReduceSalary(salary.getReduceSalary());
		modifyLog.setOperatorId(sysUser.getId());
		teacherSalaryModifyLogDao.insert(modifyLog);
		//修改教师课酬
		salary.setExpectSalary(modifyLog.getCurrentExpectSalary());
		salary.setReduceSalary(modifyLog.getCurrentReduceSalary());
		salary.setActualSalary(salary.getExpectSalary().subtract(salary.getReduceSalary()));
		salary.setMemo(modifyLog.getMemo());
		courseScheduleTeacherSalaryDao.update(salary);
	}
}