package com.srs.web.controller.dormitory;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.srs.common.annotation.Log;
import com.srs.common.core.controller.BaseController;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.core.domain.entity.SysUser;
import com.srs.common.core.page.TableDataInfo;
import com.srs.common.enums.BusinessType;
import com.srs.common.utils.poi.ExcelUtil;
import com.srs.comprehensive.domain.CphBiyeApply;
import com.srs.comprehensive.domain.SrsDormitory;
import com.srs.comprehensive.domain.SrsStudent;
import com.srs.comprehensive.domain.Vo.CphBiyeApplyVo;
import com.srs.comprehensive.domain.Vo.CphSearch;
import com.srs.comprehensive.domain.Vo.StuClass;
import com.srs.comprehensive.service.ISrsStudentService;
import com.srs.dormitory.domain.DormitoryImportModel;
import com.srs.dormitory.domain.Dto.*;
import com.srs.dormitory.domain.SrsDormitoryStudent;
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.service.IDmsDormitoryService;
import com.srs.dormitory.service.ISrsDormitoryStudentService;
import com.srs.dormitory.utils.DmsOperationLog;
import com.srs.stureg.domain.SrsStuReg;
import com.srs.system.domain.SysDeptMap;
import com.srs.system.service.ISysDeptMapService;
import com.srs.system.service.ISysPostService;
import com.srs.web.controller.common.RoleBool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import liquibase.pro.packaged.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * <p>
 * 宿舍学生关联表 前端控制器
 * </p>
 *
 * @author 猪油骨
 * @since 2023-07-14
 */
@Api(tags = "学生宿舍关联表信息")
@RestController
@RequestMapping("/dormitory/srs-dormitory-student")
public class SrsDormitoryStudentController extends BaseController {
    @Autowired
    private ISrsDormitoryStudentService srsDormitoryStudentService;

    @Autowired
    public IDmsDormitoryService _dormService;

    @Autowired
    public ISrsStudentService _stuService;

    @Autowired
    ISysPostService _postService;
    @Autowired
    ISysDeptMapService _deptMap;

    @PostMapping("/sendStudentConfirmMsg")
    public AjaxResult sendStudentConfirmMsg(@RequestBody SendConfirmDto param){
        return srsDormitoryStudentService.sendStudentConfirmMsg(param);
    }


    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<ImportDormStuDto> util = new ExcelUtil<ImportDormStuDto>(ImportDormStuDto.class);
        List<ImportDormStuDto> list = util.importExcel(file.getInputStream());
        String message = srsDormitoryStudentService.doImport(list, updateSupport);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        List<ImportDormStuDto> list = new ArrayList<>();
        ImportDormStuDto expample1 = new ImportDormStuDto();
        expample1.setStuNo("2021010101");
        expample1.campusName = "里建";
        expample1.parkName = "和园";
        expample1.buildingName = "9栋";
        expample1.floor = "1";
        expample1.roomNo = "101";
        list.add(expample1);
        ImportDormStuDto expample2 = new ImportDormStuDto();
        expample2.setStuNo("2021010102");
        expample2.campusName = "长堽";
        expample2.parkName = "长堽校区默认园区";
        expample2.buildingName = "长江阁";
        expample2.floor = "5";
        expample2.roomNo = "513";
        list.add(expample2);
        ExcelUtil<ImportDormStuDto> util = new ExcelUtil<ImportDormStuDto>(ImportDormStuDto.class);
        util.exportExcel(response, list, "学生宿舍数据");
    }

    @GetMapping("/listJwc")
    public TableDataInfo listJwc(CphSearch param) {
        boolean hasRole = RoleBool.isJwc(getUserId(), _postService);
        if (hasRole) {
            startPage();
            List<StuClass> list = srsDormitoryStudentService.listView(param);
            return getDataTable(list);
        } else {
            List<String> list = new ArrayList<>();
            return getDataTable(list);
        }
    }


    @GetMapping("/listXw")
    public TableDataInfo listXw(CphSearch param) {
        boolean hasRole = RoleBool.isXw(getUserId(), _postService);
        if (hasRole) {
            Long oldId = getDeptId();
            SysDeptMap dept = _deptMap.getOldDeptByNewId(oldId);
            Long deptId = null;
            if(dept != null){
                deptId = dept.getOldDeptId();
            }
            param.setDeptId(deptId);
            startPage();
            List<StuClass> list = srsDormitoryStudentService.listView(param);
            return getDataTable(list);
        } else {
            List<String> list = new ArrayList<>();
            return getDataTable(list);
        }
    }

    @GetMapping("/listFdy")
    public TableDataInfo listFdy(CphSearch param) {
        boolean hasRole = RoleBool.isFdy(getUserId(), _postService);
        if (hasRole) {
            param.setTNo(getUsername());
            startPage();
            List<StuClass> list = srsDormitoryStudentService.listView(param);
            return getDataTable(list);
        } else {
            List<String> list = new ArrayList<>();
            return getDataTable(list);
        }
    }

    @GetMapping("/getStuLog/{stuNo}")
    public AjaxResult getStuLog(@PathVariable String stuNo) {
        boolean hasRole = RoleBool.isHigh(getUserId(), _postService);
        if (hasRole) {
            return srsDormitoryStudentService.getStuLog(stuNo);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }

    @GetMapping("/getOwnLog")
    public AjaxResult getOwnLog() {
        return srsDormitoryStudentService.getStuLog(getUsername());
    }


    @ApiOperation(value = "学生自主选择床位", notes = "id不用填写,只能选择是当前学生班级并且为空的宿舍床位", response = StudentDormitoryDto.class)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody StudentDormitoryDto dto) {
            boolean hasRole = RoleBool.isHigh(getUserId(), _postService);
            if (hasRole) {
                DomInfo dorm = _dormService.getDormHas(dto.getDormitoryId());
                SrsStudent stu = _stuService.getStuInfo(dto.getStuNo());
                if (stu == null) {
                    return AjaxResult.error("学号不存在");
                }
                QueryWrapper<SrsDormitoryStudent> query = new QueryWrapper<>();
                query.eq("stu_no", dto.getStuNo());
                SrsDormitoryStudent find = srsDormitoryStudentService.getOne(query);
                if (find != null) {
                    return AjaxResult.error("该生已分配宿舍");
                }
                if(dorm!=null) {
                    if (!Objects.equals(stu.getGender(), dorm.gender)) {
                        return AjaxResult.error("学生性别与宿舍性别不符");
                    }
                }
                SrsDormitoryStudent param = new SrsDormitoryStudent();
                if(dto.getIsInStudentsleep().equals("否")||dto.getIsInStudentsleep().equals("外宿")||dto.getIsInStudentsleep().equals("外出实习")){
                    param.setDormitoryId(null);
                    param.setBedId(null);
                    param.setStuNo(dto.getStuNo());
                    param.setIsDormitoryHead(0);
                    param.setStatus(0);
                    param.setCheckinTime(null);
                    param.setIsInStudentsleep(dto.getIsInStudentsleep());
                }
                if(dorm!=null) {
                    if (dorm.bedNum > dorm.occupancy) {
//                    param.setStuNo(dto.getStuNo());
//                    param.setDormitoryId(dto.getDormitoryId());
//                    param.setCheckinTime(dto.checkinTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                        if (dto.getIsInStudentsleep().equals("是")) {
                            param.setCheckinTime(dto.getCheckinTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                            BeanUtils.copyProperties(dto, param);
                        }

                    } else {
                        return AjaxResult.error("宿舍床位不够");
                    }
                }
                return toAjax(srsDormitoryStudentService.save(param));
            } else {
                return AjaxResult.error(401, "你无权做这些");
            }
        }



    @ApiOperation(value = "学生自主选择床位", notes = "id不用填写,只能选择是当前学生班级并且为空的宿舍床位", response = StudentDormitoryDto.class)
    @PostMapping("/addCheckInInformation")
    public AjaxResult addCheckInInformation(@RequestBody StudentDormitoryDto dto) {
        DomInfo dorm = _dormService.getDormHas(dto.getDormitoryId());
        SrsStudent stu = _stuService.getStuInfo(dto.getStuNo());
        if (stu == null) {
            return AjaxResult.error("学号不存在");
        }
        QueryWrapper<SrsDormitoryStudent> query = new QueryWrapper<>();
        query.eq("stu_no", dto.getStuNo());
        SrsDormitoryStudent find = srsDormitoryStudentService.getOne(query);
        if (find != null) {
            return AjaxResult.error("该生已分配宿舍");
        }
        if(dorm!=null) {
            if (!Objects.equals(stu.getGender(), dorm.gender)) {
                return AjaxResult.error("学生性别与宿舍性别不符");
            }
        }
        SrsDormitoryStudent param = new SrsDormitoryStudent();
        if(dto.getIsInStudentsleep().equals("否")||dto.getIsInStudentsleep().equals("外宿")||dto.getIsInStudentsleep().equals("外出实习")){
            param.setDormitoryId(null);
            param.setBedId(null);
            param.setStuNo(dto.getStuNo());
            param.setIsDormitoryHead(0);
            param.setStatus(0);
            param.setCheckinTime(null);
            param.setIsInStudentsleep(dto.getIsInStudentsleep());
        }
        if(dorm!=null) {
            if (dorm.bedNum > dorm.occupancy) {
//                    param.setStuNo(dto.getStuNo());
//                    param.setDormitoryId(dto.getDormitoryId());
//                    param.setCheckinTime(dto.checkinTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                if (dto.getIsInStudentsleep().equals("是")) {
                    param.setCheckinTime(dto.getCheckinTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                    BeanUtils.copyProperties(dto, param);
                }

            } else {
                return AjaxResult.error("宿舍床位不够");
            }
        }
        return toAjax(srsDormitoryStudentService.save(param));
    }
    @GetMapping("/list")
    public TableDataInfo list(DmsSearch param) {
        boolean hasRole = RoleBool.isHigh(getUserId(), _postService);
        if (hasRole) {
            startPage();
            List<SrsDormitoryStudentVo> list = srsDormitoryStudentService.list(param);
            return getDataTable(list);
        } else {
            List<String> list = new ArrayList<>();
            return getDataTable(list);
        }
    }

    @PreAuthorize("@ss.hasPermi('dms:dormStu:add')")
    @GetMapping("/checkInInformation")
    public TableDataInfo checkInInformation(DmsSearch param) {
        startPage();
        List<SrsDormitoryStudentVo> list = srsDormitoryStudentService.list(param);
        return getDataTable(list);
    }


    @ApiOperation("查询学生宿舍关联列表")
    @PostMapping("/list")
    public TableDataInfo getList(@RequestBody DormitoryQueryDto queryDto) {
        boolean hasRole = RoleBool.isHigh(getUserId(), _postService);
        if (hasRole) {
            startPage();
            List<Map<String, Object>> list = srsDormitoryStudentService.getList(queryDto);
            return getDataTable(list);
        } else {
            List<String> list = new ArrayList<>();
            return getDataTable(list);
        }
    }

    @ApiOperation("根据关联表id查看详情")
    @GetMapping("/{id}")
    public AjaxResult get(@PathVariable Long id) {
        return srsDormitoryStudentService.get(id);
    }

    @ApiOperation("取消选择床位")
    @PostMapping("/cancel")
    public AjaxResult cancel() {
        return srsDormitoryStudentService.cancel();
    }


    @ApiOperation(value = "管理员分配学生床位", notes = "id不用填写", response = StudentDormitoryDto.class)
    @PostMapping("/admin/add")
    public AjaxResult adminAdd(@RequestBody StudentDormitoryDto studentDormitoryDto) {
        return srsDormitoryStudentService.AdminAddStudentDormitory(studentDormitoryDto);
    }

    @ApiOperation(value = "批量删除学生宿舍关联")
    @PostMapping("/delete/{id}")
    public AjaxResult delete(@PathVariable("id") List<Long> ids) {
        return srsDormitoryStudentService.batchDelete(ids);
    }

    @ApiOperation(value = "根据id修改学生宿舍关联表")
    @PostMapping("/update")
    public AjaxResult update(@RequestBody StudentDormitoryDto studentDormitoryDto) {
        SrsDormitoryStudent dormitoryStudent = new SrsDormitoryStudent();
        String sleep = studentDormitoryDto.getIsInStudentsleep();
        if("否".equals(sleep) || "外宿".equals(sleep) || "外出实习".equals(sleep)){
            dormitoryStudent.setId(studentDormitoryDto.getId());
            dormitoryStudent.setDormitoryId(null);
            dormitoryStudent.setBedId(null);
            dormitoryStudent.setStuNo(studentDormitoryDto.getStuNo());
            dormitoryStudent.setIsDormitoryHead(0);
            dormitoryStudent.setStatus(0);
            dormitoryStudent.setCheckinTime(null);
            dormitoryStudent.setIsInStudentsleep(sleep);
        }else{
            if (studentDormitoryDto.getCheckinTime() != null) {
                dormitoryStudent.setCheckinTime(studentDormitoryDto.getCheckinTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
            } else {
                dormitoryStudent.setCheckinTime(null);
            }
            BeanUtils.copyProperties(studentDormitoryDto, dormitoryStudent);
        }
        //boolean b = srsDormitoryStudentService.updateById(dormitoryStudent);
        boolean b=srsDormitoryStudentService.updateSrsDormitoryStudent(dormitoryStudent);
        return toAjax(b);
    }

    //    @DmsOperationLog(title = "学生宿舍关联表",content = "自动分配床位")
//    @ApiOperation(value = "自动分配床位",notes = "输入班级id列表，自动将该班级的学生分配到该班级的宿舍")
//    @PostMapping("/batch/add")
//    public AjaxResult batchAdd(@RequestBody List<String> majorCodes){
//        return srsDormitoryStudentService.batchAdd(majorCodes);
//    }
    @ApiOperation("查看还没有选择床位的学生列表")
    @PostMapping("/noBed/list")
    public TableDataInfo getNoBedStudent() {
        startPage();
        List<SrsStuReg> list = srsDormitoryStudentService.getNoBedStudent();
        return getDataTable(list);
    }

    @ApiOperation("毕业学生一键退宿")
    @PostMapping("/out")
    public AjaxResult out(@ApiParam(value = "年级ID") @RequestBody Long gradeId,
                          @ApiParam(value = "学院ID") @RequestBody(required = false) Long deptId,
                          @ApiParam(value = "专业ID") @RequestBody(required = false) Long majorId) {
        return srsDormitoryStudentService.out(gradeId, deptId, majorId);
    }

    @ApiOperation("新生请求分配宿舍")
    @PostMapping("/allocate-dormitory")
    public AjaxResult allocateDormitory() {
        return srsDormitoryStudentService.allocateDormitory();
    }

    @ApiOperation("数据导入")
    @PostMapping("/import")
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<DormitoryImportModel> util = new ExcelUtil<>(DormitoryImportModel.class);
        List<DormitoryImportModel> list = util.importExcel(file.getInputStream());
        return srsDormitoryStudentService.importData(list);
    }

    @ApiOperation("导出宿舍信息表")
    @PostMapping("/export")
    public void export(HttpServletResponse response, DmsSearch param) {
        List<DomInfo> list = srsDormitoryStudentService.doExport(param);
        ExcelUtil<DomInfo> util = new ExcelUtil<>(DomInfo.class);
        util.exportExcel(response, list, "宿舍学生数据");
    }
    @ApiOperation("统计学院获奖的宿舍的间数")
    @GetMapping("/rankingCount")
    public AjaxResult rankingCount() {
        return srsDormitoryStudentService.rankingCount();
    }
}
