package com.yida.data.user.controller.web;

import cc.mrbird.febs.common.redis.service.RedisService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.FebsConstant;
import com.yida.data.common.core.entity.school.EduSchoolStudentInformation;
import com.yida.data.common.core.enums.ReportStatusEnum;
import com.yida.data.common.core.utils.FebsUtil;
import com.yida.data.common.core.utils.FileUtil;
import com.yida.data.common.core.utils.RedisUtil;
import com.yida.data.common.service.CommonService;
import com.yida.data.user.dto.DownloadStudentTemplateDTO;
import com.yida.data.user.service.EduSchoolParentInformationService;
import com.yida.data.user.service.EduSchoolStudentInformationService;
import com.yida.data.user.vo.EduSchoolStudentInNumformationVo;
import com.yida.data.user.vo.EduSchoolStudentInformationVo;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ehcache.impl.internal.concurrent.ConcurrentHashMap;
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.Arrays;

/**
 * 学校智慧迎新web后台接口
 *
 * @author wjm
 * @date 2021/8/21
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/web/welcome/student")
@Api(tags = "学校智慧迎新后台接口")
public class WebEduSchoolWelcomeStudentController {

    private final RedisService redisService;

    private final CommonService commonService;

    private final EduSchoolStudentInformationService eduSchoolStudentInformationService;

    private final EduSchoolParentInformationService eduSchoolParentInformationService;

    /***
     * @Author jianMingWang
     * @Description 分页列表查询学生信息
     * @Date 15:26 2021/8/21
     * @Param [schoolId]
     * @return com.yida.data.common.core.common.ResultBean<com.yida.data.common.core.entity.school.EduSchoolTips>
     **/
    @ApiOperation("分页列表查询学生信息")
    @GetMapping("/listStudentInfo")
    public ResultBean<IPage<EduSchoolStudentInformationVo>> listStudentInfo(
            @ApiParam(value = "学校id", required = true) @RequestParam Integer schoolId,
            @ApiParam(value = "学区id", required = false) @RequestParam(value = "campusId", required = false) Integer campusId,
            @ApiParam(value = "学段ID", required = false) @RequestParam(value = "sectionId", required = false) Integer sectionId,
            @ApiParam(value = "年级id", required = false) @RequestParam(value = "gradeId", required = false) Integer gradeId,
            @ApiParam(value = "班级id", required = false) @RequestParam(value = "classId", required = false) Integer classId,
            @ApiParam(value = "学生姓名", required = false) @RequestParam(value = "studentName", required = false) String studentName,
            @ApiParam(value = "学生身份证号", required = false) @RequestParam(value = "studentIdCard", required = false) String studentIdCard,
            @ApiParam("当前页码,默认1") @RequestParam(defaultValue = "1") Integer pageNum,
            @ApiParam("分页大小，默认10") @RequestParam(defaultValue = "10") Integer pageSize,
            @ApiParam(value = "报到状态. -1:查询全部报到状态, 0:未报到, 1:已报到") @RequestParam(required = false) Integer reportStatus) {
        try {
            return ResultBean.buildSuccess(eduSchoolStudentInformationService.listStudentInfo(new Page(pageNum, pageSize),
                    schoolId, campusId, sectionId, gradeId, classId, studentName, studentIdCard, reportStatus)
            );
        } catch (Exception e) {
            log.error("分页列表查询学生信息: {}", e.getMessage(), e);
            return ResultBean.buildError(ResultMsgType.QUERY_FAIL.getValue());
        }
    }

    /***
     * @Author jianMingWang
     * @Description //查询学生报到数量信息
     * @Date 17:28 2021/8/21
     * @Param [schoolId]
     * @return com.yida.data.common.core.common.ResultBean<com.yida.data.school.vo.EduSchoolStudentInNumformationVo>
     **/
    @ApiOperation("查询学生报到数量信息")
    @GetMapping("/findStudentNum")
    public ResultBean<EduSchoolStudentInNumformationVo> findStudentNum(@ApiParam(value = "学校id", required = true) @RequestParam Long schoolId) {
        try {
            int total = (int) eduSchoolStudentInformationService.count(Wrappers.<EduSchoolStudentInformation>query().lambda().eq(EduSchoolStudentInformation::getSchoolId, schoolId));
            int checkNUm = (int) eduSchoolParentInformationService.getCheckNum(schoolId);
            return ResultBean.buildSuccess(new EduSchoolStudentInNumformationVo(total, checkNUm));
        } catch (Exception e) {
            log.error("查询学生报到数量信息: {}", e.getMessage(), e);
            return ResultBean.buildError(ResultMsgType.QUERY_FAIL.getValue());
        }
    }

    /**
     * 导入迎新学生数据
     *
     * @param file     导入的excel文件
     * @param schoolId 学校id
     * @return com.yida.data.common.core.common.ResultBean<org.ehcache.impl.internal.concurrent.ConcurrentHashMap < java.lang.Integer, java.lang.Object>>
     * @author ZYJ
     * @date 2021/8/23 15:58
     */
    @ApiOperation("导入迎新学生数据")
    @ApiResponses({
            @ApiResponse(code = 200, message = "导入迎新学生数据成功"),
            @ApiResponse(code = 500, message = "导入迎新学生数据失败"),
            @ApiResponse(code = 555, message = "导入迎新学生数据部份成功. data里返回有问题的数据")
    })
    @PostMapping(value = "/importWelcomeStudentDataExcel", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResultBean<ConcurrentHashMap<Integer, Object>> importWelcomeStudentDataExcel(
            @ApiParam(value = "导入的excel文件", required = true) @RequestParam("file") MultipartFile file,
            @ApiParam(value = "学校id", required = true) @RequestParam("schoolId") Long schoolId) {
        // 当前时间时间戳
        long timestamp = System.currentTimeMillis();
        try {
            // TODO 2021/08/24 后续修改为异步导入数据, 操作完后给对应的登录用户发送系统通知
            // 生成智慧迎新部门缓存数据
            eduSchoolStudentInformationService.getDeptInfo(schoolId, String.valueOf(timestamp));
            // 导入迎新学生数据
            return eduSchoolStudentInformationService.importWelcomeStudentDataExcel(file, schoolId, timestamp);
        } catch (Exception e) {
            log.error("导入迎新学生数据失败: {}", e.getMessage(), e);
            return ResultBean.buildError(ResultMsgType.IMPORT_EXCEL_FAIL.getValue());
        } finally {
            // 清空当前导入的redis学校数据
            redisService.del(RedisUtil.getDeptKey(String.valueOf(timestamp)));
        }
    }

    /**
     * 根据查询条件导出迎新学生数据
     *
     * @param schoolId      学校id
     * @param campusId      学区id
     * @param sectionId     学段id
     * @param gradeId       年级id
     * @param classId       班级id
     * @param studentName   学生姓名
     * @param studentIdCard 学生身份证号码
     * @param reportStatus  报到状态 {@link ReportStatusEnum}
     * @param response      response返回类
     * @author ZYJ
     * @date 2021/8/24 10:50
     */
    @ApiOperation("导出迎新学生数据")
    @PostMapping(value = "/exportWelcomeStudentData")
    public void exportWelcomeStudentData(
            @ApiParam(value = "学校id", required = true) @RequestParam Integer schoolId,
            @ApiParam(value = "学区id") @RequestParam(required = false) Integer campusId,
            @ApiParam(value = "学段id") @RequestParam(required = false) Integer sectionId,
            @ApiParam(value = "年级id") @RequestParam(required = false) Integer gradeId,
            @ApiParam(value = "班级id") @RequestParam(required = false) Integer classId,
            @ApiParam(value = "学生姓名") @RequestParam(required = false) String studentName,
            @ApiParam(value = "学生身份证号") @RequestParam(required = false) String studentIdCard,
            @ApiParam(value = "报到状态. -1:查询全部报到状态, 0:未报到, 1:已报到") @RequestParam(required = false) Integer reportStatus,
            HttpServletResponse response) {
        eduSchoolStudentInformationService.exportWelcomeStudentData(schoolId, campusId, sectionId,
                gradeId, classId, studentName, studentIdCard, reportStatus, response);
    }

    /**
     * 下载智慧迎新相关导入模板
     *
     * @param dto      下载学生导入模板请求类
     * @param response response返回类
     * @throws Exception 导出模板异常信息
     * @author ZYJ
     * @date 2021/8/24 16:15
     */
    @ApiOperation("下载智慧迎新相关导入模板")
    @PostMapping("/downloadTemplate")
    public void downloadTemplate(@RequestBody DownloadStudentTemplateDTO dto, HttpServletResponse response) throws Exception {
        eduSchoolStudentInformationService.downloadTemplate(dto.getType(), response);
    }

    /**
     * 导入学生基础信息
     *
     * @param file     导入的excel文件
     * @param schoolId 学校id
     * @return com.yida.data.common.core.common.ResultBean<java.lang.String>
     * @author ZYJ
     * @date 2021/8/24 17:12
     */
    @ApiOperation("导入学生基础信息")
    @PostMapping(value = "/importWelcomeInviteData", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResultBean<String> importWelcomeInviteData(
            @ApiParam(value = "导入的excel文件", required = true) @RequestParam("file") MultipartFile file,
            @ApiParam(value = "学校id", required = true) @RequestParam("schoolId") Long schoolId) {
        // 验证文件类型
        if (!FileUtil.checkMultipartFile(file, FebsConstant.EXCEL_FILE_TYPE)) {
            return ResultBean.buildError(ResultMsgType.FILE_TYPE_ERROR.getValue());
        }
        // 当前登录用户信息
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        String fileUrl = FileUtil.uploadMultipartFile(file);
        // 导入一键邀请数据
        eduSchoolStudentInformationService.importWelcomeInviteData(fileUrl, schoolId, currentUser);
        return ResultBean.buildSuccess(ResultMsgType.IMPORT_EXCEL_SUCCESS.getValue(), null);
    }

    /**
     * 批量删除迎新数据
     *
     * @param ids 数据id集合
     * @return com.yida.data.common.core.common.ResultBean<java.lang.String>
     * @author ZYJ
     * @date 2021/8/27 18:08
     */
    @ApiOperation("批量删除迎新数据")
    @PostMapping("/deleteWelcomeStudentBatch")
    public ResultBean<String> deleteWelcomeStudentBatch(@ApiParam(value = "数据id集合", required = true) @RequestBody Long[] ids) throws Exception {
        try {
            eduSchoolStudentInformationService.removeByIds(Arrays.asList(ids));
            return ResultBean.buildSuccess();
        } catch (Exception e) {
            log.error("批量删除迎新数据失败: {}", e.getMessage(), e);
            return ResultBean.buildError(ResultMsgType.DELETE_FAIL.getValue());
        }
    }
}
