package com.xjrsoft.module.attendance.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.xjrsoft.common.enums.OutInStatusEnum;
import com.xjrsoft.common.model.result.RT;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.module.attendance.dto.TeacherDetailsDto;
import com.xjrsoft.module.attendance.entity.AttendanceUserRelation;
import com.xjrsoft.module.attendance.service.IAttendanceRuleCategoryService;
import com.xjrsoft.module.attendance.vo.AttendanceRuleDetailsUserVo;
import com.xjrsoft.module.attendance.vo.TeacherStatisticsPageVo;
import com.xjrsoft.module.holiday.entity.HolidayDate;
import com.xjrsoft.module.holiday.service.IHolidayDateService;
import com.xjrsoft.module.organization.entity.Department;
import com.xjrsoft.module.organization.entity.User;
import com.xjrsoft.module.organization.entity.UserDeptRelation;
import com.xjrsoft.module.organization.service.IUserService;
import com.xjrsoft.module.outint.dto.TeacherOutInRecordDto;
import com.xjrsoft.module.outint.entity.CarOutInRecord;
import com.xjrsoft.module.outint.entity.TeacherOutInRecord;
import com.xjrsoft.module.outint.service.ICarOutInRecordService;
import com.xjrsoft.module.outint.service.ITeacherOutInRecordService;
import com.xjrsoft.module.personnel.entity.CarMessageApply;
import com.xjrsoft.module.teacher.entity.BaseTeacher;
import com.xjrsoft.module.teacher.entity.WfHeadTeacherLeave;
import com.xjrsoft.module.teacher.entity.WfTeacherleave;
import com.xjrsoft.module.teacher.entity.XjrUser;
import com.xjrsoft.module.teacher.service.IWfHeadTeacherLeaveService;
import com.xjrsoft.module.teacher.service.IWfTeacherleaveService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @title: 教师考勤
* @Author dzx
* @Date: 2024-05-29
* @Version 1.0
*/
@RestController
@RequestMapping("/teacherStatistics")
@Api(value = "/teacherStatistics" ,tags = "教师考勤统计")
@AllArgsConstructor
public class TeacherStatisticsController {


    private final IUserService xjrUserService;
    private final ITeacherOutInRecordService teacherOutInRecordService;
    private final IWfTeacherleaveService wfTeacherleaveService;
    private final IHolidayDateService holidayDateService;
    private final IWfHeadTeacherLeaveService headTeacherLeaveService;
    private final IAttendanceRuleCategoryService attendanceRuleCategoryService;
    private final ICarOutInRecordService carOutInRecordService;

    @GetMapping(value = "/teacher-details")
    @ApiOperation(value="教师考勤")
    @SaCheckPermission("statistics:detail")
    public RT<PageOutput<TeacherStatisticsPageVo>> teacherDetails(@Valid TeacherDetailsDto dto){
        MPJLambdaWrapper<User> queryUser = new MPJLambdaWrapper<>();
        queryUser.disableSubLogicDel().distinct()
                .eq(ObjectUtil.isNotNull(dto.getDeptId()), UserDeptRelation::getDeptId, dto.getDeptId())
                .eq(StrUtil.isNotEmpty(dto.getAttendanceMode()), AttendanceUserRelation::getAttendanceMode, dto.getAttendanceMode())
                .like(StrUtil.isNotEmpty(dto.getCarNumber()), AttendanceUserRelation::getCarNumber, dto.getCarNumber())
                .like(StrUtil.isNotEmpty(dto.getName()), User::getName, dto.getName())
                .selectAs(User::getName, TeacherStatisticsPageVo::getTeacherName)
                .selectAs(User::getId, TeacherStatisticsPageVo::getUserId)
                .selectAs(User::getMobile, TeacherStatisticsPageVo::getMobile)
                .selectAs(Department::getName, TeacherStatisticsPageVo::getDeptName)
                .innerJoin(BaseTeacher.class, BaseTeacher::getUserId, User::getId)
                .innerJoin(UserDeptRelation.class, UserDeptRelation::getUserId, User::getId)
                .leftJoin(AttendanceUserRelation.class, AttendanceUserRelation::getUserId, User::getId)
                .leftJoin(Department.class, Department::getId, UserDeptRelation::getDeptId);
        IPage<TeacherStatisticsPageVo> voIPage = xjrUserService.selectJoinListPage(ConventPage.getPage(dto), TeacherStatisticsPageVo.class, queryUser);

        if(dto.getDate() != null && !"".equals(dto.getDate())){
            DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE;
            LocalDate queryDate = LocalDate.parse(dto.getDate(), formatter);

            HolidayDate holidayDate = holidayDateService.getOne(
                    new QueryWrapper<HolidayDate>().lambda()
                            .eq(HolidayDate::getDate, queryDate)
            );
            if(holidayDate != null && holidayDate.getWay() != null && holidayDate.getWay() != 0){
                return RT.ok(ConventPage.getPageOutput(voIPage, TeacherStatisticsPageVo.class));
            }

            List<Long> userIds = voIPage.getRecords().stream().map(TeacherStatisticsPageVo::getUserId).collect(Collectors.toList());
            Map<Long, AttendanceRuleDetailsUserVo> teacherTodyRuleByUserId = attendanceRuleCategoryService.getTeacherTodyRuleByUserId(userIds);
            
//            //查询当前时间段存在请假的教师
//            Map<Long, WfTeacherleave> leaveList = wfTeacherleaveService.getLeaveList(startTime, endTime);
//
//            Map<Long, WfHeadTeacherLeave> teacherLeaveMap = headTeacherLeaveService.getLeaveList(startTime, endTime);
//            //查询进入记录
//            List<TeacherOutInRecord> outInRecords = teacherOutInRecordService.list(
//                    new QueryWrapper<TeacherOutInRecord>().lambda()
//                            .between(TeacherOutInRecord::getRecordTime, startTime, endTime)
//                            .eq(TeacherOutInRecord::getStatus, 1)
//                            .orderByAsc(TeacherOutInRecord::getRecordTime)
//            );
//            Map<Long, TeacherOutInRecord> outInMap = new HashMap<>();
//            for (TeacherOutInRecord inRecord : outInRecords) {
//                if(outInMap.containsKey(inRecord.getUserId())){
//                    continue;
//                }
//                outInMap.put(inRecord.getUserId(), inRecord);
//            }
            for (TeacherStatisticsPageVo record : voIPage.getRecords()) {
                LocalDateTime startTime, endTime, amEndTime = null;
                AttendanceRuleDetailsUserVo detailsUserVo = teacherTodyRuleByUserId.get(record.getUserId());
                if(dto.getTimePeriod() == 1){
                    startTime = queryDate.atTime(5, 0, 0);
                    if(detailsUserVo != null && detailsUserVo.getAmStartTime() != null){
                        startTime = queryDate.atTime(detailsUserVo.getAmStartTime());
                    }
                    endTime = queryDate.atTime(12, 0, 0);
                    if(detailsUserVo != null && detailsUserVo.getAmEndTime() != null){
                        endTime = queryDate.atTime(detailsUserVo.getAmEndTime());
                    }
                }else if(dto.getTimePeriod() == 2){
                    startTime = queryDate.atTime(12, 0, 0);
                    if(detailsUserVo != null && detailsUserVo.getPmStartTime() != null){
                        startTime = queryDate.atTime(detailsUserVo.getPmStartTime());
                    }
                    endTime = queryDate.atTime(18, 0, 0);
                    if(detailsUserVo != null && detailsUserVo.getPmEndTime() != null){
                        endTime = queryDate.atTime(detailsUserVo.getPmEndTime());
                    }
                    amEndTime  = queryDate.atTime(12, 0, 0);
                    if(detailsUserVo != null && detailsUserVo.getAmEndTime() != null){
                        amEndTime = queryDate.atTime(detailsUserVo.getAmEndTime());
                    }
                }else{
                    startTime = queryDate.atTime(0, 0, 0);
                    if(detailsUserVo != null && detailsUserVo.getEveningStartTime() != null){
                        startTime = queryDate.atTime(detailsUserVo.getEveningStartTime());
                    }
                    endTime = queryDate.atTime(23, 59, 59);
                    if(detailsUserVo != null && detailsUserVo.getEveningEndTime() != null){
                        endTime = queryDate.atTime(detailsUserVo.getEveningEndTime());
                    }
                }
                
                WfTeacherleave studentLeave = wfTeacherleaveService.getLeaveByUserId(startTime, endTime, record.getUserId());
                if(studentLeave != null){
                    record.setStatus(studentLeave.getLeaveType());
                    continue;
                }

                WfHeadTeacherLeave teacherLeave = headTeacherLeaveService.selectJoinOne(WfHeadTeacherLeave.class,
                        new MPJLambdaWrapper<WfHeadTeacherLeave>()
                                .select(WfHeadTeacherLeave.class, x -> VoToColumnUtil.fieldsToColumns(WfHeadTeacherLeave.class).contains(x.getProperty()))
                                .innerJoin(XjrUser.class, XjrUser::getId, WfHeadTeacherLeave::getApplicantUserId)
                                .eq(WfHeadTeacherLeave::getStatus, 1)
                                .eq(WfHeadTeacherLeave::getApplicantUserId, record.getUserId())
                                .between(WfHeadTeacherLeave::getStartTime, startTime, endTime)
                );
                if(teacherLeave != null){
                    record.setStatus(teacherLeave.getLeaveReason());
                    continue;
                }
                TeacherOutInRecordDto outInDto = new TeacherOutInRecordDto();
                outInDto.setQueryDate(startTime.toLocalDate());
                outInDto.setRecordTime(endTime);
                outInDto.setStatus(OutInStatusEnum.enter.getCode());
                outInDto.setUserId(record.getUserId());
                List<TeacherOutInRecord> outInRecords = teacherOutInRecordService.getListByParam(outInDto);
                if(!outInRecords.isEmpty()){
                    TeacherOutInRecord outInRecord = outInRecords.get(0);
                    if(outInRecord != null){
                        record.setRecordTime(outInRecord.getRecordTime());
                        record.setStatus(outInRecord.getAttendanceStatus());
                        record.setAttendanceMode("人脸");
                    }
                }else{
                    //查询该教师是否通过车辆进入
                    List<CarOutInRecord> list = carOutInRecordService.list(
                            new MPJLambdaWrapper<CarOutInRecord>()
                                    .select(CarOutInRecord.class, x -> VoToColumnUtil.fieldsToColumns(CarOutInRecord.class).contains(x.getProperty()))
                                    .leftJoin(CarMessageApply.class, CarMessageApply::getId, CarOutInRecord::getCarMessageApplyId)
                                    .le(CarOutInRecord::getRecordTime, endTime)
                                    .eq("DATE_FORMAT(record_time, '%Y-%m-%d')", endTime.toLocalDate())
                                    .eq(CarMessageApply::getUserId, record.getUserId())
                                    .ge(dto.getTimePeriod() == 2 && amEndTime != null, CarOutInRecord::getRecordTime, amEndTime)
                                    .eq(CarOutInRecord::getStatus, OutInStatusEnum.enter.getCode())
                                    .orderByAsc(CarOutInRecord::getRecordTime)
                    );
                    if(!list.isEmpty()){
                        CarOutInRecord outInRecord = list.get(0);
                        if(outInRecord != null && outInRecord.getRecordTime().isBefore(startTime)){
                            record.setRecordTime(outInRecord.getRecordTime());
                            record.setStatus("到校");
                            record.setAttendanceMode("车辆");
                            record.setCarNumber(outInRecord.getPlanNo());
                        }else if(outInRecord != null && outInRecord.getRecordTime().isAfter(startTime)){
                            record.setRecordTime(outInRecord.getRecordTime());
                            record.setStatus("迟到");
                            record.setAttendanceMode("车辆");
                            record.setCarNumber(outInRecord.getPlanNo());
                        }
                    }
                }

                if(record.getStatus() == null){
                    record.setStatus("缺勤");
                }
            }
        }
        PageOutput<TeacherStatisticsPageVo> pageOutput = ConventPage.getPageOutput(voIPage, TeacherStatisticsPageVo.class);
        return RT.ok(pageOutput);
    }

}