package com.ym.mec.teacher.controller;

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.StudentAttendanceDao;
import com.ym.mec.biz.dal.dto.StudentAttendanceDto;
import com.ym.mec.biz.dal.dto.TeacherSignOutDto;
import com.ym.mec.biz.dal.entity.CourseSchedule;
import com.ym.mec.biz.dal.entity.MusicGroup;
import com.ym.mec.biz.dal.entity.StudentAttendance;
import com.ym.mec.biz.dal.enums.GroupType;
import com.ym.mec.biz.dal.enums.MessageTypeEnum;
import com.ym.mec.biz.dal.enums.StudentAttendanceStatusEnum;
import com.ym.mec.biz.dal.enums.UpdateAttendanceEnum;
import com.ym.mec.biz.dal.page.TeacherAttendanceQueryInfo;
import com.ym.mec.biz.service.*;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.entity.HttpResponseResult;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.thirdparty.message.MessageSenderPluginContext;
import com.ym.mec.util.date.DateUtil;
import com.yonge.log.model.AuditLogAnnotation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

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

@RequestMapping("teacherAttendance")
@Api(tags = "教师签到服务")
@RestController
public class TeacherAttendanceController extends BaseController {

    @Autowired
    private TeacherAttendanceService teacherAttendanceService;

    @Autowired
    private StudentAttendanceService studentAttendanceService;

    @Autowired
    private StudentAttendanceDao studentAttendanceDao;

    @Autowired
    private ClassGroupService classGroupService;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private SysMessageService sysMessageService;
    @Autowired
    private CourseScheduleService courseScheduleService;
    @Autowired
    private MusicGroupService musicGroupService;

    @ApiOperation(value = "新增教师签到")
    @PostMapping("/add")
    @AuditLogAnnotation(operateName = "新增教师签到")
    public Object add(@RequestBody TeacherSignOutDto teacherSignOutDto) {
        return succeed(teacherAttendanceService.addTeacherAttendanceRecord(teacherSignOutDto));
    }

    @ApiOperation(value = "分页查询教师签到列表")
    @GetMapping("/queryPage")
    public Object queryPage(TeacherAttendanceQueryInfo queryInfo) {
        return succeed(teacherAttendanceService.queryPage(queryInfo));
    }
    
    @ApiOperation(value = "根据班级ID获取当前课程的学生")
    @GetMapping("/getCurrentCourseStudents")
    public Object getCurrentCourseStudents(Long courseScheduleId){
        return succeed(classGroupService.findAttendanceStudentByCourse(courseScheduleId));
    }

    @ApiOperation(value = "点名")
    @PostMapping("/addStudentAttendances")
    @AuditLogAnnotation(operateName = "点名")
    public Object addStudentAttendances(@RequestBody StudentAttendanceDto studentAttendanceInfo){
        return succeed(studentAttendanceService.addStudentAttendances(studentAttendanceInfo));
    }

    @ApiOperation(value = "学员到课提醒")
    @PostMapping("/studentAttendanceNormalRemind")
    public HttpResponseResult studentAttendanceNormalRemind(Long courseId){
        int remindNum = studentAttendanceDao.countNormalRemindNum(courseId);
        if(remindNum>0){
            return failed("您已发送过到课提醒");
        }
        CourseSchedule courseSchedule = courseScheduleService.get(courseId);
        //获取正常签到的学生信息
        List<StudentAttendance> studentAttendances = studentAttendanceDao.findByCourseId(courseId);
        if(CollectionUtils.isEmpty(studentAttendances)){
            return succeed();
        }

        List<StudentAttendance> normal = studentAttendances.stream().filter(studentAttendance -> studentAttendance.getStatus() == StudentAttendanceStatusEnum.NORMAL).collect(Collectors.toList());
        //教务推送
        if(Objects.nonNull(courseSchedule)&& GroupType.MUSIC.equals(courseSchedule.getGroupType())){
            MusicGroup musicGroup = musicGroupService.get(courseSchedule.getMusicGroupId());
            if(Objects.isNull(musicGroup)||Objects.isNull(musicGroup.getTransactionTeacherId())){
                return succeed();
            }
            int normalStudentNum = normal.size();
            long leaveStudentNum = studentAttendances.stream().filter(studentAttendance -> studentAttendance.getStatus() == StudentAttendanceStatusEnum.LEAVE).count();
            long truantStudentNum = studentAttendances.stream().filter(studentAttendance -> studentAttendance.getStatus() == StudentAttendanceStatusEnum.TRUANT).count();
            Map<Integer, String> receivers = new HashMap<>();
            receivers.put(musicGroup.getTransactionTeacherId(), musicGroup.getTransactionTeacherId().toString());
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.SYSTEM_PUSH_NAMES_ACHIEVE,
                    receivers, null, 0, null, "SYSTEM", courseSchedule.getName(), normalStudentNum, leaveStudentNum, truantStudentNum);
        }

        if (normal != null && normal.size() > 0) {
            Map<Integer, String> receivers = new HashMap<>();
            normal.forEach(e -> {
                receivers.put(e.getUserId(), e.getUserId().toString());
            });
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.STUDENT_PUSH_NAMES_ACHIEVE,
                    receivers, null, 0, "2", "STUDENT", DateUtil.format(new Date(), DateUtil.DATE_FORMAT_MIN));
        }else{
            return succeed();
        }
        studentAttendanceDao.updateNormalRemind(courseId);
        return succeed();
    }

    @ApiOperation(value = "获取签退详情")
    @GetMapping("/getTeacherSignDetail")
    public Object getTeacherSignDetail(Integer courseScheduleId){
        SysUser user = sysUserFeignService.queryUserInfo();
        if(Objects.isNull(user)){
            return failed(HttpStatus.FORBIDDEN,"请登录");
        }
        return succeed(teacherAttendanceService.getTeacherSignDetail(courseScheduleId, user.getId()));
    }

    @ApiOperation(value = "提交考勤申述")
    @PostMapping("/addComplaints")
    public Object addComplaints(Long courseScheduleId, String content, String url, UpdateAttendanceEnum complaintsType){
        SysUser user = sysUserFeignService.queryUserInfo();
        if(Objects.isNull(user)){
            throw new BizException("请登录");
        }
        teacherAttendanceService.addComplaints(courseScheduleId,content,url,user.getId(),complaintsType);
        return succeed();
    }

    @ApiOperation(value = "撤销考勤申述")
    @PostMapping("/repealComplaints")
    public Object repealComplaints(Long courseScheduleId){
        SysUser user = sysUserFeignService.queryUserInfo();
        if(Objects.isNull(user)){
            throw new BizException("请登录");
        }
        teacherAttendanceService.repealComplaints(courseScheduleId,user.getId());
        return succeed();
    }
}
