package com.srs.dormitory.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.utils.DateUtils;
import com.srs.common.utils.SecurityUtils;
import com.srs.comprehensive.domain.SrsStuYear;
import com.srs.comprehensive.domain.SrsStudent;
import com.srs.comprehensive.mapper.SrsStuYearMapper;
import com.srs.comprehensive.mapper.SrsStudentMapper;
import com.srs.dormitory.domain.*;
import com.srs.dormitory.domain.Dto.DmsSearch;
import com.srs.dormitory.domain.Vo.DomInfo;
import com.srs.dormitory.domain.Vo.DormitoryVo;
import com.srs.dormitory.domain.Vo.SrsDormitoryStudentVo;
import com.srs.dormitory.mapper.*;
import liquibase.pro.packaged.A;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.srs.dormitory.service.IDmsManageApplicationService;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import static com.srs.common.utils.DateUtils.getNowDate;
import static com.srs.common.utils.SecurityUtils.getUsername;
import static com.srs.dormitory.utils.BeanCopyUtils.isToday;

/**
 * 宿舍管理申请Service业务层处理
 *
 * @author srs
 * @date 2024-02-29
 */
@Service
public class DmsManageApplicationServiceImpl extends ServiceImpl<DmsManageApplicationMapper, DmsManageApplication> implements IDmsManageApplicationService {
    @Autowired
    private DmsManageApplicationMapper dmsManageApplicationMapper;
    @Autowired
    private DmsApprovalProcessMapper approvalProcessMapper;
    @Autowired
    private SrsDormitoryStudentMapper dormitoryStudentMapper;
    @Autowired
    private DmsSemesterMapper semesterMapper;
    @Autowired
    private DmsDormitoryMapper dormitoryMapper;
    @Autowired
    private DmsLiveDetailMapper liveDetailMapper;
    @Autowired
    public DmsNewRecordMapper _newRecordMapper;
    @Autowired
    public DmsNewRangeMapper _rangeMapper;
    @Autowired
    public DmsNewRecordServiceImpl _newRecordService;
    @Autowired
    public SrsStuYearMapper _yearMapper;
    @Autowired
    public ISrsDormitoryStudentServiceImpl _domStuService;
    @Autowired
    public SrsDormitoryStudentMapper _dormStuMapper;
    @Autowired
    public DmsNewTaskMapper _taskMapper;
    @Autowired
    public DmsNewTaskServiceImpl _taskService;
    @Autowired
    public IDmsDormitoryServiceImpl _dormService;
    @Autowired
    public SrsStudentMapper _stuMapper;

    @Autowired
    public PlatformTransactionManager transactionManager;

    @Override
    public List<DomInfo> listView(DmsSearch param){
        return dmsManageApplicationMapper.listView(param);
    }



    @Override
    public AjaxResult stuChange(DmsManageApplication param) {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            Long id = param.getId();
            DmsManageApplication find = dmsManageApplicationMapper.selectById(id);
            if (find == null) {
                throw new Exception("该记录不存在");
            }
            if (find.getStatus() != 0) {
                throw new Exception("该记录已被审核，不可修改");
            }

            String stuNo = getUsername();
            if (!Objects.equals(find.getStuNo(), stuNo)) {
                throw new Exception("你是谁？");
            }

            int res = dmsManageApplicationMapper.updateById(param);
            if (res == 0) {
                throw new Exception("未知原因，修改失败");
            }

            transactionManager.commit(status);
            return AjaxResult.success();
        } catch (Exception ex) {
            transactionManager.rollback(status);
            return AjaxResult.error(ex.getMessage());
        }
    }


    /**
     * 查询宿舍管理申请
     *
     * @param id 宿舍管理申请主键
     * @return 宿舍管理申请
     */
    @Override
    public DmsManageApplication selectDmsManageApplicationById(Long id) {
        return dmsManageApplicationMapper.selectDmsManageApplicationById(id);
    }

    /**
     * 查询宿舍管理申请列表
     *
     * @param dmsManageApplication 宿舍管理申请
     * @return 宿舍管理申请
     */
    @Override
    public List<DmsManageApplication> selectDmsManageApplicationList(DmsManageApplication dmsManageApplication) {
        return dmsManageApplicationMapper.selectDmsManageApplicationList(dmsManageApplication);
    }

    /**
     * 根据学号获取学生当前宿舍信息
     *
     * @param studentNo 学号
     * @return 学生宿舍信息
     */
    public AjaxResult getStudentDormitoryInfo(String studentNo) {
        try {
            // 参考现有逻辑中的查询方式
            QueryWrapper<SrsDormitoryStudent> dormStuQuery = new QueryWrapper<>();
            dormStuQuery.eq("stu_no", studentNo)
                    .last("limit 1");

            SrsDormitoryStudent dormStu = _dormStuMapper.selectOne(dormStuQuery);
            if (dormStu == null) {
                return AjaxResult.error("该学生不在住宿记录表中，可能已退宿");
            }

            // 获取宿舍详细信息
            DmsDormitory dormitory = dormitoryMapper.selectById(dormStu.getDormitoryId());
            if (dormitory == null) {
                return AjaxResult.error("未找到学生宿舍信息");
            }

            // 使用新添加的Mapper方法直接获取学生宿舍完整信息
            DomInfo studentDormInfo = dmsManageApplicationMapper.selectStudentDormitoryInfoByStuNo(studentNo);
            
            if (studentDormInfo == null) {
                return AjaxResult.error("未找到该学生的宿舍信息");
            }

            // 返回学生宿舍完整信息
            return AjaxResult.success(studentDormInfo);
        } catch (Exception e) {
            return AjaxResult.error("查询学生宿舍信息失败: " + e.getMessage());
        }
    }

    /**
     * 新增宿舍管理申请
     *
     * @param dmsManageApplication 宿舍管理申请
     * @return 结果
     */
    @Override
    public AjaxResult insertDmsManageApplication(DmsManageApplication dmsManageApplication) {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            String username = getUsername();
            String userType = dmsManageApplication.getGetBy(); // 获取当前用户类型
            // 只允许辅导员发起申请
            if (!"teacher".equals(userType)) {
                throw new Exception("只有辅导员可以发起宿舍申请");
            }

            QueryWrapper<SrsDormitoryStudent> dormStuQuery = new QueryWrapper<>();
            dormStuQuery.eq("stu_no", dmsManageApplication.getStuNo())
                    .last("limit 1");

            SrsDormitoryStudent dormStu = _dormStuMapper.selectOne(dormStuQuery);
            if (dormStu == null) {
                throw new Exception("该学生已退宿(不在住宿记录表中)");
            }

            // 检查该学生是否已存在未完成的申请
            List<String> isExistStatus = new ArrayList<>();
            isExistStatus.add("0");
            isExistStatus.add("1");
            isExistStatus.add("2");

            QueryWrapper<DmsManageApplication> applyQuery = new QueryWrapper<>();
            applyQuery.eq("stu_no", dmsManageApplication.getStuNo())
                    .in("status", isExistStatus);

            List<DmsManageApplication> isExist = dmsManageApplicationMapper.selectList(applyQuery);

            if (isExist.size() > 0) {
                throw new RuntimeException("该学生当前存在未审核完成的流程");
            }

            QueryWrapper<DmsNewRecord> recordQueryWrapper = new QueryWrapper<>();
            recordQueryWrapper.eq("stu_no", dmsManageApplication.getStuNo())
                    .orderByDesc("id");
            List<DmsNewRecord> records = _newRecordMapper.selectList(recordQueryWrapper);

            QueryWrapper<DmsNewTask> taskQuery = new QueryWrapper<>();
            taskQuery.eq("stu_no", dmsManageApplication.getStuNo())
                    .eq("task_status", "2");
            List<DmsNewTask> taskList = _taskMapper.selectList(taskQuery);
            if (taskList.size() != 0) {
                throw new Exception("该学生当前存在未执行的调宿计划任务，建议调宿任务执行后再申请");
            }

            if (records.size() == 0) {
                throw new RuntimeException("该学生没有住宿记录");
            }

            dmsManageApplication.setCurrentDormId(records.get(0).getRoomId());
            dmsManageApplication.setCreateTime(getNowDate());
            // 辅导员发起的申请直接进入下一审批环节（状态为1）
            dmsManageApplication.setStatus(1L);

            int i1 = dmsManageApplicationMapper.insertDmsManageApplication(dmsManageApplication);
            DmsApprovalProcess approvalProcess = new DmsApprovalProcess();
            approvalProcess.setApplyId(dmsManageApplication.getId());
            approvalProcess.setCreateTime(getNowDate());
            // 自动设置辅导员审批信息
            approvalProcess.setFdyTime(getNowDate());
            approvalProcess.setFdyNo(username);
            approvalProcess.setFdyStatus("6"); // 辅导员审批通过
            int i2 = approvalProcessMapper.insert(approvalProcess);
            if (i1 + i2 != 2) {
                throw new Exception("操作失败");
            }
            transactionManager.commit(status);
            return AjaxResult.success("宿舍申请已成功发起并通过辅导员审批");
        } catch (Exception ex) {
            transactionManager.rollback(status);
            return AjaxResult.error(ex.getMessage());
        }
    }
    /*@Override
    public AjaxResult insertDmsManageApplication(DmsManageApplication dmsManageApplication) {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            String username = getUsername();

            QueryWrapper<SrsDormitoryStudent> dormStuQuery = new QueryWrapper<>();
            dormStuQuery.eq("stu_no", username)
                    .last("limit 1");

            SrsDormitoryStudent dormStu = _dormStuMapper.selectOne(dormStuQuery);
            if (dormStu == null) {
                throw new Exception("您已退宿(不在住宿记录表中)");
            }

            dmsManageApplication.setStuNo(username);

            QueryWrapper<DmsNewRecord> recordQueryWrapper = new QueryWrapper<>();
            recordQueryWrapper.eq("stu_no", username)
                    .orderByDesc("id");
            List<DmsNewRecord> records = _newRecordMapper.selectList(recordQueryWrapper);

            List<String> isExistStatus = new ArrayList<>();
            isExistStatus.add("0");
            isExistStatus.add("1");
            isExistStatus.add("2");

            QueryWrapper<DmsManageApplication> applyQuery = new QueryWrapper<>();
            applyQuery.eq("stu_no", username)
                    .in("status", isExistStatus);

            List<DmsManageApplication> isExist = dmsManageApplicationMapper.selectList(applyQuery);

            if (isExist.size() > 0) {
                throw new RuntimeException("您当前存在未审核完成的流程");
            }


            QueryWrapper<DmsNewTask> taskQuery = new QueryWrapper<>();
            taskQuery.eq("stu_no", username)
                    .eq("task_status", "2");
            List<DmsNewTask> taskList = _taskMapper.selectList(taskQuery);
            if (taskList.size() != 0) {
                throw new Exception("您当前存在未执行的调宿计划任务，建议调宿任务执行后再申请");
            }

            if (records.size() == 0) {
                throw new RuntimeException("您没有住宿记录");
            }
            dmsManageApplication.setCurrentDormId(records.get(0).getRoomId());
            dmsManageApplication.setCreateTime(getNowDate());
            int i1 = dmsManageApplicationMapper.insertDmsManageApplication(dmsManageApplication);
            DmsApprovalProcess approvalProcess = new DmsApprovalProcess();
            approvalProcess.setApplyId(dmsManageApplication.getId());
            approvalProcess.setCreateTime(getNowDate());
            int i2 = approvalProcessMapper.insert(approvalProcess);
            if (i1 + i2 != 2) {
                throw new Exception("操作失败");
            }
            transactionManager.commit(status);
            return AjaxResult.success();
        } catch (Exception ex) {
            transactionManager.rollback(status);
            return AjaxResult.error(ex.getMessage());
        }

    }*/

    /**
     * 修改宿舍管理申请
     *
     * @param dmsManageApplication 宿舍管理申请
     * @return 结果
     */
    @Override
    public AjaxResult updateDmsManageApplication(DmsManageApplication dmsManageApplication) {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            Date nowDate = getNowDate();
            String username = getUsername();
            dmsManageApplication.setUpdateTime(nowDate);


            if (dmsManageApplication.getGetBy().equals("teacher")) {


                new LambdaUpdateChainWrapper<>(approvalProcessMapper)
                        .set(DmsApprovalProcess::getFdyTime, nowDate)
                        .set(DmsApprovalProcess::getFdyNo, username)
                        .set(DmsApprovalProcess::getFdyStatus, dmsManageApplication.getStatus())
                        .eq(DmsApprovalProcess::getApplyId, dmsManageApplication.getId())
                        .update();
                dmsManageApplication.setStatus(dmsManageApplication.getStatus() == 6 ? 1L : -1L);
            } else if (dmsManageApplication.getGetBy().equals("work")) {
                new LambdaUpdateChainWrapper<>(approvalProcessMapper)
                        .set(DmsApprovalProcess::getWorkTime, nowDate)
                        .set(DmsApprovalProcess::getWorkNo, username)
                        .set(DmsApprovalProcess::getWorkStatus, dmsManageApplication.getStatus())
                        .eq(DmsApprovalProcess::getApplyId, dmsManageApplication.getId())
                        .update();
                dmsManageApplication.setStatus(dmsManageApplication.getStatus() == 6 ? 2L : -1L);
            } else if (dmsManageApplication.getGetBy().equals("final")) {
                new LambdaUpdateChainWrapper<>(approvalProcessMapper)
                        .set(DmsApprovalProcess::getFinalTime, nowDate)
                        .set(DmsApprovalProcess::getFinalNo, username)
                        .set(DmsApprovalProcess::getFinalStatus, dmsManageApplication.getStatus())
                        .eq(DmsApprovalProcess::getApplyId, dmsManageApplication.getId())
                        .update();
                if (dmsManageApplication.getStatus() == 6) { //审核通过时执行操作

                    QueryWrapper<DmsNewRecord> dmsNewRecordQueryWrapper = new QueryWrapper<>();
                    dmsNewRecordQueryWrapper.eq("stu_no", dmsManageApplication.getStuNo())
                            .orderByDesc("id");
                    List<DmsNewRecord> stuRecords = _newRecordMapper.selectList(dmsNewRecordQueryWrapper);
                    QueryWrapper<DmsNewRange> rangeQuery = new QueryWrapper<>();
                    rangeQuery.eq("range_status", 1)
                            .last("limit 1");
                    DmsNewRange range = _rangeMapper.selectOne(rangeQuery);
                    Date startDate;

                    DmsNewRecord record;
                    if (stuRecords.size() == 0) {
                        record = new DmsNewRecord();
                        record.setStuNo(dmsManageApplication.getStuNo());
                        record.setRoomId(dmsManageApplication.getTargetDormId());
                        record.setStartDate(range.getStartDate());
                        record.setEndDate(range.getEndDate());
                        startDate = range.getStartDate();
                    } else {
                        record = stuRecords.get(0);
                        record.setEndDate(dmsManageApplication.getTime());
                        startDate = record.getStartDate();
                    }

                    DmsDormitory dormitory = dormitoryMapper.selectById(dmsManageApplication.getCurrentDormId());
                    // 计算住宿时间
                    Calendar endTime = Calendar.getInstance();
                    Calendar startTime = Calendar.getInstance();
                    startTime.setTime(startDate);
                    endTime.setTime(dmsManageApplication.getTime());
                    endTime.add(Calendar.DATE, -1);

                    int i1 = startTime.get(Calendar.DAY_OF_MONTH);
                    int i2 = endTime.get(Calendar.DAY_OF_MONTH);
                    double month = 0.5;
                    if (i2 >= 15 && i1 <= 15) month = 1;
                    int yearDiff = endTime.get(Calendar.YEAR) - startTime.get(Calendar.YEAR);
                    int monthDiff = endTime.get(Calendar.MONTH) - startTime.get(Calendar.MONTH);
                    double totalMonthDiff = yearDiff * 12 + monthDiff + month;

                    record.setEndDate(endTime.getTime());

                    record.setInMonth(new BigDecimal(totalMonthDiff));
                    record.setRangeCode(range.getRangeCode());
                    record.setNeedMoney(record.getInMonth().multiply(dormitory.getChargeStandard().divide(new BigDecimal("10"), 2, RoundingMode.HALF_UP)));
                    record.setMainMoney(dormitory.getChargeStandard());
                    record.setApplyStatus("6");

                    _newRecordService.saveOrUpdate(record);

                    if (dmsManageApplication.getType() == 1) { //调宿申请表操作
                        QueryWrapper<SrsDormitoryStudent> domStuQuery = new QueryWrapper<>();
                        domStuQuery.eq("stu_no", dmsManageApplication.getStuNo())
                                .last("limit 1");

                        SrsDormitoryStudent domStu = dormitoryStudentMapper.selectOne(domStuQuery);

                        if (domStu == null) {
                            domStu = new SrsDormitoryStudent();
                            domStu.setStuNo(dmsManageApplication.getStuNo());
                        }


                        QueryWrapper<SrsStuYear> yearQuery = new QueryWrapper<>();
                        yearQuery.eq("xndm", range.getXndm())
                                .last("limit 1");
                        SrsStuYear year = _yearMapper.selectOne(yearQuery);


                        Date checkInTime = dmsManageApplication.getTime();


                        if (isToday(checkInTime)) {
                            Instant instant = checkInTime.toInstant();
                            LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();

                            domStu.setCheckinTime(localDateTime);
                            domStu.setDormitoryId(dmsManageApplication.getTargetDormId());
                            _domStuService.saveOrUpdate(domStu);

                            DmsDormitory newDom = dormitoryMapper.selectById(dmsManageApplication.getTargetDormId());

                            DmsNewRecord newRecord = new DmsNewRecord();
                            newRecord.setStartDate(dmsManageApplication.getTime());
                            newRecord.setEndDate(range.getEndDate());
                            newRecord.setRoomId(newDom.getId());

                            Calendar endTime1 = Calendar.getInstance();
                            Calendar startTime1 = Calendar.getInstance();
                            startTime1.setTime(dmsManageApplication.getTime());
                            endTime1.setTime(range.getEndDate());

                            int i11 = startTime1.get(Calendar.DAY_OF_MONTH);
                            int i21 = endTime1.get(Calendar.DAY_OF_MONTH);
                            double month1 = 0.5;
                            if (i21 >= 15 && i11 <= 15) month1 = 1;
                            int yearDiff1 = endTime1.get(Calendar.YEAR) - startTime1.get(Calendar.YEAR);
                            int monthDiff1 = endTime1.get(Calendar.MONTH) - startTime1.get(Calendar.MONTH);
                            double totalMonthDiff1 = yearDiff1 * 12 + monthDiff1 + month1;

                            newRecord.setInMonth(new BigDecimal(totalMonthDiff1));
                            newRecord.setRangeCode(range.getRangeCode());
                            newRecord.setNeedMoney(newRecord.getInMonth().multiply(newDom.getChargeStandard().divide(new BigDecimal("10"), 2, RoundingMode.HALF_UP)));
                            newRecord.setMainMoney(newDom.getChargeStandard());
                            newRecord.setApplyStatus("6");
                            newRecord.setStuNo(dmsManageApplication.getStuNo());
                            newRecord.setStuYearId(year.getId());
                            newRecord.setBankCard(record.getBankCard());

                            _newRecordMapper.insert(newRecord);

                            dormitory.setOccupancy(dormitory.getOccupancy() - 1);

                            DmsDormitory dom = new DmsDormitory();
                            dom.setId(newDom.getId());
                            dom.setOccupancy(newDom.getOccupancy() + 1);
                            int res1 = dormitoryMapper.updateById(dom);
                            if (res1 == 0) {
                                throw new Exception("更新新宿舍入住人数失败");
                            }

                            DmsNewTask task = new DmsNewTask();
                            task.setTaskWant(checkInTime);
                            task.setOldDormId(dmsManageApplication.getCurrentDormId());
                            task.setNewDormId(dmsManageApplication.getTargetDormId());
                            task.setStuNo(dmsManageApplication.getStuNo());
                            task.setTaskType("1");
                            task.setTaskStatus("1");
                            task.setTaskRun(getNowDate());

                            int taskRes = _taskMapper.insert(task);
                            if (taskRes == 0) {
                                throw new Exception("插入修改宿舍计划失败");
                            }


                        } else {
                            DmsNewTask task = new DmsNewTask();
                            task.setTaskWant(checkInTime);
                            task.setOldDormId(dmsManageApplication.getCurrentDormId());
                            task.setNewDormId(dmsManageApplication.getTargetDormId());
                            task.setStuNo(dmsManageApplication.getStuNo());
                            task.setTaskType("1");
                            task.setTaskStatus("2");

                            int taskRes = _taskMapper.insert(task);
                            if (taskRes == 0) {
                                throw new Exception("插入修改宿舍计划失败");
                            }
                        }
                        int res = dormitoryMapper.updateById(dormitory);
                        if (res == 0) {
                            throw new Exception("更新旧宿舍人数失败");
                        }

                    } else if (dmsManageApplication.getType() == 2) { //退宿申请表操作
                        QueryWrapper<SrsDormitoryStudent> domStuQuery = new QueryWrapper<>();
                        domStuQuery.eq("stu_no", dmsManageApplication.getStuNo())
                                .last("limit 1");

                        SrsDormitoryStudent domStu = dormitoryStudentMapper.selectOne(domStuQuery);

                        Date checkInTime = dmsManageApplication.getTime();
                        if (isToday(checkInTime)) {
                            if (domStu.getId() != null) {
                                int res = dormitoryStudentMapper.deleteById(domStu.getId());
                                if (res == 0) {
                                    throw new Exception("删除学生与宿舍关联记录失败");
                                }
                            }
                            dormitory.setOccupancy(dormitory.getOccupancy() - 1);

                            DmsNewTask task = new DmsNewTask();
                            task.setTaskWant(checkInTime);
                            task.setOldDormId(dmsManageApplication.getCurrentDormId());
                            task.setStuNo(dmsManageApplication.getStuNo());
                            task.setTaskType("2");
                            task.setTaskStatus("1");
                            task.setTaskRun(getNowDate());

                            int taskRes = _taskMapper.insert(task);
                            if (taskRes == 0) {
                                throw new Exception("插入修改宿舍计划失败");
                            }

                        } else {
                            DmsNewTask task = new DmsNewTask();
                            task.setTaskWant(checkInTime);
                            task.setOldDormId(dmsManageApplication.getCurrentDormId());
                            task.setStuNo(dmsManageApplication.getStuNo());
                            task.setTaskType("2");
                            task.setTaskStatus("2");

                            int taskRes = _taskMapper.insert(task);
                            if (taskRes == 0) {
                                throw new Exception("插入修改宿舍计划失败");
                            }
                        }
                        int res = dormitoryMapper.updateById(dormitory);
                        if (res == 0) {
                            throw new Exception("更新旧宿舍人数失败");
                        }
                    }
                }
                dmsManageApplication.setStatus(dmsManageApplication.getStatus() == 6 ? 3L : -1L);
            }
            int res = dmsManageApplicationMapper.updateDmsManageApplication(dmsManageApplication);
            if (res == 0) {
                throw new Exception("更新记录失败");
            }

            List<DmsDormitory> dormList = dormitoryMapper.listDormCount();
            boolean doUpdateDormStu = _dormService.updateBatchById(dormList);
            if (!doUpdateDormStu) {
                throw new Exception("更新房间入住人数失败");
            }

            transactionManager.commit(status);
            return AjaxResult.success();
        } catch (Exception ex) {
            transactionManager.rollback(status);
            return AjaxResult.error(ex.getMessage());
        }

    }

    /**
     * 批量删除宿舍管理申请
     *
     * @param ids 需要删除的宿舍管理申请主键
     * @return 结果
     */
    @Override
    public int deleteDmsManageApplicationByIds(Long[] ids) {
        return dmsManageApplicationMapper.deleteDmsManageApplicationByIds(ids);
    }

    /**
     * 删除宿舍管理申请信息
     *
     * @param id 宿舍管理申请主键
     * @return 结果
     */
    @Override
    public int deleteDmsManageApplicationById(Long id) {
        return dmsManageApplicationMapper.deleteDmsManageApplicationById(id);
    }

    @Override
    public AjaxResult stuDel(Long[] ids) {
        try {
            QueryWrapper<DmsManageApplication> applyQuery = new QueryWrapper<>();
            applyQuery.in("id", ids)
                    .ne("stu_no", getUsername())
                    .ne("status", 0);

            List<DmsManageApplication> list = dmsManageApplicationMapper.selectList(applyQuery);
            QueryWrapper<DmsApprovalProcess> apQuery = new QueryWrapper<>();
            apQuery.in("apply_id", ids);

            approvalProcessMapper.delete(apQuery);

            if (list.size() > 0) {
                throw new Exception("不可删除");
            }
            int res = dmsManageApplicationMapper.deleteDmsManageApplicationByIds(ids);
            if (res == 0) {
                throw new Exception("删除失败");
            }
            return AjaxResult.success();
        } catch (Exception ex) {
            return AjaxResult.error(ex.getMessage());
        }
    }

    public void changeTask() {

        List<DmsNewTask> taskList = new ArrayList<>();
        LocalDate currentDate = LocalDate.now();
        Date nowDate = getNowDate();
        QueryWrapper<DmsNewTask> taskQuery = new QueryWrapper<>();
        taskQuery.eq("task_status", "2")
                .eq("task_want", currentDate);
        taskList = _taskMapper.selectList(taskQuery);

        for (DmsNewTask item : taskList) {
            TransactionDefinition def = new DefaultTransactionDefinition();
            TransactionStatus status = transactionManager.getTransaction(def);
            try {

                QueryWrapper<SrsDormitoryStudent> domStuQuery = new QueryWrapper<>();
                domStuQuery.eq("stu_no", item.getStuNo())
                        .last("limit 1");

                SrsDormitoryStudent domStu = dormitoryStudentMapper.selectOne(domStuQuery);

                if (domStu == null) {
                    domStu = new SrsDormitoryStudent();
                    domStu.setStuNo(item.getStuNo());
                }
                QueryWrapper<DmsNewRange> rangeQuery = new QueryWrapper<>();
                rangeQuery.eq("range_status", 1)
                        .last("limit 1");
                DmsNewRange range = _rangeMapper.selectOne(rangeQuery);

                QueryWrapper<SrsStuYear> yearQuery = new QueryWrapper<>();
                yearQuery.eq("xndm", range.getXndm())
                        .last("limit 1");
                SrsStuYear year = _yearMapper.selectOne(yearQuery);

                QueryWrapper<DmsNewRecord> dmsNewRecordQueryWrapper = new QueryWrapper<>();
                dmsNewRecordQueryWrapper.eq("stu_no", item.getStuNo())
                        .orderByDesc("id");
                List<DmsNewRecord> stuRecords = _newRecordMapper.selectList(dmsNewRecordQueryWrapper);

                DmsNewRecord record;
                if (stuRecords.size() == 0) {
                    record = new DmsNewRecord();
                } else {
                    record = stuRecords.get(0);
                }

                if (Objects.equals(item.getTaskType(), "1")) { //调宿申请表操作
                    Date checkInTime = item.getTaskWant();

                    Instant instant = checkInTime.toInstant();
                    LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();

                    domStu.setCheckinTime(localDateTime);
                    domStu.setDormitoryId(item.getNewDormId());
                    _domStuService.saveOrUpdate(domStu);

                    DmsDormitory newDom = dormitoryMapper.selectById(item.getNewDormId());

                    QueryWrapper<SrsStudent> stuQuery = new QueryWrapper<>();
                    stuQuery.eq("stu_no", item.getStuNo())
                            .last("limit 1");
                    SrsStudent stu = _stuMapper.selectOne(stuQuery);
                    if (stu == null) {
                        throw new Exception("该生不存在");
                    }

                    DmsNewRecord newRecord = new DmsNewRecord();
                    newRecord.setStartDate(checkInTime);
                    newRecord.setEndDate(range.getEndDate());
                    newRecord.setRoomId(newDom.getId());

                    Calendar endTime1 = Calendar.getInstance();
                    Calendar startTime1 = Calendar.getInstance();
                    startTime1.setTime(checkInTime);
                    endTime1.setTime(range.getEndDate());

                    int i11 = startTime1.get(Calendar.DAY_OF_MONTH);
                    int i21 = endTime1.get(Calendar.DAY_OF_MONTH);
                    double month1 = 0.5;
                    if (i21 >= 15 && i11 <= 15) month1 = 1;
                    int yearDiff1 = endTime1.get(Calendar.YEAR) - startTime1.get(Calendar.YEAR);
                    int monthDiff1 = endTime1.get(Calendar.MONTH) - startTime1.get(Calendar.MONTH);
                    double totalMonthDiff1 = yearDiff1 * 12 + monthDiff1 + month1;

                    newRecord.setInMonth(new BigDecimal(totalMonthDiff1));
                    newRecord.setRangeCode(range.getRangeCode());
                    newRecord.setNeedMoney(newRecord.getInMonth().multiply(newDom.getChargeStandard().divide(new BigDecimal("10"), 2, RoundingMode.HALF_UP)));
                    newRecord.setMainMoney(newDom.getChargeStandard());
                    newRecord.setApplyStatus("6");
                    newRecord.setStuNo(item.getStuNo());
                    newRecord.setStuYearId(year.getId());
                    newRecord.setBankCard(record.getBankCard());

                    _newRecordMapper.insert(newRecord);

                    DmsDormitory dormitory = dormitoryMapper.selectById(item.getOldDormId());
                    dormitory.setOccupancy(dormitory.getOccupancy() - 1);
                    DmsDormitory dom = new DmsDormitory();
                    dom.setId(newDom.getId());
                    dom.setOccupancy(newDom.getOccupancy() + 1);
                    dormitoryMapper.updateById(dom);
                    dormitoryMapper.updateById(dormitory);

                }

                if (Objects.equals(item.getTaskType(), "2")) { //退宿操作

                    if (domStu.getId() != null) {
                        dormitoryStudentMapper.deleteById(domStu.getId());
                    }

                    DmsDormitory dormitory = dormitoryMapper.selectById(item.getOldDormId());
                    dormitory.setOccupancy(dormitory.getOccupancy() - 1);
                    int res = dormitoryMapper.updateById(dormitory);
                    if (res == 0) {
                        throw new Exception("修改宿舍人数失败");
                    }
                }

                transactionManager.commit(status);
                item.setTaskStatus("1");
                item.setTaskRun(getNowDate());
            } catch (Exception ex) {
                transactionManager.rollback(status);
                item.setTaskStatus("0");
                item.setRemark(ex.getMessage());
                item.setTaskRun(getNowDate());
            }

        }

        _taskService.updateBatchById(taskList);

        List<DmsDormitory> dormList = dormitoryMapper.listDormCount();
        _dormService.updateBatchById(dormList);


    }


}
