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

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yida.data.common.core.common.ResultBean;
import com.yida.data.common.core.common.ResultMsgType;
import com.yida.data.common.core.entity.CurrentUser;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.constant.FebsConstant;
import com.yida.data.common.core.enums.FileDealStatusEnum;
import com.yida.data.common.core.file.common.DownloadFileChunk;
import com.yida.data.common.core.file.common.export.ExportLargeData;
import com.yida.data.common.core.utils.Asserts;
import com.yida.data.common.core.utils.FebsUtil;
import com.yida.data.common.core.utils.FileUtil;
import com.yida.data.school.dto.smart.GuideRosterSelectPageDTO;
import com.yida.data.school.dto.smart.GuideSaveDTO;
import com.yida.data.school.dto.smart.GuideSelectPageDTO;
import com.yida.data.school.dto.smart.UpdateQrCodeInfoDTO;
import com.yida.data.school.smart.service.EduSmartWelcomeGuideRosterService;
import com.yida.data.school.smart.service.EduSmartWelcomeGuideService;
import com.yida.data.school.smart.service.EduSmartWelcomeGuideStepService;
import com.yida.data.school.vo.smart.*;
import com.yida.data.user.vo.ImportFaceVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 智慧迎新指南后台Controller
 *
 * @author ZYJ
 * @date 2023-05-15 15:33:18
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "智慧迎新指南后台api")
@RequestMapping("eduSmartWelcomeGuide")
public class EduSmartWelcomeGuideController {

    private final EduSmartWelcomeGuideService eduSmartWelcomeGuideService;
    private final EduSmartWelcomeGuideStepService eduSmartWelcomeGuideStepService;
    private final EduSmartWelcomeGuideRosterService eduSmartWelcomeGuideRosterService;

    private final RedisService redisService;

    @PostMapping(value = "listGuidePage")
    @ApiOperation(value = "查询迎新指南列表数据")
    public ResultBean<IPage<GuideSelectPageVO>> listGuidePage(GuideSelectPageDTO dto) {
        IPage<GuideSelectPageVO> page = eduSmartWelcomeGuideService.listGuidePage(dto);
        return ResultBean.buildSuccess(page);
    }

    @GetMapping(value = "getGuideInfo")
    @ApiOperation(value = "获取迎新指南详细信息")
    public ResultBean<GuideInfoVO> getGuideInfo(@ApiParam(value = "指南id", required = true) @RequestParam Long guideId) {
        return ResultBean.buildSuccess(eduSmartWelcomeGuideService.getGuideInfo(guideId));
    }

    @PostMapping(value = "saveGuide", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "保存迎新指南数据", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResultBean<String> saveGuide(@RequestBody GuideSaveDTO dto) {
        eduSmartWelcomeGuideService.saveGuide(dto);
        return ResultBean.buildSuccess();
    }

    @GetMapping("updateGuideEnableStatus")
    @ApiOperation("修改指南状态")
    public ResultBean<String> updateGuideEnableStatus(
            @ApiParam(value = "指南id", required = true) @RequestParam Long guideId,
            @ApiParam(value = "状态. 0:未启用, 1:已启用", required = true) @RequestParam Integer enableStatus) {
        eduSmartWelcomeGuideService.updateGuideEnableStatus(guideId, enableStatus);
        return ResultBean.buildSuccess();
    }

    @PostMapping("updateQrCodeInfo")
    @ApiOperation("保存指南二维码配置")
    public ResultBean<String> updateQrCodeInfo(@RequestBody UpdateQrCodeInfoDTO dto) {
        eduSmartWelcomeGuideService.updateQrCodeInfo(dto);
        return ResultBean.buildSuccess();
    }

    @GetMapping(value = "deleteGuide")
    @ApiOperation(value = "删除指南")
    public ResultBean<String> deleteGuide(@ApiParam(value = "指南id", required = true) @RequestParam Long guideId) {
        eduSmartWelcomeGuideService.deleteGuide(guideId);
        return ResultBean.buildSuccess();
    }

    @GetMapping(value = "listGuideRosterTableCol")
    @ApiOperation(value = "查询花名册动态表头")
    public ResultBean<List<GuideStepColVO>> listGuideRosterTableCol(
            @ApiParam(value = "指南id", required = true) @RequestParam Long guideId) {
        return ResultBean.buildSuccess(eduSmartWelcomeGuideStepService.listGuideRosterTableCol(guideId));
    }

    @PostMapping("/listGuideRoster")
    @ApiOperation("查询指南花名册列表")
    public ResultBean<IPage<Map<String, String>>> listGuideRoster(GuideRosterSelectPageDTO dto) {
        IPage<Map<String, String>> page = eduSmartWelcomeGuideRosterService.listGuideRoster(dto);
        return ResultBean.buildSuccess(page);
    }

    @PostMapping("/statisticsGuideRoster")
    @ApiOperation("查询指南花名册统计信息")
    public ResultBean<List<StatisticsGuideRosterVO>> statisticsGuideRoster(
            @ApiParam(value = "指南id", required = true) @RequestParam Long guideId) {
        return ResultBean.buildSuccess(eduSmartWelcomeGuideRosterService.statisticsGuideRoster(guideId));
    }

    @GetMapping(value = "getGuideRosterInfo")
    @ApiOperation(value = "获取花名册详细信息")
    public ResultBean<GuideRosterInfoVO> getGuideRosterInfo(
            @ApiParam(value = "花名册id", required = true) @RequestParam Long rosterId) {
        return ResultBean.buildSuccess(eduSmartWelcomeGuideRosterService.getGuideRosterInfo(rosterId));
    }

    @GetMapping(value = "createRosterQrCode")
    @ApiOperation(value = "生成花名册二维码")
    public ResultBean<String> createRosterQrCode(
            @ApiParam(value = "花名册id", required = true) @RequestParam Long rosterId,
            @ApiParam(value = "指南id", required = true) @RequestParam Long guideId) {
        eduSmartWelcomeGuideRosterService.createRosterQrCode(rosterId, guideId);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("导入指南花名册数据")
    @PostMapping(value = "/importGuideRoster", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResultBean<ImportRosterDataVO> importGuideRoster(
            @ApiParam(value = "导入的excel文件", required = true) @RequestParam("file") MultipartFile file,
            @ApiParam(value = "指南id", required = true) @RequestParam("guideId") Long guideId) {
        // 验证文件类型
        if (!FileUtil.checkMultipartFile(file, FebsConstant.EXCEL_FILE_TYPE)) {
            return ResultBean.buildError(ResultMsgType.FILE_TYPE_ERROR.getValue());
        }
        String uuid = StrUtil.uuid();
        // 当前登录用户信息
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        String fileUrl = FileUtil.uploadMultipartFile(file);
        // 导入花名册数据
        eduSmartWelcomeGuideRosterService.importGuideRoster(fileUrl, guideId, currentUser, uuid);
        return ResultBean
                .buildSuccess(ImportRosterDataVO.builder().percent(0).finish(0).key(uuid).build());
    }


    @ApiOperation("查询导入指南花名册数据进度")
    @GetMapping("/getImportGuideRosterPercent")
    public ResultBean<Object> getImportGuideRosterPercent(String key) {
        return ResultBean.buildSuccess(
                redisService.get(CachePrefixConstant.IMPORT_GUIDE_ROSTER_KEY + key));
    }

    @ApiOperation("下载指南花名册导入模板")
    @PostMapping("/downloadGuideTemplate")
    public void downloadTemplate(HttpServletResponse response) {
        eduSmartWelcomeGuideRosterService.downloadGuideTemplate(response);
    }

    @PostMapping("/exportRosterInfoData")
    @ApiOperation("导出花名册数据")
    public ResultBean<ExportRosterDataVO> exportRosterInfoData(@RequestBody GuideRosterSelectPageDTO dto) {
        String uuid = IdUtil.simpleUUID();
        ExportRosterDataVO vo = ExportRosterDataVO.builder()
                .key(uuid)
                .exportStatus(FileDealStatusEnum.DEALING.getStatus())
                .totalNum(100)
                .currentNum(0).build();
        redisService.hset(CachePrefixConstant.GUIDE_ROSTER_DATA_DOWNLOAD, uuid, vo);
        // 异步导出花名册数据
        eduSmartWelcomeGuideRosterService.exportRosterInfoData(dto, uuid);
        return ResultBean.buildSuccess(vo);
    }

    @ApiOperation("获取导出花名册数据下载进度")
    @GetMapping("/getExportProgress")
    public ResultBean<ExportRosterDataVO> getExportProgress(String key) {
        return ResultBean.buildSuccess(
                (ExportRosterDataVO) redisService.hget(CachePrefixConstant.GUIDE_ROSTER_DATA_DOWNLOAD, key));
    }

    @ApiOperation("批量上传人脸寸照")
    @PostMapping("/uploadAvatarBatch")
    public ResultBean uploadFaceBatch(@RequestParam("file") MultipartFile file,
                                      @ApiParam("指南ID") @RequestParam Long guideId) {
        Long userId = FebsUtil.getCurrentUser().getUserId();
        Object o = redisService.get(CachePrefixConstant.IMPORT_GUIDE_AVATAR_KEY + userId.toString());
        Asserts.isTrue(o == null || ((ImportFaceVO) o).getFinish() == 1, "有文件正在上传中");
        eduSmartWelcomeGuideService.uploadStudentAvatarBatch(FileUtil.uploadMultipartFile(file), guideId, userId);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("查询批量上传人脸寸照进度")
    @GetMapping("/getUploadAvatarBatchPercent")
    public ResultBean<Object> getUploadAvatarBatchPercent() {
        return ResultBean.buildSuccess(
                redisService.get(CachePrefixConstant.IMPORT_GUIDE_AVATAR_KEY + FebsUtil.getCurrentUser().getUserId().toString()));
    }

    @PostMapping("/exportRosterPic")
    @ApiOperation("导出花名册身份证和通知书")
    public ResultBean<ExportLargeData> exportRosterPic(
            @ApiParam(value = "指南id", required = true) @RequestParam Long guideId) {
        String key = IdUtil.simpleUUID();
        ExportLargeData vo = ExportLargeData.builder()
                .key(key)
                .exportStatus(FileDealStatusEnum.DEALING.getStatus())
                // 初始化数据
                .total(1)
                .finish(0)
                .build();

        redisService.hset(CachePrefixConstant.GUIDE_ROSTER_PIC_DATA_DOWNLOAD, key, vo);
        // 异步导出花名册身份证和通知书
        eduSmartWelcomeGuideRosterService.exportRosterPic(guideId, key);
        return ResultBean.buildSuccess(vo);
    }

    @ApiOperation("查询导出花名册身份证和通知书详情")
    @GetMapping("/getExportRosterPicInfo")
    public ResultBean<Object> getExportRosterPicInfo(@RequestParam String key) {
        return ResultBean.buildSuccess(eduSmartWelcomeGuideRosterService.getExportRosterPicInfo(key));
    }

    @ApiOperation("分片下载花名册身份证和通知书图片")
    @PostMapping("/downloadRosterPicChunk")
    public void downloadRosterPicChunk(DownloadFileChunk dto, HttpServletResponse response) {
        eduSmartWelcomeGuideRosterService.downloadRosterPicChunk(dto, response);
    }
}
