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.model.result.RT;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.module.attendance.dto.TeacherDetailsDto;
import com.xjrsoft.module.attendance.vo.TeacherStatisticsPageVo;
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.entity.TeacherOutInRecord;
import com.xjrsoft.module.outint.service.ITeacherOutInRecordService;
import com.xjrsoft.module.teacher.entity.BaseTeacher;
import com.xjrsoft.module.teacher.entity.WfTeacherleave;
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.HashMap;
import java.util.List;
import java.util.Map;

/**
* @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;


    @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())
                .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)
                .leftJoin(UserDeptRelation.class, UserDeptRelation::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);
            LocalDateTime startTime, endTime;

            if(dto.getTimePeriod() == 1){
                startTime = queryDate.atTime(9, 0, 0);
                endTime = queryDate.atTime(12, 0, 0);
            }else if(dto.getTimePeriod() == 2){
                startTime = queryDate.atTime(12, 0, 0);
                endTime = queryDate.atTime(18, 0, 0);
            }else{
                startTime = queryDate.atTime(0, 0, 0);
                endTime = queryDate.atTime(23, 59, 59);
            }

            //查询当前时间段存在请假的教师
            Map<Long, WfTeacherleave> leaveList = wfTeacherleaveService.getLeaveList(startTime, endTime);
            //查询进入记录
            List<TeacherOutInRecord> outInRecords = teacherOutInRecordService.list(
                    new QueryWrapper<TeacherOutInRecord>().lambda()
                            .between(TeacherOutInRecord::getRecordTime, startTime, endTime)
                            .eq(TeacherOutInRecord::getStatus, 0)
                            .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()) {
                WfTeacherleave studentLeave = leaveList.get(record.getUserId());
                if(studentLeave != null){
                    record.setStatus(studentLeave.getLeaveType());
                }else{
                    TeacherOutInRecord outInRecord = outInMap.get(record.getUserId());
                    if(outInRecord != null){
                        record.setRecordTime(outInRecord.getRecordTime());
                        record.setStatus(outInRecord.getAttendanceStatus());
                    }else{
                        record.setStatus("缺勤");
                    }

                }
            }
        }
        PageOutput<TeacherStatisticsPageVo> pageOutput = ConventPage.getPageOutput(voIPage, TeacherStatisticsPageVo.class);
        return RT.ok(pageOutput);
    }

}