package com.srs.web.controller.comprehensive;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.srs.common.annotation.Anonymous;
import com.srs.common.core.domain.entity.SysUser;
import com.srs.common.utils.StringUtils;
import com.srs.comprehensive.domain.Dto.StuDataSelcetDto;
import com.srs.comprehensive.domain.Dto.StuStatusImport;
import com.srs.comprehensive.domain.SrsStudent;
import com.srs.comprehensive.domain.CphStudentDetailExport;

import com.srs.comprehensive.domain.Vo.*;
import com.srs.comprehensive.service.ICascaderDataStudentService;
import com.srs.comprehensive.service.ISrsStudentService;
import com.srs.comprehensive.service.ICphStudentDetailExportService;
import com.srs.system.domain.vo.StuStatus;
import com.srs.system.service.ISysPostService;
import com.srs.web.controller.common.RoleBool;

import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.srs.common.annotation.Log;
import com.srs.common.core.controller.BaseController;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.enums.BusinessType;

import com.srs.common.utils.poi.ExcelUtil;
import com.srs.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 学生信息Controller
 *
 * @author srs
 * @date 2023-06-27
 */
@RestController
@RequestMapping("/system/student")
public class SrsStudentController extends BaseController {
    @Autowired
    private ISrsStudentService srsStudentService;
    
    @Autowired
    private ICascaderDataStudentService cascaderDataStudentService;
    
    @Autowired
    private ICphStudentDetailExportService cphStudentDetailExportService;

    @Autowired
    ISysPostService _postService;

    @PostMapping("/doDept")
    @ApiOperation("学生部门挂靠")
    public AjaxResult doDept(@RequestBody CphSearch param){
        return srsStudentService.doDept(param);
    }


    @GetMapping("/countGradeStuNew")
    @ApiOperation("统计年级学生")
    public AjaxResult countGradeStuNew(){
        List<Map<String, Object>> list = srsStudentService.countGradeStuNew();
        return AjaxResult.success(list);
    }

    @GetMapping("/countDeptStuNew")
    @ApiOperation("统计学院学生")
    public AjaxResult countDeptStuNew(){
        List<Map<String, Object>> list = srsStudentService.countDeptStuNew();
        return AjaxResult.success(list);
    }


    @GetMapping("/countMajorStuByDept")
    @ApiOperation("根据学院统计专业人数")
    public AjaxResult countMajorStuByDept(CphSearch param){
        List<Map<String, Object>> list = srsStudentService.countMajorStuByDept(param);
        return AjaxResult.success(list);
    }


    @GetMapping("/countDeptGradeStuNew")
    @ApiOperation("统计学院人数")
    public AjaxResult countDeptGradeStuNew(){
        List<Map<String, Object>> list = srsStudentService.countDeptGradeStuNew();
        return AjaxResult.success(list);
    }


    @GetMapping("/countParkStu")
    @ApiOperation("统计园区入住人数")
    public AjaxResult countParkStu() {
        boolean hasRole = RoleBool.isJwc(getUserId(), _postService);
        if (hasRole) {
            List<StuCount> list = srsStudentService.countParkStu();
            return AjaxResult.success(list);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }

    @GetMapping("/countLakeGradeStu")
    @ApiOperation("统年级静湖之星人数")
    public AjaxResult countLakeGradeStu() {
        boolean hasRole = RoleBool.isJwc(getUserId(), _postService);
        if (hasRole) {
            List<StuCount> list = srsStudentService.countLakeGradeStu();
            return AjaxResult.success(list);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }

    @GetMapping("/countGoodGradeStu")
    @ApiOperation("统年级评优评先人数")
    public AjaxResult countGoodGradeStu() {
        boolean hasRole = RoleBool.isJwc(getUserId(), _postService);
        if (hasRole) {
            List<StuCount> list = srsStudentService.countGoodGradeStu();
            return AjaxResult.success(list);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }


    @GetMapping("/countGoodBiyeGradeStu")
    @ApiOperation("统年级优秀毕业生人数")
    public AjaxResult countGoodBiyeGradeStu() {
        boolean hasRole = RoleBool.isJwc(getUserId(), _postService);
        if (hasRole) {
            List<StuCount> list = srsStudentService.countGoodBiyeGradeStu();
            return AjaxResult.success(list);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }

    @GetMapping("/countDeptGradeStu")
    @ApiOperation("统计学院年级在校生人数")
    public AjaxResult countDeptGradeStu() {
        boolean hasRole = RoleBool.isJwc(getUserId(), _postService);
        if (hasRole) {
            List<StuCount> list = srsStudentService.countDeptGradeStu();
            return AjaxResult.success(list);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }

    @GetMapping("/countDeptStu")
    @ApiOperation("统计学院在校生人数")
    public AjaxResult countDeptStu() {
        boolean hasRole = RoleBool.isJwc(getUserId(), _postService);
        if (hasRole) {
            List<StuCount> list = srsStudentService.countDeptStu();
            return AjaxResult.success(list);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }

    @GetMapping("/getDeptLeveaDataCount")
    @ApiOperation("/统计各学院请假人数")
    public AjaxResult getDeptLeveaDataCount() {
        boolean hasRole = RoleBool.isJwc(getUserId(), _postService);
        if (hasRole) {
            List<DeptLeaveDataVo> list = srsStudentService.getDeptLeveaDataCount();
            return AjaxResult.success(list);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }

    @GetMapping("/getStuQuitSchoolCount")
    @ApiOperation("统计各学院休学人数-11-26写")
    public AjaxResult getStuQuitSchoolCount() {
        List<DeptStuQuitPunisDataVo> list = srsStudentService.getStuQuitSchoolCount();
        return AjaxResult.success(list);
    }

    @GetMapping("/getStuDropOutSchoolCount")
    @ApiOperation("统计各学院退学人数2-21写")
    public AjaxResult getStuDropOutSchoolCount() {
        List<DeptStuQuitPunisDataVo> list = srsStudentService.getStuDropOutSchoolCount();
        return AjaxResult.success(list);
    }


    @ApiOperation("获取各学院处分人数_11-26写")
    @GetMapping("/getStuPunishCount")
    public AjaxResult getStuPunishCount() {
        List<DeptStuQuitPunisDataVo> stuPunishCount = srsStudentService.getStuPunishCount();
        return AjaxResult.success(stuPunishCount);
    }

    @ApiOperation("获取当年各学院困难认定的人数数量_11-28写")
    @GetMapping("/getKnrdCount")
    public AjaxResult getKnrdCount() {
        List<DeptStuQuitPunisDataVo> list = srsStudentService.getKnrdCount();
        return AjaxResult.success(list);
    }

    @ApiOperation("获取各学院人数，按校区划分，11-28写")
    @GetMapping("/getDeptCountByCampus/{campusName}")
    public AjaxResult getDeptCountByCampus(@PathVariable String campusName) {
        List<DeptStuQuitPunisDataVo> list = srsStudentService.getDeptCountByCampus(campusName);
        return AjaxResult.success(list);
    }

    @ApiOperation("获取当年各学院助学金的人数数量_11-28写")
    @GetMapping("/getZxjCount")
    public AjaxResult getZxjCount() {
        List<DeptStuQuitPunisDataVo> list = srsStudentService.getZxjCount();
        return AjaxResult.success(list);
    }

    @ApiOperation("获取在校生，各年级学生数量_11-28写")
    @GetMapping("/getGradeCount")
    public AjaxResult getGradeCount() {
        List<GradeStuDataVo> list = srsStudentService.getGradeCount();
        return AjaxResult.success(list);
    }


    @PostMapping("/changeOwnInfo")
    public AjaxResult changeOwnInfo(@RequestBody SrsStudent param) {
        param.setStuNo(getUsername());
        return srsStudentService.changeStuInfo(param);
    }


    @GetMapping("/getOwnInfo")
    public AjaxResult getOwnInfo() {
        String stuNo = getUsername();
        SrsStudent res = srsStudentService.getStuInfo(stuNo);
        return AjaxResult.success(res);
    }

    @GetMapping("/getOwnInfoByStuNo")
    public AjaxResult getOwnInfoByStuNo(@RequestParam(value = "stuNo", required = false) String stuNo) {
        if (StringUtils.isEmpty(stuNo)) {
            return AjaxResult.error(400, "学生编号不能为空");
        }
        SrsStudent res = srsStudentService.getStuInfo(stuNo);
        return AjaxResult.success(res);
    }

    @GetMapping("/getOwnClass")
    public AjaxResult getOwnClass() {
        String stuNo = getUsername();
        StuClass res = srsStudentService.getOwnClass(stuNo);
        return success(res);
    }
    @GetMapping("/statusList")
    public AjaxResult statusList() {
        List<StuStatus> status=srsStudentService.statusList();
        return success(status);
    }

    @GetMapping("/listEnableStu")
    public AjaxResult listEnableStu() {
        List<SrsStudent> list = srsStudentService.listEnableStu();
        return success(list);
    }


    /**
     * 查询学生信息列表 及相关信息
     */
    @GetMapping("/list")
    public TableDataInfo list(SrsStudent srsStudent) {
        startPage();
        List<SrsStudent> list = srsStudentService.selectSrsStudentListJoin(srsStudent);
        return getDataTable(list);
    }


    @GetMapping("/listAll")
    public AjaxResult listAll(SrsStudent srsStudent) {
        List<SrsStudent> list = srsStudentService.selectSrsStudentListJoin(srsStudent);
        AjaxResult<Object> result = new AjaxResult<>();
        result.put("code", 200);
        result.put("msg", "查询成功");
        result.put("data", list);
        return result;
    }

    @ApiOperation("列出辅导员自己的学生")
    @GetMapping("/listOwnStu")
    public TableDataInfo listOwnStu(SrsStudent srsStudent) {
        String tNo = getUsername();
        srsStudent.tNo = tNo;
        startPage();
        List<SrsStudent> list = srsStudentService.selectSrsStudentListJoin(srsStudent);
        return getDataTable(list);
    }

    /**
     * 通过班级id查询学生名字列表
     */
    @GetMapping("/list/name")
    public AjaxResult listName(Long classId) {
        return AjaxResult.success(srsStudentService.selectSrsStudentNameList(classId));
    }

    /**
     * 查询学生名字列表 以及所有上级
     */
    @GetMapping("/name")
    public AjaxResult listNameAll() {
        return AjaxResult.success(cascaderDataStudentService.getCascadeData(4));
    }


    /**
     * 导出学生信息列表
     */
//    @PreAuthorize("@ss.hasPermi('system:student:export')")
    @Log(title = "学生信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SrsStudent srsStudent) {
        List<SrsStudent> list = srsStudentService.selectSrsStudentListJoin(srsStudent);
        ExcelUtil<SrsStudent> util = new ExcelUtil<SrsStudent>(SrsStudent.class);
        util.exportExcel(response, list, "学生信息数据");
    }

    /**
     * 导出全部学生信息（包含查新详情）
     */
    //@PreAuthorize("@ss.hasPermi('system:student:exportAll')")
    @Log(title = "学生信息", businessType = BusinessType.EXPORT)
    @PostMapping("/exportAll")
    public void exportAll(HttpServletResponse response, SrsStudent srsStudent) {
        List<CphStudentDetailExport> list = cphStudentDetailExportService.getStudentDetailExportList(srsStudent);
        ExcelUtil<CphStudentDetailExport> util = new ExcelUtil<CphStudentDetailExport>(CphStudentDetailExport.class);
        util.exportExcel(response, list, "学生查新详情数据");
    }

    /**
     * 在我的学生页面导出学生信息
     */
    //@PreAuthorize("@ss.hasPermi('system:student:exportAllOwnStu')")
    @Log(title = "学生信息", businessType = BusinessType.EXPORT)
    @PostMapping("/exportAllOwnStu")
    public void exportAllOwnStu(HttpServletResponse response, SrsStudent srsStudent) {
        srsStudent.tNo = getUsername();
        List<CphStudentDetailExport> list = cphStudentDetailExportService.getStudentDetailExportList(srsStudent);
        ExcelUtil<CphStudentDetailExport> util = new ExcelUtil<CphStudentDetailExport>(CphStudentDetailExport.class);
        util.exportExcel(response, list, "学生查新详情数据");
    }

    /**
     * 下载导入模板
     *
     * @param response
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<StuStatusImport> util = new ExcelUtil<StuStatusImport>(StuStatusImport.class);
        util.importTemplateExcel(response, "学生信息数据");
    }
    @PostMapping("/importTemplate2")
    public void importTemplate2(HttpServletResponse response) throws Exception {
        ClassPathResource classPathResource = new ClassPathResource("学生状态信息数据.xlsx");
        InputStream inputStream = classPathResource.getInputStream();
        Workbook workbook = new XSSFWorkbook(inputStream);
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode("学生状态信息数据.xlsx", "utf-8"));
        response.setHeader("Access-Control-Expose-Headers", "content-Disposition");
        OutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 导入
     *
     * @param file
     * @return
     * @throws Exception
     */
    @Log(title = "学生信息", businessType = BusinessType.IMPORT)
//    @PreAuthorize("@ss.hasPermi('system:student:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<StuStatusImport> util = new ExcelUtil<StuStatusImport>(StuStatusImport.class);
        List<StuStatusImport> studentsList = util.importExcel(file.getInputStream());
        List<SrsStudent> students = new ArrayList<>();
        for(StuStatusImport x:studentsList){
            SrsStudent srsStudent = new SrsStudent();
            srsStudent.setStuNo(x.stuNo);
            switch(x.status){
                case "在校":
                    srsStudent.setStatus("01");
                    break;
                case "离校变更":
                    srsStudent.setStatus("02");
                    break;
                case "毕业":
                    srsStudent.setStatus("03");
                    break;
                case "外出实训":
                    srsStudent.setStatus("04");
                    break;
                case "外出实习":
                    srsStudent.setStatus("05");
                    break;
                case "在校实习":
                    srsStudent.setStatus("06");
                    break;
                default:
                    srsStudent.setStatus("01");
                    break;
            }
            students.add(srsStudent);
        }

        String message = srsStudentService.importStudent(students, getUsername());
        return AjaxResult.success(message);
    }


    /**
     * 获取学生信息详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:student:query')")
    @GetMapping(value = "/{stuId}")
    public AjaxResult getInfo(@PathVariable("stuId") Long stuId) {
        return success(srsStudentService.selectSrsStudentByStuId(stuId));
    }
    //获取登陆学生信息
    @GetMapping("/getLoginStudent")
    public AjaxResult getLoginStudent() {
        String stuNo = getUsername();
        return success(srsStudentService.getSrsStudentByStuNoNew(stuNo));
    }

    /**
     * 新增学生信息
     */
//    @PreAuthorize("@ss.hasPermi('system:student:add')")
    @Log(title = "学生信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SrsStudent srsStudent) {
        return toAjax(srsStudentService.insertSrsStudent(srsStudent));
    }

    /**
     * 修改学生信息
     */
//    @PreAuthorize("@ss.hasPermi('system:student:edit')")
    @Log(title = "学生信息", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    public AjaxResult edit(@RequestBody SrsStudent srsStudent) {
        return toAjax(srsStudentService.updateSrsStudent(srsStudent));
    }

    /**
     * 删除学生信息
     */
//    @PreAuthorize("@ss.hasPermi('system:student:remove')")
    @Log(title = "学生信息", businessType = BusinessType.DELETE)
    @PostMapping("/delete/{stuIds}")
    public AjaxResult remove(@PathVariable Long[] stuIds) {
        return toAjax(srsStudentService.deleteSrsStudentByStuIds(stuIds));
    }

    /**
     * 从中间表同步数据
     */
    @PostMapping("/dataSync")
    public AjaxResult dataSync() {

        return AjaxResult.success(srsStudentService.studentDataSync());
    }

    //批量初始化密码
    //@PreAuthorize("@ss.hasPermi('system:student:import')")
    @PostMapping("/initializePwd")
    public AjaxResult initializePwd() {
        if (!Objects.equals(getUsername(), "admin")) {
            throw new RuntimeException("没有管理员权限！");
        }
        return toAjax(srsStudentService.initializePwd());
    }

    //单个初始化密码
    @PostMapping("/updateUserPwds")
    public AjaxResult updateUserPwds(@RequestBody Map<String, Object> objectMap) {
        SysUser sysUser = new SysUser();
        sysUser.setUserName(objectMap.get("username").toString());
        int i = srsStudentService.updateUserPwd(sysUser);
        if (i == 0) {
            return error();
        }
        return success("密码初始化为#A账号A#，请尽快进入系统修改密码");
    }
    @GetMapping("/getRtSuspendSchooling")
    @ApiOperation("获取休学人员以及具体信息")
    public TableDataInfo getRtSuspendSchooling(StuDataSelcetDto stuDataSelcetDto){
        startPage();
        return getDataTable(srsStudentService.getRtStuQuitSchool(stuDataSelcetDto));

    }
    @GetMapping("/getRtStuDisciplinaryApplication")
    @ApiOperation("获取处分人员以及具体信息")
    public TableDataInfo getRtStuDisciplinaryApplication(StuDataSelcetDto stuDataSelcetDto){
        startPage();
        return getDataTable(srsStudentService.getRtStuDisciplinaryApplication(stuDataSelcetDto));
    }
    @GetMapping("/getRtStuDropOutSchool")
    @ApiOperation("获取退学人员以及具体信息")
    public TableDataInfo getRtStuDropOutSchool(StuDataSelcetDto stuDataSelcetDto) {
        startPage();
        return getDataTable(srsStudentService.getRtStuDropOutSchool(stuDataSelcetDto));
    }
    @GetMapping("/getSrsKnrdApply")
    @ApiOperation("获取困难人员以及具体信息")
    public TableDataInfo getSrsKnrdApply(StuDataSelcetDto stuDataSelcetDto){
        startPage();
        return getDataTable(srsStudentService.getSrsKnrdApply(stuDataSelcetDto));
    }
    @GetMapping("/getSrsZxjApply")
    @ApiOperation("获取助学金人员以及具体信息")
    public TableDataInfo getSrsZxjApply(StuDataSelcetDto stuDataSelcetDto){
        startPage();
        return getDataTable(srsStudentService.getSrsZxjApply(stuDataSelcetDto));

    }
    @GetMapping("/getSrsMZCount")
    @ApiOperation("获取学生是各民族多少人")
    public AjaxResult getSrsMZCount(){
        List<Map<String, Object>> list = srsStudentService.countStuMZ();
        return AjaxResult.success(list);
    }
    @GetMapping("/getSrsHZCount")
    @ApiOperation("获取户口是农村城镇多少人")
    public AjaxResult getSrsHZCount(){
        List<Map<String, Object>> list = srsStudentService.getSrsHZCount();
        return AjaxResult.success(list);
    }
    @GetMapping("/getSrsZZCount")
    @ApiOperation("获取政治面貌多少人")
    public AjaxResult getSrsZZCount(){
        List<Map<String, Object>> list = srsStudentService.getSrsZZCount();
        return AjaxResult.success(list);
    }
    @GetMapping("/getSrsGenderCount")
    @ApiOperation("获取男女的人数")
    public AjaxResult getSrsGenderCount(){
        List<Map<String, Object>> list = srsStudentService.getSrsGenderCount();
        return AjaxResult.success(list);
    }
    @GetMapping("/getSrsknrdCount")
    @ApiOperation("获取不同困难类型的人数")
    public AjaxResult getSrsknrdCount(){
        List<Map<String, Object>> list = srsStudentService.getSrsknrdCount();
        return AjaxResult.success(list);
    }
    @GetMapping("/getSrsAgeCount")
    @ApiOperation("获取不同年龄段的人数")
    public AjaxResult getSrsAgeCount(){
        List<Map<String, Object>> list = srsStudentService.getSrsAgeCount();
        return AjaxResult.success(list);
    }
    @GetMapping("/getCountbyCity")
    @ApiOperation("获取不同城市男女人数")
    public AjaxResult getCountbyCity(){
        List<Map<String, Object>> list = srsStudentService.getCountbyCity();
        return AjaxResult.success(list);
    }
    @GetMapping("/getSchoolCountbyGrade")
    @ApiOperation("获取学校每个年级的人数")
    public AjaxResult getSchoolCountbyGrade(){
        List<Map<String, Object>> list = srsStudentService.getSchoolCountbyGrade();
        return AjaxResult.success(list);
    }
    @GetMapping("/getSchoolTotalCount")
    @ApiOperation("统计学校总人数、男女人数，以及男女占比")
    public AjaxResult getSchoolTotalCount(){
        List<Map<String, Object>> list = srsStudentService.getSchoolTotalCount();
        return AjaxResult.success(list);
    }
    @GetMapping("/getNotSchoolTotalCount")
    @ApiOperation("统计学校总人数、男女人数，以及男女占比")
    public AjaxResult getNotSchoolTotalCount(){
        List<Map<String, Object>> list = srsStudentService.getNotSchoolTotalCount();
        return AjaxResult.success(list);
    }
    @GetMapping("/getMajorsCount")
    @ApiOperation("统计学校各个专业各个年级的人数")
    public AjaxResult getMajorsCount(){
        List<Map<String, Object>> list = srsStudentService.getMajorsCount();
        return AjaxResult.success(list);
    }
    @GetMapping("/getFiveSchoolTotalCount")
    @ApiOperation("统计近5年学校的总人数")
    public  AjaxResult getFiveSchoolTotalCount(){
        List<Map<String, Object>> list = srsStudentService.getFiveSchoolTotalCount();
        return AjaxResult.success(list);
    }
}
