package com.template.controller;


import com.alibaba.druid.sql.visitor.functions.If;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.seewo.open.sdk.DefaultSeewoClient;
import com.seewo.open.sdk.SeewoClient;
import com.seewo.open.sdk.auth.Account;
import com.template.annotation.DESRespondSecret;
import com.template.annotation.PassToken;
import com.template.api.SmartAttendanceControllerAPI;
import com.template.common.utils.*;
import com.template.config.ControlConfig;
import com.template.config.ScheduleConfig;
import com.template.config.SeewoConfig;
import com.template.model.enumModel.*;
import com.template.model.evaluate.student.SmartEvaluateStudent;
import com.template.model.pojo.*;
import com.template.model.request.askForLeaveRequest;
import com.template.model.result.CommonResult;
import com.template.model.result.PageUtils;
import com.template.model.seewo.*;
import com.template.model.vo.*;
import com.template.services.*;
import com.tencentcloudapi.tci.v20190318.models.Person;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.validation.BindingResult;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.template.common.utils.AesTestOne.decrypt;

/**
 * <p>
 * 楼栋表 前端控制器
 * </p>
 *
 * @author ceshi
 * @since 2023-12-25
 */
@RestController
//返回参数加密注解
@DESRespondSecret
public class SmartAttendanceController implements SmartAttendanceControllerAPI {
    private static Logger logger = LoggerFactory.getLogger(SmartAttendanceController.class);

    @Resource
    private SeewoConfig seewoConfig;
    @Resource
    private ControlConfig controlConfig;
    @Autowired
    private SmartUserService smartUserService;
    @Autowired
    private SmartAttendanceService smartAttendanceService;
    @Autowired
    SmartSemesterService smartSemesterService;

    @Autowired
    SmartAskForLeaveConfigService smartAskForLeaveConfigService;

    @Autowired
    SmartClassService smartClassService;

    @Override
    @DESRespondSecret(validated = true)
    public CommonResult insertSmartAttendance(SmartAttendance smartApply, BindingResult bindingResult) {
        return null;
    }

    @Override
    @DESRespondSecret(validated = true)
    public CommonResult updateSmartAttendanceById(SmartAttendance ra, BindingResult bindingResult) {
        return null;
    }

    @Override
    @DESRespondSecret(validated = true)
    public CommonResult queryPageSmartAttendances(int currentPage, int pageCount, String name) {
        return null;
    }

    @Override
    @DESRespondSecret(validated = true)
    public CommonResult deleteSmartAttendanceById(int id) {
        return null;
    }


    @Resource
    private ScheduleConfig scheduleConfig;

    /**
     * 每一小时获取请假信息
     */
    @Async
    @Scheduled(cron = "0 0 0/1 * * ? ")
    public void get() {
        if (scheduleConfig.getIsOpen().equals("1")) {
            queryLeaveRecords();
        }

    }

    @Override
    @DESRespondSecret(validated = true)
    public CommonResult queryLeaveRecords() {
        int findPageSize = 20;

        PersonalLeaveListSchoolPeriodRecordsResult result = getXwAttendance(TimeExchange.getDate(), TimeExchange.getDate(), 1, findPageSize);
//        PersonalLeaveListSchoolPeriodRecordsResult result = getXwAttendance("2024-05-23","2024-06-14", 1, findPageSize);
        if (result == null) {
            return CommonResult.fail("当天不存在请假数据！");
        }

        if (!result.getResponseBody().getCode().equals("000000")) {
            return CommonResult.fail(result.getResponseBody().getMessage());
        }
        SmartAskForLeaveConfig list = smartAskForLeaveConfigService.getList();
        Integer IfVerification = 0;
        if (ObjectUtils.isNotEmpty(list) && ObjectUtils.isNotEmpty(list.getConfig())) {
            IfVerification = list.getConfig();
        }
//        当前集合的数量
        Integer resultCount = result.getResponseBody().getData().getResult().size();
        List<SmartAttendance> attendances = new ArrayList<>();
        for (int i = 0; i < resultCount; i++) {
            if (result.getResponseBody().getData().getResult().get(i).getLeaveStatus().intValue() == eXwApproveStatu.Passed.getValue()) {
                SmartAttendance attendance = new SmartAttendance();
                attendance.setXwuid(result.getResponseBody().getData().getResult().get(i).getUid());
                attendance.setUserUid(result.getResponseBody().getData().getResult().get(i).getUserUid());
                attendance.setXwUserName(result.getResponseBody().getData().getResult().get(i).getUserName());
                attendance.setReason(result.getResponseBody().getData().getResult().get(i).getReason());
                attendance.setStartTime(TimeExchange.StringToDate(result.getResponseBody().getData().getResult().get(i).getStartTime(), "yyyy-MM-dd HH:mm:ss"));
                attendance.setEndTime(TimeExchange.StringToDate(result.getResponseBody().getData().getResult().get(i).getEndTime(), "yyyy-MM-dd HH:mm:ss"));
                attendance.setInitiateTime(TimeExchange.StringToDate(result.getResponseBody().getData().getResult().get(i).getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                attendance.setInitiateXwuid(result.getResponseBody().getData().getResult().get(i).getApplyUserUid());
                attendance.setInitiateXwname(result.getResponseBody().getData().getResult().get(i).getApplyUserName());
                attendance.setInitiateXwphone(result.getResponseBody().getData().getResult().get(i).getApplyUserPhone());
                attendance.setStatus(eAttendanceStatu.AskLeave.getValue());
//               加未核销字段
                attendance.setIfVerification(IfVerification);
                attendances.add(attendance);
            }
        }
        //如果总条数大于第二条 那说明还有第二页
//        总数
        int totalCount = result.getResponseBody().getData().getTotalCount().intValue();
//        当前分页数
        Integer page = result.getResponseBody().getData().getPage();
//        当前页面展示数
        int pageSize = result.getResponseBody().getData().getPageSize().intValue();

        Integer count = page * pageSize;

        if (totalCount > count) {
            Integer totalPage = totalCount / pageSize + 1;
            for (int i = 2; i <= totalPage; i++) {
                PersonalLeaveListSchoolPeriodRecordsResult nextResult = getXwAttendance(TimeExchange.getDate(), TimeExchange.getDate(), i, findPageSize);
//                PersonalLeaveListSchoolPeriodRecordsResult nextResult = getXwAttendance("2024-05-23","2024-06-14", i, findPageSize);
                if (nextResult == null) {
                    return CommonResult.fail("当天不存在请假数据！");
                }

                if (!nextResult.getResponseBody().getCode().equals("000000")) {
                    return CommonResult.fail(nextResult.getResponseBody().getMessage());
                }
                for (int j = 0; j < nextResult.getResponseBody().getData().getResult().size(); j++) {
                    if (nextResult.getResponseBody().getData().getResult().get(j).getLeaveStatus().intValue() == eXwApproveStatu.Passed.getValue()) {
                        SmartAttendance attendance = new SmartAttendance();
                        attendance.setXwuid(nextResult.getResponseBody().getData().getResult().get(j).getUid());
                        attendance.setUserUid(nextResult.getResponseBody().getData().getResult().get(j).getUserUid());
                        attendance.setXwUserName(nextResult.getResponseBody().getData().getResult().get(j).getUserName());
                        attendance.setReason(nextResult.getResponseBody().getData().getResult().get(j).getReason());
                        attendance.setStartTime(TimeExchange.StringToDate(nextResult.getResponseBody().getData().getResult().get(j).getStartTime(), "yyyy-MM-dd HH:mm:ss"));
                        attendance.setEndTime(TimeExchange.StringToDate(nextResult.getResponseBody().getData().getResult().get(j).getEndTime(), "yyyy-MM-dd HH:mm:ss"));
                        attendance.setInitiateTime(TimeExchange.StringToDate(nextResult.getResponseBody().getData().getResult().get(j).getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                        attendance.setInitiateXwuid(nextResult.getResponseBody().getData().getResult().get(j).getApplyUserUid());
                        attendance.setInitiateXwname(nextResult.getResponseBody().getData().getResult().get(j).getApplyUserName());
                        attendance.setInitiateXwphone(nextResult.getResponseBody().getData().getResult().get(j).getApplyUserPhone());
                        attendance.setStatus(eAttendanceStatu.AskLeave.getValue());
//                        加未核销字段
                        attendance.setIfVerification(IfVerification);
                        attendances.add(attendance);
                    }
                }
            }
        }
//        //获取当天的请假数据中是否存在重复的
//        List<SmartAttendance> oldAttendances = smartAttendanceService.queryExistAttendances(TimeExchange.getStartDate(), TimeExchange.getEndDate());
//        if (oldAttendances != null && oldAttendances.size() > 0) {
//            if (attendances != null && attendances.size() > 0) {
//                for (SmartAttendance oldAttendance : oldAttendances) {
//                    attendances = attendances.stream().filter(e -> !e.getXwuid().equals(oldAttendance.getXwuid())).collect(Collectors.toList());
//                }
//            }
//        }

        //新增请假数据
        if (attendances != null && attendances.size() > 0) {
            //获取用户数据
            List<String> xwuids = attendances.stream().map(SmartAttendance::getUserUid).collect(Collectors.toList());
            List<SmartUser> users = smartUserService.getSmartUserByxwuids(xwuids);
            if (users != null && users.size() > 0) {
                for (SmartAttendance attendance : attendances) {
                    Optional<SmartUser> user = users.stream().filter(e -> e.getXwStudentUid().equals(attendance.getUserUid())).findFirst();
                    if (user != null && user.isPresent()) {
                        attendance.setUserId(user.get().getId());
                        attendance.setClassId(user.get().getSchoolClass());
                    }
                }
            }
            ArrayList<SmartAttendance> attendanceArrayList = new ArrayList<>();
            for (SmartAttendance attendance : attendances) {
//                判断是否有重复数据
                List<SmartAttendance> smartAttendances = smartAttendanceService.duplicatesList(attendance.getStartTime(), attendance.getEndTime(), attendance.getInitiateTime());
                if (ObjectUtils.isEmpty(smartAttendances) && smartAttendances.size() <= 0) {
                    attendanceArrayList.add(attendance);
                }
            }

            boolean insertResult = smartAttendanceService.insertAttendanceBatch(attendanceArrayList);
            if (!insertResult) {
                return CommonResult.fail("请假数据获取失败");
            }
        }

        return CommonResult.ok("操作成功");
    }

    @Override
    @DESRespondSecret(validated = true)
    public CommonResult queryAttendanceList(String date, int classId) {
        if (date == null || date == "") {
            date = TimeExchange.getDate();
        }

        List<HomePageAttendanceVo> result = new ArrayList<>();

        SmartClass classData = smartClassService.getSmartClassById(classId);
        if (classData != null) {
            //初始化客户端
            SeewoClient seewoClient = new DefaultSeewoClient(new Account(seewoConfig.getAppId(), seewoConfig.getAppSecret()));
            AttendanceServiceListEventRecordsByClazzParam param = new AttendanceServiceListEventRecordsByClazzParam();
            //响应体，MimeType为 application/json
            AttendanceServiceListEventRecordsByClazzParam.RequestBody requestBody = AttendanceServiceListEventRecordsByClazzParam.RequestBody.builder()
                    .build();
            param.setRequestBody(requestBody);
            //query
            AttendanceServiceListEventRecordsByClazzParam.Query query = AttendanceServiceListEventRecordsByClazzParam.Query.builder()
                    .appId(seewoConfig.getAppId())
                    .schoolUid(seewoConfig.getSchoolId())
                    .attendDate(date)
                    .classUid(classData.getClassUid())
                    .build();
            requestBody.setQuery(query);
            AttendanceServiceListEventRecordsByClazzRequest request = new AttendanceServiceListEventRecordsByClazzRequest(param);
            // 该接口需要数据权限，请将授权资源id替换至下方，请妥善保管好授权资源id，避免泄露
            // permissionId位置: 控制台 -> 应用详情 -> 我申请的 -> 已通过的接口 -> 调用范围 -> 审批信息 中查看授权资源的「学校id」或「区域id」
            //request.setPermissionId("");
            System.out.println("入参：" + request);
            //执行请求，如果想获取到com.seewo.open.sdk.HttpResponse对象，请调用 seewoClient.execute 方法
            AttendanceServiceListEventRecordsByClazzResult xwResult = seewoClient.invoke(request);
            System.out.println("出参：" + xwResult);

            if (xwResult == null) {
                return CommonResult.fail("当天不存在请假数据！");
            }

            if (!xwResult.getResponseBody().getCode().equals("000000")) {
                return CommonResult.fail(xwResult.getResponseBody().getMessage());
            }

            Integer totalNum = 0;//考勤总人数
            Integer presentNum = 0;//考勤准时人数
            Integer lateNum = 0;//考勤迟到人数
            Integer leaveNum = 0;//考勤请假人数
            Integer absenceNum = 0;//考勤缺卡人数
            Integer timeoutNum = 0;//超时打卡人数
            if (xwResult.getResponseBody().getData() != null
                    && xwResult.getResponseBody().getData().getAttendStatistic() != null
                    && xwResult.getResponseBody().getData().getAttendStatistic().size() > 0) {
                for (AttendanceServiceListEventRecordsByClazzResult.AttendStatistic statistic : xwResult.getResponseBody().getData().getAttendStatistic()) {
                    totalNum = totalNum + statistic.getTotalNum();
                    presentNum = presentNum + statistic.getPresentNum();
                    lateNum = lateNum + statistic.getLateNum();
                    leaveNum = leaveNum + statistic.getLeaveNum();
                    absenceNum = absenceNum + statistic.getAbsenceNum();
                }
            }
            timeoutNum = totalNum - (presentNum + lateNum + leaveNum + absenceNum);

            List<Integer> status = eAttendanceStatu.attendanceStatus();
            for (int statu : status) {
                double restData = 0.0;

                HomePageAttendanceVo data = new HomePageAttendanceVo();
                data.setName(eAttendanceStatu.stringOf(statu));

                switch (data.getName()) {
                    case "准时":
                        restData = totalNum == 0 ? 0 : (double) presentNum / totalNum * 100;
                        break;
                    case "迟到":
                        restData = totalNum == 0 ? 0 : (double) lateNum / totalNum * 100;
                        break;
                    case "缺卡":
                        restData = totalNum == 0 ? 0 : (double) absenceNum / totalNum * 100;
                        break;
                    case "请假":
                        restData = totalNum == 0 ? 0 : (double) leaveNum / totalNum * 100;
                        break;
                    case "超时打卡":
                        restData = totalNum == 0 ? 0 : (double) timeoutNum / totalNum * 100;
                        break;
                    default:
                        break;
                }

                data.setProportion(restData);
                result.add(data);
            }
        }

        return CommonResult.ok(result);
    }

    @Override
    public CommonResult askForLeave(askForLeaveRequest request, BindingResult bindingResult) throws Exception {

        SmartStudentVo student = smartUserService.querySmartStudentById(request.getId());
        if (student == null) {
            return CommonResult.fail("学生数据无效，请假失败！");
        }

        if (student.getIdentityId().intValue() != eIdentityStatu.Student.getValue()) {
            return CommonResult.fail("当前用户身份不是学生，无法请假！");
        }

        String reason = request.getReason() == null ? "学生请假" : request.getReason();

        //region 学生请假
        String appId = controlConfig.getAppId();
        String schoolno = controlConfig.getSchoolCode();
        String timestamp = TimeExchange.DateNowTimeStamo();
        String appSecret = controlConfig.getAppSecret();
        String url = controlConfig.getUrl() + "student/addleavebill";

        JSONObject jsonobject = new JSONObject();
        jsonobject.put("appid", appId);
        String str = "{\"student_no\":\"" + student.getBsStudentNo() + "\",\"grade_no\":\"" + student.getBsGradeNo() + "\",\"classtab_no\":\"" + student.getBsClassNo() + "\",\"leavebill_content\":\"" + reason + "\",\"leavebill_begindate\":\"" + request.getStartTime() + "\",\"leavebill_enddate\":\"" + request.getEndTime() + "\",\"leavebill_remark\":\"" + "" + "\"}";
        String aesStr = URLEncoder.encode(AesTestOne.encrypt(str, controlConfig.getAppSecret()), "UTF-8");
        jsonobject.put("data", aesStr);
        jsonobject.put("schoolno", schoolno);
        jsonobject.put("timestamp", timestamp);

        String md5Str = "appid=" + appId + "&data={\"student_no\":\"" + student.getBsStudentNo() + "\",\"grade_no\":\"" + student.getBsGradeNo() + "\",\"classtab_no\":\"" + student.getBsClassNo() + "\",\"leavebill_content\":\"" + reason + "\",\"leavebill_begindate\":\"" + request.getStartTime() + "\",\"leavebill_enddate\":\"" + request.getEndTime() + "\",\"leavebill_remark\":\"" + "" + "\"}" + "&schoolno=" + schoolno + "&timestamp=" + timestamp + "&key=" + appSecret;
        String sign = CommonUtil.MD5(md5Str);
        //sign签名
        jsonobject.put("sign", sign);

        //返回的结果中 code为1表示成功
        String bsResult = RequestUtils.httpPost(url, jsonobject.toJSONString());

        ObjectMapper objectMapper = new ObjectMapper();
        BsLeaveVo leave = objectMapper.readValue(bsResult, BsLeaveVo.class);

        if (!bsResult.contains("添加成功")) {
            return CommonResult.fail(leave.getMsg());
        }

        // URL解码
        String decodedUrl = URLDecoder.decode(leave.getData(), "UTF-8");

        BsLeaveNoVo leaveNo = objectMapper.readValue(decrypt(decodedUrl, controlConfig.getAppSecret()), BsLeaveNoVo.class);

        return CommonResult.ok("200", "操作成功", leaveNo.getLeavebill_no());
        //endregion

    }

    @Override
    public CommonResult historicalAttendance(int userId, String dateTime) {

        LocalDateTime now = LocalDateTime.now();
        Date startTime = null;
        Date endTime = null;
        HistoricalAttendanceVo historicalAttendanceVo = new HistoricalAttendanceVo();
        if ("1".equals(dateTime)) {
//        本学期
            SmartSemester smartSemester = smartSemesterService.getSemester(now);
            if (ObjectUtils.isEmpty(smartSemester)) {
                return CommonResult.ok(historicalAttendanceVo);
            }
            startTime = smartSemester.getStartTime();
            endTime = smartSemester.getEndTime();
            System.out.println("smartSemester = " + smartSemester);

        } else if ("2".equals(dateTime)) {
//        近1个月
            LocalDateTime localDateTime = now.minusMonths(1);
            startTime = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
            endTime = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());

        } else if ("3".equals(dateTime)) {
//        近一周
            LocalDateTime localDateTime = now.minusDays(7);
            startTime = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
            endTime = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
        }

        List<Integer> statusList = smartAttendanceService.getGroup();

        for (Integer status : statusList) {
            List<SmartAttendance> smartAttendances = smartAttendanceService.getHistoricalAttendance(userId, status, startTime, endTime);
            if (0 == status) {
                historicalAttendanceVo.setPunctuality(smartAttendances.size());
            } else if (1 == status) {
                historicalAttendanceVo.setBeLate(smartAttendances.size());
            } else if (3 == status) {
                historicalAttendanceVo.setNotClockingIn(smartAttendances.size());
            } else if (6 == status) {
                historicalAttendanceVo.setAskForLeave(smartAttendances.size());
            } else if (7 == status) {
                historicalAttendanceVo.setClockOut(smartAttendances.size());
            }
        }

        return CommonResult.ok(historicalAttendanceVo);
    }

    @Override
    @DESRespondSecret(validated = true)
    public CommonResult askForLeavePage(int currentPage, int pageCount, String name, String cardNo, String startTime, String endTime, String ifVerification, String classId) {
        PageUtils<AskForLeaveVo> result = smartAttendanceService.askForLeavePage(currentPage, pageCount, name, cardNo, startTime, endTime, ifVerification, classId);
        return CommonResult.ok(result);

    }

    @Override
    @DESRespondSecret(validated = true)
    public CommonResult queryPage(int currentPage, int pageCount, Integer gradeId, Integer classId, String status, String studentNo, String name, String startTime, String endTime) {
        PageUtils<SmartAttendanceVo> result = smartAttendanceService.queryPage(currentPage, pageCount, gradeId, classId, status, studentNo, name, startTime, endTime);
        return CommonResult.ok(result);
    }

    @Override
    @DESRespondSecret(validated = true)
    @PassToken
    public CommonResult verification(String id) {
        SmartAttendance attendance = smartAttendanceService.getById(id);
        if (ObjectUtils.isEmpty(attendance)) {
            return CommonResult.fail("该id不存在");
        }
        attendance.setIfVerification(1);
        boolean update = smartAttendanceService.updateById(attendance);
        if (update) {
            return CommonResult.ok();
        }
        return CommonResult.fail();
    }

    @Override
    public void queryPageExport(HttpServletResponse response, Integer gradeId, Integer classId, String status, String studentNo, String name, String startTime, String endTime) {

        //导出
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("学生考勤记录");
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("序号");
        headerRow.createCell(1).setCellValue("姓名");
        headerRow.createCell(2).setCellValue("年级");
        headerRow.createCell(3).setCellValue("班级");
        headerRow.createCell(4).setCellValue("学号");
        headerRow.createCell(5).setCellValue("头像");
        headerRow.createCell(6).setCellValue("打卡时间");
        headerRow.createCell(7).setCellValue("请假时间");
        headerRow.createCell(8).setCellValue("考勤状态");

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //        默认前一天的
        if (ObjectUtils.isEmpty(startTime) || ObjectUtils.isEmpty(endTime)) {
            LocalDateTime end = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
            LocalDateTime now = end.minusDays(1);
            startTime = now.format(dateTimeFormatter);
            endTime = end.format(dateTimeFormatter);
        }

        //获取学生考勤记录
        List<SmartAttendanceVo> vos = smartAttendanceService.queryExpor(gradeId, classId, status, studentNo, name, startTime, endTime);

        for (int i = 0; i < vos.size(); i++) {
            SmartAttendanceVo vo = vos.get(i);

            Row dataRow = sheet.createRow(i + 1);
            dataRow.createCell(0).setCellValue(i + 1);
            dataRow.createCell(1).setCellValue(vo.getName());
            dataRow.createCell(2).setCellValue(vo.getGradeName());
            dataRow.createCell(3).setCellValue(vo.getClassName());
            dataRow.createCell(4).setCellValue(vo.getCardNo());
            dataRow.createCell(5).setCellValue(vo.getHeadImage());
            dataRow.createCell(6).setCellValue(vo.getAttendTime());
            dataRow.createCell(7).setCellValue(vo.getInitiateTime());
//            状态
            Integer status1 = vo.getStatus();
            String type = "";
            if (0 == status1) {
                type = "准时";
            } else if (1 == status1) {
                type = "迟到";
            } else if (3 == status1) {
                type = "缺卡";
            } else if (6 == status1) {
                type = "请假";
            } else if (7 == status1) {
                type = "超时打卡";
            }
            dataRow.createCell(8).setCellValue(type);
        }

        // 将工作簿写入文件
        ExcelUtils.excelDownload(workbook, "学生考勤.xlsx", response);
    }

    @Override
    @DESRespondSecret(validated = true)
    @PassToken
    public CommonResult askForLeaveScreenPage(int currentPage, int pageCount, String cardNo, String ifVerification) {
        PageUtils<AskForLeaveScreenVo> result = smartAttendanceService.askForLeaveScreenPage(currentPage, pageCount, cardNo, ifVerification);

        return CommonResult.ok(result);
    }

    @Override
    @DESRespondSecret(validated = true)
    public CommonResult studentHistoricalAttendance(String dateTime) {
        LocalDateTime now = LocalDateTime.now();
        Date startTime = null;
        Date endTime = null;
        HistoricalAttendanceVo historicalAttendanceVo = new HistoricalAttendanceVo();
        if ("1".equals(dateTime)) {
//        本学期
            SmartSemester smartSemester = smartSemesterService.getSemester(now);
            if (ObjectUtils.isEmpty(smartSemester)) {
                return CommonResult.ok(historicalAttendanceVo);
            }
            startTime = smartSemester.getStartTime();
            endTime = smartSemester.getEndTime();
            System.out.println("smartSemester = " + smartSemester);

        } else if ("2".equals(dateTime)) {
//        近1个月
            LocalDateTime localDateTime = now.minusMonths(1);
            startTime = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
            endTime = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());

        } else if ("3".equals(dateTime)) {
//        近一周
            LocalDateTime localDateTime = now.minusDays(7);
            startTime = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
            endTime = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
        }

        List<Integer> statusList = smartAttendanceService.getGroup();

        for (Integer status : statusList) {
            Integer count = smartAttendanceService.getStudentHistoricalAttendance(status, startTime, endTime);
            if (0 == status) {
                historicalAttendanceVo.setPunctuality(count);
            } else if (1 == status) {
                historicalAttendanceVo.setBeLate(count);
            } else if (3 == status) {
                historicalAttendanceVo.setNotClockingIn(count);
            } else if (6 == status) {
                historicalAttendanceVo.setAskForLeave(count);
            } else if (7 == status) {
                historicalAttendanceVo.setClockOut(count);
            }
        }

        return CommonResult.ok(historicalAttendanceVo);
    }

    @Override
    @DESRespondSecret(validated = true)
    public CommonResult classHistoricalAttendance(String dateTime, int currentPage, int pageCount, String className) {

        LambdaQueryWrapper<SmartClass> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ObjectUtils.isNotEmpty(className), SmartClass::getName, className);
        IPage<SmartClass> page = smartClassService.page(new Page<>(currentPage, pageCount), wrapper);


        LocalDateTime now = LocalDateTime.now();
        Date startTime = null;
        Date endTime = null;
        if ("1".equals(dateTime)) {
//        本学期
            SmartSemester smartSemester = smartSemesterService.getSemester(now);
            if (ObjectUtils.isEmpty(smartSemester)) {
                return CommonResult.ok("不存在该学期");
            }
            startTime = smartSemester.getStartTime();
            endTime = smartSemester.getEndTime();


        } else if ("2".equals(dateTime)) {
//        近1个月
            LocalDateTime localDateTime = now.minusMonths(1);
            startTime = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
            endTime = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());

        } else if ("3".equals(dateTime)) {
//        近一周
            LocalDateTime localDateTime = now.minusDays(7);
            startTime = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
            endTime = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
        }


        List<SmartClass> records = page.getRecords();
        ArrayList<ClassHistoricalAttendanceVo> vos = new ArrayList<>();
        for (SmartClass record : records) {
            ClassHistoricalAttendanceVo historicalAttendanceVo = new ClassHistoricalAttendanceVo();
            historicalAttendanceVo.setClassName(record.getName());
            List<ClasAttendanceVo> list = smartAttendanceService.getClassHistoricalAttendance(startTime, endTime, record.getId());
            for (ClasAttendanceVo clasAttendanceVo : list) {
                Integer status = clasAttendanceVo.getStatus();
                Integer count = clasAttendanceVo.getCount();

                if (0 == status) {
                    historicalAttendanceVo.setPunctuality(count);
                } else if (1 == status) {
                    historicalAttendanceVo.setBeLate(count);
                } else if (3 == status) {
                    historicalAttendanceVo.setNotClockingIn(count);
                } else if (7 == status) {
                    historicalAttendanceVo.setClockOut(count);
                }
            }
//        请假的单独弄
            Integer count = smartAttendanceService.getClassAckHistoricalAttendance(6, startTime, endTime, record.getId());
            historicalAttendanceVo.setAskForLeave(count);
            vos.add(historicalAttendanceVo);
        }

        Page<ClassHistoricalAttendanceVo> objectPage = new Page<>();
        BeanUtils.copyProperties(page, objectPage);
        objectPage.setRecords(vos);

        return CommonResult.ok(objectPage);
    }

    @Override
    @DESRespondSecret(validated = true)
    public CommonResult ackDetail(Integer userId, String dateTime) {
        DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startTime = LocalDateTime.parse(dateTime, dateTimeFormatter1);
        LocalDateTime endTime = startTime.plusDays(1);

//        获取单人单日的请假数据
        List<AckDetailVo> ackVos= smartAttendanceService.ackDetail(userId,startTime,endTime);

        return CommonResult.ok(ackVos);
    }

    public PersonalLeaveListSchoolPeriodRecordsResult getXwAttendance(String startDate, String endDate, Integer currentPage, Integer pageSize) {
        //初始化客户端
        SeewoClient seewoClient = new DefaultSeewoClient(new Account(seewoConfig.getAppId(), seewoConfig.getAppSecret()));
        PersonalLeaveListSchoolPeriodRecordsParam param = new PersonalLeaveListSchoolPeriodRecordsParam();
        //请求体，MimeType为 application/json
        PersonalLeaveListSchoolPeriodRecordsParam.RequestBody requestBody = PersonalLeaveListSchoolPeriodRecordsParam.RequestBody.builder()
                .build();
        param.setRequestBody(requestBody);
        //query
        PersonalLeaveListSchoolPeriodRecordsParam.Query query = PersonalLeaveListSchoolPeriodRecordsParam.Query.builder()
                .schoolUid(seewoConfig.getSchoolId())//学校ID
                .startDate(startDate)//开始日期
                .endDate(endDate)//结束日期
                .page(currentPage)//当前页
                .pageSize(pageSize)//分页条数
                .appId(seewoConfig.getAppId())
                .build();
        requestBody.setQuery(query);
        param.setRequestBody(requestBody);
        PersonalLeaveListSchoolPeriodRecordsRequest request = new PersonalLeaveListSchoolPeriodRecordsRequest(param);
        logger.info("入参：" + request);
        //如果想要调用沙箱环境，请通过设置 request 对象的 serverUrl 属性，如：
        //request.setServerUrl("https://openapi.test.seewo.com")
        //执行请求，如果想获取到com.seewo.open.sdk.HttpResponse对象，请调用 seewoClient.execute 方法
        PersonalLeaveListSchoolPeriodRecordsResult result = seewoClient.invoke(request);
        logger.info("出参：" + result);


        return result;
    }

}

