package com.yida.data.user.controller;

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.user.EduStudent;
import com.yida.data.common.core.enums.FileDealStatusEnum;
import com.yida.data.common.core.exception.FebsException;
import com.yida.data.common.core.file.common.export.ExportExcelData;
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.user.dto.ExchangeDormDTO;
import com.yida.data.user.dto.ImportStudentDormDTO;
import com.yida.data.user.dto.PageStudentDTO;
import com.yida.data.user.dto.PageStudentDormDTO;
import com.yida.data.user.service.EduStudentDormService;
import com.yida.data.user.service.EduStudentService;
import com.yida.data.user.vo.StudentDormInfoVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
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.*;
import org.springframework.web.multipart.MultipartFile;

@Api(tags = "学生住宿管理")
@RestController
@Slf4j
@RequestMapping("/studentDorm")
@RequiredArgsConstructor
public class EduStudentDormController {

    private final EduStudentService eduStudentService;
    private final EduStudentDormService eduStudentDormService;

    private final RedisService redisService;

    @ApiOperation("分页查询住宿学生情况")
    @GetMapping("/listStudentDormPage")
    public ResultBean<IPage<StudentDormInfoVO>> listStudentDormPage(PageStudentDormDTO dto) {
        if (dto.getSchoolId() == null) {
            CurrentUser currentUser = FebsUtil.getCurrentUser();
            if (currentUser.getDeptType() == 0) {
                dto.setSchoolId(currentUser.getDeptId());
            }
        }
        return ResultBean.buildSuccess(eduStudentDormService.listStudentDormPage(dto));
    }

    @ApiOperation("新增住宿生")
    @GetMapping("/saveStudentDorm")
    public ResultBean saveStudent(@ApiParam("学生id") Long studentId,
        @ApiParam("寝室id") Long dormRoomId,
        @ApiParam("宿舍id") Long dormId) {
        EduStudent student = eduStudentService.getById(studentId);
        Asserts.isNotNull(student, "学生不存在");
        Asserts.isTrue(student.getDormRoomId() == null, "学生已存在宿舍");
        eduStudentDormService.saveStudentDorm(studentId, dormRoomId, dormId);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("退宿")
    @PostMapping("/cancelBatch")
    public ResultBean cancelBatch(@RequestBody List<Long> studentIds) {
        eduStudentDormService.cancelBatch(studentIds);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("换寝")
    @PostMapping("/exchangeDorm")
    public ResultBean exchangeDorm(@RequestBody ExchangeDormDTO dto) {
        eduStudentDormService.exchangeDorm(dto);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("导入住宿学生")
    @PostMapping("/importStudentDorm")
    public void importStudentDorm(MultipartFile file) {
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        eduStudentDormService.importDormRoom(file, currentUser.getDeptId(), currentUser.getUserId().toString());
    }

    @ApiOperation("导入进度")
    @GetMapping("/importStudentDormPercent")
    public ResultBean importStudenrDormPercent() {
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        return ResultBean.buildSuccess(redisService.hget(CachePrefixConstant.IMPORT_STUDENT_DORM,
            currentUser.getUserId().toString()));
    }

    @ApiOperation("下载错误数据")
    @PostMapping("/downloadErrorData")
    public void downloadError(HttpServletResponse response) {
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        ImportPercentVO percent = (ImportPercentVO) redisService.hget(CachePrefixConstant.IMPORT_STUDENT_DORM,
            currentUser.getUserId().toString());
        ExcelUtil.export("错误数据.xlsx", ImportStudentDormDTO.class, percent.getError(), response);
    }

    @ApiOperation("下载导入模板")
    @PostMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) {
        InputStream inputStream = getClass().getClassLoader()
            .getResourceAsStream("template/studentDormUpload.xlsx");
        try {
            FileUtil.download(inputStream, "住宿学生导入.xlsx", response);
        } catch (Exception e) {
            log.error("下载住宿学生导入模板失败", e);
            throw new FebsException("下载住宿学生导入模板失败");
        }
    }

    @ApiOperation("导出宿舍数据")
    @PostMapping("/exportStudentDorm")
    public ResultBean<ExportExcelData> exportStudentDorm(@RequestBody PageStudentDormDTO dto) {

        String key = IdUtil.simpleUUID();
        ExportExcelData vo = ExportExcelData.builder()
                .key(key)
                .exportStatus(FileDealStatusEnum.DEALING.getStatus())
                // 初始化数据
                .total(1)
                .finish(0)
                .build();

        redisService.hset(CachePrefixConstant.EXPORT_STUDENT_DORM_DATA, key, vo);
        // 异步导出宿舍数据
        eduStudentDormService.exportStudentDorm(dto, key);
        return ResultBean.buildSuccess(vo);
    }

    @ApiOperation("查询导出学生宿舍详情")
    @GetMapping("/getStudentDormExportInfo")
    public ResultBean<Object> getStudentDormExportInfo(@RequestParam String key) {
        return ResultBean.buildSuccess(eduStudentDormService.getStudentDormExportInfo(key));
    }
}
