package com.srs.web.controller.dormitory;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.Vo.CphSearch;
import com.srs.dormitory.domain.DmsApprovalProcess;
import com.srs.dormitory.domain.DmsDormitory;
import com.srs.dormitory.domain.DmsDormitoryClass;
import com.srs.dormitory.domain.DmsNewReg;
import com.srs.dormitory.domain.Dto.*;
import com.srs.dormitory.domain.Vo.ClassInfo;
import com.srs.dormitory.domain.Vo.DomInfo;
import com.srs.dormitory.service.IDmsDormitoryClassService;
import com.srs.dormitory.service.ISrsDormitoryStudentService;
import com.srs.stureg.domain.SrsStuReg;
import com.srs.stureg.domain.VO.TeacherVo;
import com.srs.stureg.mapper.SrsStuRegMapper;
import com.srs.stureg.service.ISrsStuRegService;
import com.srs.system.service.ISysPostService;
import com.srs.web.controller.common.RoleBool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

import static com.srs.common.utils.PageUtils.startPage;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 猪油骨
 * @since 2023-07-25
 */
@RestController
@RequestMapping("/dormitory/dms-dormitory-class")
@Api(tags = "分配宿舍")
@AllArgsConstructor
public class DmsDormitoryClassController extends BaseController {
    private final IDmsDormitoryClassService iDmsDormitoryClassService;

    @Autowired
    ISysPostService _postService;

    @Autowired
    private SrsStuRegMapper stuRegMapper;


    @Autowired
    private ISrsDormitoryStudentService iDormitoryStudentService;


    @ApiOperation("自动分配宿舍")
    @PostMapping("/autoDorm")
    public AjaxResult autoDorm(){
        return iDormitoryStudentService.assignDormitoryByTeacher(getUsername());
    }


    @ApiOperation("锁定班级分配")
    @PostMapping("/lockDmsClass/{id}")
    public AjaxResult lockDmsClass(@PathVariable("id") Long id){
        boolean hasRole = RoleBool.isXw(getUserId(), _postService);
        if (hasRole) {
            return iDmsDormitoryClassService.lockDmsClass(id);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }


    @ApiOperation("新生分配宿舍")
    @PostMapping("/addReg")
    public AjaxResult addReg(@RequestBody DmsNewReg param){
        boolean hasRole = RoleBool.isHigh(getUserId(), _postService);
        if (hasRole) {
            return iDmsDormitoryClassService.addReg(param);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }

    @ApiOperation("取消新生分配宿舍")
    @PostMapping("/cancelReg")
    public AjaxResult cancelReg(@RequestBody DmsNewReg param){
        boolean hasRole = RoleBool.isHigh(getUserId(), _postService);
        if (hasRole) {
            return iDmsDormitoryClassService.cancelReg(param);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }



    @ApiOperation("辅导员快速分配宿舍")
    @PostMapping("/fastAllot")
    public AjaxResult fastAllot() {
        boolean hasRole = RoleBool.isFdy(getUserId(), _postService);
        if (hasRole) {
            String tNo = getUsername();
            return iDmsDormitoryClassService.fastAllot(tNo);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }


    @ApiOperation("通过宿舍id获取已分配新生")
    @GetMapping("/getRegByRoom/{id}")
    public AjaxResult getRegByRoom(@PathVariable("id") Long id) {
        return iDmsDormitoryClassService.getRegByRoom(id);
    }

    @ApiOperation("通过班级code获取新生")
    @GetMapping("/listClassStu/{code}")
    public AjaxResult listClassStu(@PathVariable("code") String classCode) {
        boolean hasRole = RoleBool.isHigh(getUserId(), _postService);
        if (hasRole) {
            return iDmsDormitoryClassService.listClassStu(classCode);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }

    @ApiOperation("通过班级code获取已缴费新生")
    @GetMapping("/listClassCanStu")
    public AjaxResult listClassCanStu(SrsStuReg param) {
        boolean hasRole = RoleBool.isHigh(getUserId(), _postService);
        if (hasRole) {
            return iDmsDormitoryClassService.listClassCanStu(param);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }


    @ApiOperation("列出学生自己可以选择的宿舍")
    @GetMapping("/listOwnCanSelectDorm")
    public AjaxResult listOwnCanSelectDorm() {
        boolean hasRole = RoleBool.isHigh(getUserId(), _postService);
        if (hasRole) {
            String ksh = getUsername();
            return iDmsDormitoryClassService.listOwnCanSelectDorm(ksh);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }


    @ApiOperation("修改宿舍是否开放给学生选择")
    @PostMapping("/changeRoomIsMixed")
    public AjaxResult changeRoomIsMixed(@RequestBody DmsDormitoryClass param) {
        boolean hasRole = RoleBool.isHigh(getUserId(), _postService);
        if (hasRole) {
            return iDmsDormitoryClassService.changeRoomIsMixed(param);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }


    @ApiOperation("列出分配到辅导员名下班级的宿舍")
    @GetMapping("/listFdyRoom")
    public TableDataInfo listFdyRoom() {
        boolean hasRole = RoleBool.isFdy(getUserId(), _postService);
        if (hasRole) {
            DmsSearch param = new DmsSearch();
            param.setTNo(getUsername());
            startPage();
            List<DomInfo> list = iDmsDormitoryClassService.listFdyRoom(param);
            return getDataTable(list);
        } else {
            List<String> list = new ArrayList<>();
            return getDataTable(list);
        }
    }


    @ApiOperation("学务调整班级宿舍床位")
    @PostMapping("/changeClassBed")
    public AjaxResult changeClassBed(@RequestBody List<ClassInfo> param) {
        boolean hasRole = RoleBool.isXw(getUserId(), _postService);
        if (hasRole) {
            return iDmsDormitoryClassService.changeClassBed(param);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }


    @ApiOperation("学务分配班级宿舍")
    @PostMapping("/xwDomClass")
    public AjaxResult xwDomClass(@RequestBody DeptClassDto param) {
        boolean hasRole = RoleBool.isXw(getUserId(), _postService);
        if (hasRole) {
            return iDmsDormitoryClassService.xwDomClass(param);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }

    @ApiOperation("查询学务下的班级")
    @GetMapping("/selectXwClass")
    public AjaxResult selectXwClass() {
        boolean hasRole = RoleBool.isXw(getUserId(), _postService);
        if (hasRole) {
            return iDmsDormitoryClassService.selectXwClass();
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }

    @ApiOperation("查询学务下的宿舍")
    @GetMapping("/selectXwDom")
    public TableDataInfo selectXwDom(SelectDormDto param) {
        boolean hasRole = RoleBool.isXw(getUserId(), _postService);
        if (hasRole) {
            List<DomInfo> list = iDmsDormitoryClassService.selectXwDom(param);
            return getDataTable(list);
        } else {
            List<String> list = new ArrayList<>();
            return getDataTable(list);
        }
    }


    /**
     * 辅导员进行宿舍区域划分
     *
     * @param allocateDto 划分宿舍区域的参数，包含班级代码（BJDM）、宿舍ID列表（dormitoryIds）和性别（gender）
     * @return 操作结果，成功则返回成功信息，否则抛出异常
     */
    @PostMapping("/allocate")
    @ApiOperation("辅导员划分宿舍区域")
    public AjaxResult allocate(@Validated @RequestBody AllocateDto allocateDto) {
        return iDmsDormitoryClassService.allocate(allocateDto);
    }

    @PostMapping("/delete")
    @ApiOperation("取消绑定某宿舍")
    public AjaxResult delete(@RequestBody List<Long> ids) {
        return iDmsDormitoryClassService.delete(ids);
    }

    @GetMapping("/selectDept")
    @ApiOperation("查看学院人数")
    public TableDataInfo selectClass() {
        return getDataTable(iDmsDormitoryClassService.selectClass());
    }

    /**
     * 辅导员查看所属班级
     *
     * @return 所属班级信息列表，以表格数据格式返回
     */
    @GetMapping("/selectMajor")
    @ApiOperation("辅导员查看所属班级")
    public TableDataInfo selectMajor() {
        return iDmsDormitoryClassService.selectMajor();
    }


    @ApiOperation("查看宿舍楼剩余宿舍")
    @GetMapping("/selectBuilding")
    public TableDataInfo selectBuilding(SelectBuildingDto dto) {
        boolean hasRole = RoleBool.isXw(getUserId(), _postService);
        if (hasRole) {
            return getDataTable(iDmsDormitoryClassService.selectBuilding(dto));
        } else {
            List<String> list = new ArrayList<>();
            return getDataTable(list);
        }
    }

    @ApiOperation("根据楼栋id查看宿舍")
    @GetMapping("/selectDorm")
    public TableDataInfo selectDorm(SelectDormDto dto) {
        boolean hasRole = RoleBool.isXw(getUserId(), _postService);
        if (hasRole) {
            return getDataTable(iDmsDormitoryClassService.selectDorm(dto));
        } else {
            List<String> list = new ArrayList<>();
            return getDataTable(list);
        }
    }

    @ApiOperation("根据宿舍楼id查询楼层")
    @GetMapping("/selectFloor")
    public TableDataInfo selectFloor(Long build) {
        return getDataTable(iDmsDormitoryClassService.selectFloor(build));
    }


//    @ApiOperation("学生查看宿舍")
//    @GetMapping("/selectDormByStu")
//    public TableDataInfo selectFloor() {
//        return getDataTable(iDmsDormitoryClassService.selectDormByStu());
//    }

    @Log(title = "导出宿舍成员", businessType = BusinessType.EXPORT)
    @PostMapping("/import")
    @ApiOperation("导出宿舍成员")
    public void imports(HttpServletResponse response,DormitoryModelDto dormitoryModelDto){
        // 创建空的 dorm 列表，并填充数据
        List<DormitoryModelDto> dorm = new ArrayList<>();

// 获取老师信息
        TeacherVo tea = new TeacherVo();
        tea.setTno(getUsername());
        List<TeacherVo> list = stuRegMapper.getDmsClassList(tea);

// 确保 list 不为空
        if (list != null) {
            // 将 list 中的每个 TeacherVo 转换为 DormitoryModelDto
            for (TeacherVo teacher : list) {
                DormitoryModelDto dto = new DormitoryModelDto();
                dto.setId(teacher.getId());
                dto.setDorm(teacher.getDorm());
                dto.setKSH(teacher.getKSH());
                dto.setXSXM(teacher.getXSXM());
                dto.setBJ(teacher.getBJ());
                dorm.add(dto); // 将转换后的对象添加到 dorm 列表中
            }
        }

// 使用 ExcelUtil 导出数据
        ExcelUtil<DormitoryModelDto> util = new ExcelUtil<>(DormitoryModelDto.class);
        util.exportExcel(response, dorm, "宿舍成员数据");

    }
    /**
     * 导出宿舍管理审核列表
     */
//    @PreAuthorize("@ss.hasPermi('system:process:export')")
    @Log(title = "导出宿舍成员模板", businessType = BusinessType.EXPORT)
    @PostMapping("/importTemplate")
    @ApiOperation("导出宿舍成员模板")
    public void importTemplate(HttpServletResponse response,DormitoryModelDto dormitoryModelDto)
    {
        DormitoryModelDto param = new DormitoryModelDto();
        param.setTNo(getUsername());
        List<DormitoryModelDto> list = iDmsDormitoryClassService.getModelRoom(param);
        List<DormitoryModelDto> dorm=new ArrayList<>();
        DormitoryModelDto dto = new DormitoryModelDto();
        dto.setId(0000L);
        dto.setTNo(getUsername());
        dto.setDorm("长堽校区默认园区 黄河阁 000(男)");
        dto.setKSH("24400000");
        dto.setXSXM("张三");
        dorm.add(dto);
        int count=0;
        for (int i = 0; i < list.size(); i++) {
            DmsDormitory dmsDormitory=iDmsDormitoryClassService.getcount(list.get(i).getId());
            count =dmsDormitory.getBedNum();
            for (int j=0;j<count;j++){
                dorm.add(list.get(i));
            }
        }
        ExcelUtil<DormitoryModelDto> util = new ExcelUtil<DormitoryModelDto>(DormitoryModelDto.class);
        util.exportExcel(response,dorm, "宿舍成员数据");
    }
    @Log(title = "宿舍成员", businessType = BusinessType.IMPORT)
//    @PreAuthorize("@ss.hasPermi('dormitory:dms-dormitory-class:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<DormitoryModelDto> util = new ExcelUtil<DormitoryModelDto>(DormitoryModelDto.class);
        List<DormitoryModelDto> dormList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = iDmsDormitoryClassService.importUser(dormList, updateSupport, operName);
        return success(message);
    }
}
