package com.yida.data.school.facility.controller;

import cc.mrbird.febs.common.redis.service.RedisService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yida.data.common.core.common.ResultBean;
import com.yida.data.common.core.entity.CurrentUser;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.school.EduDormitoryRoom;
import com.yida.data.common.core.exception.FebsException;
import com.yida.data.common.core.utils.Asserts;
import com.yida.data.common.core.utils.ExcelUtil;
import com.yida.data.common.core.utils.FebsUtil;
import com.yida.data.common.core.utils.FileUtil;
import com.yida.data.common.core.vo.ImportPercentVO;
import com.yida.data.school.dto.facility.BatchGenerateDormRoomDTO;
import com.yida.data.school.dto.index.EditPersonNumDTO;
import com.yida.data.school.dto.index.ImportDormRoomDTO;
import com.yida.data.school.dto.index.ListDormRoomDTO;
import com.yida.data.school.dto.index.PageDormRoomDTO;
import com.yida.data.school.facility.service.EduDormitoryRoomService;
import com.yida.data.school.vo.index.DormRoomInfoVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.io.InputStream;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@Api(tags = "宿舍-寝室")
@Slf4j
@RestController
@RequestMapping("/facility/dormRoom")
@RequiredArgsConstructor
public class EduDormitoryRoomController {

    private final EduDormitoryRoomService eduDormitoryRoomService;
    private final RedisService redisService;

    @ApiOperation("寝室分页查询")
    @GetMapping("/listDormRoomPage")
    public ResultBean<IPage<DormRoomInfoVO>> listDormRoomPage(PageDormRoomDTO dto) {
        Asserts.isNotNull(dto.getDormId(), "请选择宿舍楼");
        return ResultBean.buildSuccess(eduDormitoryRoomService.listDormRoomPage(dto));
    }

    @ApiOperation("保存寝室")
    @PostMapping("/saveDormRoom")
    public ResultBean saveDormRoom(@RequestBody EduDormitoryRoom dormRoom) {
        LambdaQueryWrapper<EduDormitoryRoom> condition = Wrappers.<EduDormitoryRoom>lambdaQuery()
            .eq(EduDormitoryRoom::getDormId, dormRoom.getDormId())
            .eq(EduDormitoryRoom::getName, dormRoom.getName());
        if (dormRoom.getId() != null) {
            condition.ne(EduDormitoryRoom::getId, dormRoom.getId());
        }
        Asserts.isTrue(eduDormitoryRoomService.count(condition) == 0, "该寝室号已存在");
        eduDormitoryRoomService.saveOrUpdate(dormRoom);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("批量生成寝室")
    @PostMapping("/batchGenerateRoom")
    public ResultBean batchGenerateRoom(@RequestBody List<BatchGenerateDormRoomDTO> dtos) {
        eduDormitoryRoomService.batchGenerateRoom(dtos);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("批量删除寝室")
    @PostMapping("/deloDormRoomBatch")
    public ResultBean delDormRoomBatch(@RequestBody List<Long> ids) {
        eduDormitoryRoomService.delDormRoomBatch(ids);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("查询寝室列表")
    @PostMapping("/listDormRoom")
    public ResultBean<List<EduDormitoryRoom>> listDormRoom(@RequestBody ListDormRoomDTO dto) {
        return ResultBean.buildSuccess(eduDormitoryRoomService.listDormRoom(dto));
    }

    @ApiOperation("查询寝室")
    @GetMapping("/getDormRoom")
    public ResultBean<EduDormitoryRoom> getDormRoom(@RequestParam("id") Long id) {
        return ResultBean.buildSuccess(eduDormitoryRoomService.getDormRoom(id));
    }

    @ApiOperation("寝室入住")
    @PostMapping("/editPersonNum")
    public ResultBean editPersonNum(@RequestBody List<EditPersonNumDTO> dtos) {
        eduDormitoryRoomService.editPersonNum(dtos);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("寝室批量导入")
    @PostMapping("/importDormRoom")
    public ResultBean importDormRoom(MultipartFile file, Long dormId) {
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        eduDormitoryRoomService.importDormRoom(file, dormId, currentUser);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("寝室导入进度")
    @GetMapping("/importDormRoomPercent")
    public ResultBean<Object> importDormRoomPercent(Long dormId) {
        return ResultBean.buildSuccess(redisService.hget(CachePrefixConstant.IMPORT_DORM_ROOM,
            dormId.toString()));
    }

    @ApiOperation("下载错误数据")
    @PostMapping("/downloadErrorData")
    public void downloadErrorData(HttpServletResponse response, @RequestParam Long dormId) {
        ImportPercentVO percent = (ImportPercentVO) redisService.hget(CachePrefixConstant.IMPORT_DORM_ROOM,
            dormId.toString());
        ExcelUtil.export("错误数据.xlsx", ImportDormRoomDTO.class, percent.getError(), response);
    }

    @ApiOperation("下载导入模板")
    @PostMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) {
        InputStream inputStream = this.getClass().getClassLoader()
            .getResourceAsStream("template/index/dormRoomUpload.xlsx");
        try {
            FileUtil.download(inputStream, "寝室批量上传.xlsx", response);
        } catch (Exception e) {
            log.error("下载寝室批量上传模板失败", e);
            throw new FebsException("下载寝室批量上传模板失败");
        }
    }

    @ApiOperation("根据宿舍楼和寝室名查询寝室")
    @GetMapping("/getDormRoomByNameAndDorm")
    ResultBean<EduDormitoryRoom> getDormRoomByName(@RequestParam("name") String name,
        @RequestParam("dormId") Long dormId) {
        return ResultBean.buildSuccess(eduDormitoryRoomService.getOne(Wrappers.<EduDormitoryRoom>lambdaQuery()
            .eq(EduDormitoryRoom::getName, name)
            .eq(EduDormitoryRoom::getDormId, dormId)));
    }
}
