package com.ruoyi.school.course.service;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.page.RespPage;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.core.api.APIResponse;
import com.ruoyi.core.api.ApiResEnums;
import com.ruoyi.school.course.domain.*;
import com.ruoyi.school.course.domain.req.time.ReqSearchScClaTimeRule;
import com.ruoyi.school.course.domain.resp.time.RespClaTimeRule;
import com.ruoyi.school.course.mapper.ScClaTimeRuleMapper;
import com.ruoyi.school.room.domain.ScRoom;
import com.ruoyi.school.room.service.IScRoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ：zhangbaoyu
 * @date ：Created in 2020/9/18 15:38
 */
@Service
@Transactional
public class BusinessClaTimeRuleService {

    @Autowired
    private IScClaTimeService claTimeService;
    @Autowired
    private IScClaTimeRuleService claTimeRuleService;
    @Autowired
    private ScClaTimeRuleMapper claTimeRuleMapper;
    @Autowired
    private IScRoomService roomService;

    /**
     * 查询
     *
     * @param reqSearchScClaTimeRule
     * @return
     */
    public APIResponse searchList(ReqSearchScClaTimeRule reqSearchScClaTimeRule) {
        RespPage<RespClaTimeRule> respPage = new RespPage<>(reqSearchScClaTimeRule.getPageNum(),reqSearchScClaTimeRule.getPageSize());
        List<RespClaTimeRule> claTimeRuleList = claTimeRuleMapper.selectByCondition(reqSearchScClaTimeRule, respPage);
        respPage.setRows(claTimeRuleList);
        return APIResponse.toAPIResponse(respPage);
    }

    /**
     * 添加
     *
     * @param claTimeRule
     * @return
     */
    @Transactional
    public APIResponse addClaTimeRule(ScClaTimeRule claTimeRule) {

        if (!claTimeRule.checkParam()) {
            return APIResponse.toExceptionResponse(ApiResEnums.PARAM_FAIL);
        }
        // 教室
        if(null != claTimeRule.getRoomId()) {
            ScRoom room = roomService.getById(claTimeRule.getRoomId());
            claTimeRule.setRoomName(room.getRoomName());
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        claTimeRule.setCreateUser(loginUser.getUserId());
        claTimeRule.setCreateTime(new Date());
        claTimeRuleService.save(claTimeRule);
        saveBatchClaTime(claTimeRule);
        return APIResponse.toOkResponse();
    }

    /**
     * 详情
     *
     * @param ruleId
     * @return
     */
    public APIResponse detailById(Long ruleId) {
        if (null == ruleId) {
            return APIResponse.toAPIResponse(null);
        }
        ScClaTimeRule claTimeRule = claTimeRuleService.getById(ruleId);
        ScClaTimeRuleVo scClaTimeRuleVo = new ScClaTimeRuleVo();
        BeanUtil.copyProperties(claTimeRule,scClaTimeRuleVo);
        // 设置deptId
        scClaTimeRuleVo.setDeptId(claTimeRule.getDeptId());

        return APIResponse.toAPIResponse(scClaTimeRuleVo);
    }


    /**
     * 更新
     *
     * @param claTimeRule
     * @return
     */
    @Transactional
    public APIResponse updateClaTimeRule(ScClaTimeRule claTimeRule) {
        if (null == claTimeRule.getRuleId()) {
            return APIResponse.toExceptionResponse(ApiResEnums.PARAM_FAIL);
        }
        if (!claTimeRule.checkParam()) {
            return APIResponse.toExceptionResponse(ApiResEnums.PARAM_FAIL);
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Integer bookCount= claTimeService.selectBookCount(claTimeRule.getRuleId(), null);
        if(bookCount.intValue()>0){
            return APIResponse.toExceptionResponse("无法修改：相关课表中有会员预约！");
        }
        // 教室
        if(null != claTimeRule.getRoomId()) {
            ScRoom room = roomService.getById(claTimeRule.getRoomId());
            claTimeRule.setRoomName(room.getRoomName());
        }

        claTimeRule.setLastUpdateUser(loginUser.getUserId());
        claTimeRule.setLastUpdateTime(new Date());

        boolean updateScCourseType = claTimeRuleService.updateById(claTimeRule);
        claTimeService.deleteUnBeginTime(claTimeRule.getRuleId(), loginUser.getNowTenantId());

        saveBatchClaTime(claTimeRule);
        return APIResponse.toOkResponse();
    }

    /**
     * 删除
     *
     * @param ruleId
     * @return
     */
    @Transactional
    public APIResponse deleteById(Long ruleId) {
        if (null == ruleId) {
            return APIResponse.toExceptionResponse(ApiResEnums.FAIL_WAIT_A_MINUTE);
        }
        ScClaTimeRule claTimeRule = claTimeRuleService.getById(ruleId);

        //是否有会员预约
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Integer bookCount= claTimeService.selectBookCount(claTimeRule.getRuleId(), null);
        if(bookCount.intValue()>0){
            return APIResponse.toExceptionResponse("无法删除：相关课表中有会员预约！");

        }

        claTimeRuleService.removeById(ruleId);

        claTimeService.deleteUnBeginTime(claTimeRule.getRuleId(), loginUser.getNowTenantId());

        return APIResponse.toOkResponse();
    }

    @Autowired
    private IScCourseService courseService;
    /**
     * 保存 具体上课日期
     *
     * @param claTimeRule
     */
    private void saveBatchClaTime(ScClaTimeRule claTimeRule) {

        ScCourse course=courseService.getById(claTimeRule.getCourseId());


        List<RespClaTimeRule> claTimeList = claTimeRuleService.getClaTimeListByRule(claTimeRule, null);

        List<ScClaTime> timeList = claTimeList.stream().map(item -> {
            if (
            claTimeService.checkTeacherConflict(claTimeRule.getTeacherId(), item.getClaDate(), item.getClaTimeBegin(), item.getClaTimeEnd(), null)
            ||
            claTimeService.checkClassroomConflict(claTimeRule.getRoomId(), item.getClaDate(), item.getClaTimeBegin(), item.getClaTimeEnd(), null)
          ){
                throw new RuntimeException("存在教师或教室冲突，请重新选择上课时间");
            }
            ScClaTime claTime = new ScClaTime();
            claTime.setRuleId(claTimeRule.getRuleId());
            claTime.setCourseId(claTimeRule.getCourseId());
            claTime.setDeptId(claTimeRule.getDeptId());
            claTime.setClaDate(item.getClaDate());
            claTime.setStartTime(item.getClaTimeBegin());
            claTime.setEndTime(item.getClaTimeEnd());
            claTime.setClaDuration(claTimeRule.getClaDuration());
            claTime.setAtClassCnt(claTimeRule.getAtClassCnt());
            claTime.setLessCnt(claTimeRule.getLessCnt());
            claTime.setTeacherFee(course.getClaFee());
            claTime.setClaColor(claTimeRule.getClaColor());
            claTime.setFontSize(claTimeRule.getFontSize());
            claTime.setFontColor(claTimeRule.getFontColor());
            // 排课
            claTime.setSource("1");
            // 待上课
            claTime.setStatus("1");
            claTime.setRoomId(claTimeRule.getRoomId());
            claTime.setRoomName(claTimeRule.getRoomName());
            claTime.setClassTheme(claTimeRule.getClassTheme());
            claTime.setTeacherId(claTimeRule.getTeacherId());
            claTime.setCreateUser(claTimeRule.getCreateUser());
            claTime.setTenantId(course.getTenantId());
            return claTime;
        }).collect(Collectors.toList());
        claTimeService.saveBatch(timeList);
    }


}
