package com.srs.web.controller.routine;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.srs.common.core.domain.entity.SysDept;
import com.srs.comprehensive.domain.CphTeacher;
import com.srs.comprehensive.domain.SrsClass;
import com.srs.comprehensive.domain.SrsMajors;
import com.srs.comprehensive.domain.SrsStudent;
import com.srs.comprehensive.mapper.CphTeacherMapper;
import com.srs.comprehensive.mapper.SrsClassMapper;
import com.srs.comprehensive.mapper.SrsStudentMapper;
import com.srs.routine.domain.RtClassMeetingClass;
import com.srs.routine.domain.vo.ClassMettingThemeSumitListVo;
import com.srs.routine.mapper.RtClassMettingThemeMapper;
import com.srs.routine.service.IRtClassMettingStuUploadService;
import com.srs.system.domain.SysDeptMap;
import com.srs.system.service.ISysDeptMapService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.*;
import com.srs.routine.domain.RtClassMettingTheme;
import com.srs.routine.service.IRtClassMettingThemeService;
import com.srs.common.core.controller.BaseController;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.utils.poi.ExcelUtil;
import com.srs.common.enums.BusinessType;
import com.srs.common.annotation.Log;
import com.srs.common.core.page.TableDataInfo;
import static com.srs.common.config.SrsConfig.getUploadPath;

/**
 * 班会主题Controller
 *
 * @author deng
 * @date 2024-05-18
 */
@RestController
@RequestMapping("/runtine/ClassMettingTheme")
@Api(value = "班会主题管理", tags = "班会主题管理")
public class RtClassMettingThemeController extends BaseController {
    @Autowired
    private IRtClassMettingThemeService rtClassMettingThemeService;

    @Autowired
    private IRtClassMettingStuUploadService rtClassMettingStuUploadService;

    @Autowired
    private RtClassMettingThemeMapper rtClassMettingThemeMapper;

    @Autowired
    ISysDeptMapService _deptMap;

    @Autowired
    private SrsStudentMapper _stuMapper;

    @Autowired
    private SrsClassMapper _classMapper;

    @Autowired
    private CphTeacherMapper _fdyMapper;

    @GetMapping("/listStuFdyNeedByCmId/{id}")
    @ApiOperation("查询班会主题列表")
    public AjaxResult listStuFdyNeedByCmId(@PathVariable Long id){
        QueryWrapper<SrsStudent> studentQueryWrapper = new QueryWrapper<>();
        studentQueryWrapper.eq("stu_no", getUsername());
        studentQueryWrapper.last("limit 1");
        SrsStudent student=_stuMapper.selectOne(studentQueryWrapper);
        if(student==null){
            return AjaxResult.error("未查询到信息");
        }
        Long classId=student.getClassId();
        if(classId==null){
            return AjaxResult.error("未查询到信息");
        }
        SrsClass srsClass=_classMapper.selectSrsClassByClassId(classId);
        if(srsClass==null){
            return AjaxResult.error("未查询到信息");
        }
        Long teacherId=srsClass.getTeacherId();

        CphTeacher fdy = _fdyMapper.selectById(teacherId);
        if(fdy==null){
            return AjaxResult.error("未查询到信息");
        }
        RtClassMeetingClass dto = new RtClassMeetingClass();
        dto.setCmtId(id);
        dto.tNo = fdy.getEmployeeId();
        return rtClassMettingThemeService.listFdyNeedByCmId(dto);
    }

    @GetMapping("/listFdyNeedByCmId/{id}")
    @ApiOperation("查询班会主题列表")
    public AjaxResult listFdyNeedByCmId(@PathVariable Long id){
        RtClassMeetingClass dto = new RtClassMeetingClass();
        dto.setCmtId(id);
        dto.tNo = getUsername();
        return rtClassMettingThemeService.listFdyNeedByCmId(dto);
    }


    @PostMapping("/cancelClassMeetingById/{id}")
    @ApiOperation("根据年级删除开设")
    public AjaxResult cancelClassMeetingById(@PathVariable Long id) {
        return rtClassMettingThemeService.cancelClassMeetingById(id);
    }

    @GetMapping("/listChoose")
    @ApiOperation("查询班会主题列表")
    public TableDataInfo listChoose(RtClassMeetingClass param)
    {
        startPage();
        List<RtClassMeetingClass> list = rtClassMettingThemeService.listChoose(param);
        return getDataTable(list);
    }




    @PostMapping("/cancelClassMeetingGrade")
    @ApiOperation("根据年级删除开设")
    public AjaxResult cancelClassMeetingGrade(@RequestBody RtClassMeetingClass param){
        return rtClassMettingThemeService.cancelClassMeetingGrade(param);
    }

    @PostMapping("/chooseClassMeetingGrade")
    @ApiOperation("根据年级开设")
    public AjaxResult chooseClassMeetingGrade(@RequestBody RtClassMeetingClass param){
        return rtClassMettingThemeService.chooseClassMeetingGrade(param);
    }

    @GetMapping("/listEnableGrade")
    public AjaxResult listEnableGrade(){
        return AjaxResult.success(rtClassMettingThemeService.listEnableGrade());
    }

    @GetMapping("/downloadXwFile/{cmNo}")
    public void downloadXwFile(@PathVariable String cmNo, HttpServletResponse response) throws IOException
    {
        List<Map<String, Object>> fileList = rtClassMettingThemeMapper.selectClassFile(cmNo);

        Long oldId = getDeptId();
        SysDeptMap dept = _deptMap.getOldDeptByNewId(oldId);
        Long deptId;
        if (dept != null) {
            deptId = dept.getOldDeptId();
            fileList = fileList.stream().filter(x->Long.parseLong( x.get("dept_id").toString() )==deptId).collect(Collectors.toList());
        } else {
            deptId = null;
        }

        String fileName = "";
        QueryWrapper<RtClassMettingTheme> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cm_no", cmNo);
        RtClassMettingTheme rtClassMettingTheme = rtClassMettingThemeService.getOne(queryWrapper);
        if(rtClassMettingTheme != null){
            fileName = rtClassMettingTheme.getCmTitle();
        }

        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName+".zip", "UTF-8"));

        try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
            for (Map<String, Object> map : fileList) {
                if (map.get("res_path") != null && map.get("class_name") != null) {
                    String filePath =  map.get("res_path").toString();
                    filePath = filePath.replace("/profile/upload","");
                    filePath = getUploadPath() + filePath;
                    File file = new File(filePath);
                    if (file.exists() && file.isFile()) {
                        try (FileInputStream fis = new FileInputStream(file)) {
                            // 创建 ZIP 条目
                            ZipEntry zipEntry = new ZipEntry(map.get("class_name").toString() + "/" +  file.getName());
                            zipOut.putNextEntry(zipEntry);

                            // 写入文件内容
                            byte[] buffer = new byte[1024];
                            int length;
                            while ((length = fis.read(buffer)) > 0) {
                                zipOut.write(buffer, 0, length);
                            }
                            // 关闭当前 ZIP 条目
                            zipOut.closeEntry();
                        }
                    }
                }
            }
        }
    }

    @GetMapping("/downloadFile/{cmNo}")
    public void downloadFile(@PathVariable String cmNo, HttpServletResponse response) throws IOException
    {
        List<Map<String, Object>> fileList = rtClassMettingThemeMapper.selectClassFile(cmNo);

        String fileName = "";
        QueryWrapper<RtClassMettingTheme> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cm_no", cmNo);
        RtClassMettingTheme rtClassMettingTheme = rtClassMettingThemeService.getOne(queryWrapper);
        if(rtClassMettingTheme != null){
            fileName = rtClassMettingTheme.getCmTitle();
        }

        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName+".zip", "UTF-8"));

        try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
            for (Map<String, Object> map : fileList) {
                if (map.get("res_path") != null && map.get("class_name") != null) {
                    String filePath =  map.get("res_path").toString();
                    filePath = filePath.replace("/profile/upload","");
                    filePath = getUploadPath() + filePath;
                    File file = new File(filePath);
                    if (file.exists() && file.isFile()) {
                        try (FileInputStream fis = new FileInputStream(file)) {
                            // 创建 ZIP 条目
                            ZipEntry zipEntry = new ZipEntry(map.get("class_name").toString() + "/" +  file.getName());
                            zipOut.putNextEntry(zipEntry);

                            // 写入文件内容
                            byte[] buffer = new byte[1024];
                            int length;
                            while ((length = fis.read(buffer)) > 0) {
                                zipOut.write(buffer, 0, length);
                            }
                            // 关闭当前 ZIP 条目
                            zipOut.closeEntry();
                        }
                    }
                }
            }
        }
    }


    @Log(title = "班会主题", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation("导出班会主题列表")
    public void export(HttpServletResponse response, RtClassMettingTheme rtClassMettingTheme)
    {
        List<RtClassMettingTheme> list = rtClassMettingThemeService.selectRtClassMettingThemeList(rtClassMettingTheme);
        ExcelUtil<RtClassMettingTheme> util = new ExcelUtil<RtClassMettingTheme>(RtClassMettingTheme.class);
        util.exportExcel(response, list, "班会主题数据");
    }

    @GetMapping("/listTreeDept/{cmNo}")
    @ApiOperation("列出树形提交情况")
    public AjaxResult listTreeDept(@PathVariable("cmNo") String cmNo){
        List<Map<String, Object>> res = rtClassMettingThemeService.listTreeDept(cmNo);
        return AjaxResult.success(res);
    }

    @GetMapping("/listXwTreeDept/{cmNo}")
    @ApiOperation("学务列出树形提交情况")
    public AjaxResult listXwTreeDept(@PathVariable("cmNo") String cmNo){
        Long oldId = getDeptId();
        SysDeptMap dept = _deptMap.getOldDeptByNewId(oldId);
        Long deptId = null;
        if (dept != null) {
            deptId = dept.getOldDeptId();
        }
        List<Map<String, Object>> res = rtClassMettingThemeService.listXwTreeDept(deptId,cmNo);
        return AjaxResult.success(res);
    }


    @GetMapping("/listClassByTNo")
    @ApiOperation("列出老师自己带的班级")
    public AjaxResult listClassByTNo(){
        List<SrsClass> list = rtClassMettingThemeService.listClassByTNo(getUsername());
        return AjaxResult.success(list);
    }



    @GetMapping("/listClassByMajorId")
    @ApiOperation("通过专业id列出班级")
    public AjaxResult listClassByMajorId(RtClassMettingTheme params) {
        List<Map<String, Object>> list = rtClassMettingThemeService.listClassByMajorId(params);
        return AjaxResult.success(list);
    }

    @GetMapping("/listMajorsByDeptId/{deptId}")
    @ApiOperation("通过学院id列出专业")
    public AjaxResult listMajorsByDeptId(@PathVariable("deptId") Long deptId){
        List<SrsMajors> list = rtClassMettingThemeService.listMajorsByDeptId(deptId);
        return AjaxResult.success(list);
    }


    @GetMapping("/listDept")
    @ApiOperation("列出学院")
    public AjaxResult listDept(){
        List<SysDept> list = rtClassMettingThemeService.listDept();
        return AjaxResult.success(list);
    }


    /**
     * 查询班会主题列表
     */
    //@PreAuthorize("@ss.hasPermi('runtine:ClassMettingTheme:list')")
    @GetMapping("/list")
    @ApiOperation("查询班会主题列表")
    public TableDataInfo list(RtClassMettingTheme rtClassMettingTheme)
    {
        List<RtClassMettingTheme> list=new ArrayList<>();
        try{
            rtClassMettingTheme.setUserName(getUsername());
            startPage();
            list = rtClassMettingThemeService.selectRtClassMettingThemeList(rtClassMettingTheme);
            return getDataTable(list);
        }catch (Exception e){
            return getDataTable(list);
        }
    }

    @GetMapping("/completeStuList")
    @ApiOperation("查询自己是否已上传材料")
    public TableDataInfo completeStuList(RtClassMettingTheme rtClassMettingTheme){
        List<RtClassMettingTheme> list=new ArrayList<>();
        try{
            List<Map< String, Object >> list1 = rtClassMettingStuUploadService.listStuClass(getUsername());
            if(list1.size() == 0){
                throw new RuntimeException("未查询到您的学生信息，请联系管理员");
            }
            Map< String, Object > map = list1.get(0);
            rtClassMettingTheme.classCode= map.get("class_id").toString();
            startPage();
            list = rtClassMettingThemeService.completeStuList(rtClassMettingTheme);
            return getDataTable(list);
        }catch (Exception e){
            return getDataTable(list);
        }
    }

    /**
     * 查询自己是否已上传材料
     * @return
     */
    @GetMapping("/complatelist")
    @ApiOperation("查询自己是否已上传材料")
    public TableDataInfo selectCurrentThemeComplateList(RtClassMettingTheme rtClassMettingTheme){
        List<RtClassMettingTheme> list=new ArrayList<>();
        try{
            startPage();
            rtClassMettingTheme.setUserName(getUsername());
            list = rtClassMettingThemeService.selectCurrentThemeComplateList(rtClassMettingTheme);
        return getDataTable(list);
        }catch (Exception e){
            return getDataTable(list);
        }
    }

    @GetMapping("/listFdyNeedCm")
    @ApiOperation("列出辅导员需要开设的班会")
    public TableDataInfo listFdyNeedCm(RtClassMettingTheme rtClassMettingTheme){
        List<RtClassMettingTheme> list=new ArrayList<>();
        try{
            startPage();
            rtClassMettingTheme.setUserName(getUsername());
            list = rtClassMettingThemeService.listFdyNeedCm(rtClassMettingTheme);
            return getDataTable(list);
        }catch (Exception e){
            return getDataTable(list);
        }
    }


    /**
     * 导出班会主题列表
     */
    //@PreAuthorize("@ss.hasPermi('runtine:ClassMettingTheme:export')")
    @Log(title = "班会主题", businessType = BusinessType.EXPORT)
    @PostMapping("/exportSubmit/{cmNo}")
    @ApiOperation("导出班会主题列表")
    public void exportSubmit(HttpServletResponse response, @PathVariable("cmNo") String cmNo)
    {
        List<ClassMettingThemeSumitListVo> list = rtClassMettingThemeService.selectSubmit(cmNo);
        ExcelUtil<ClassMettingThemeSumitListVo> util = new ExcelUtil<ClassMettingThemeSumitListVo>(ClassMettingThemeSumitListVo.class);
        util.exportExcel(response, list, "班会主题提交数据");
    }

    @Log(title = "班会主题", businessType = BusinessType.EXPORT)
    @PostMapping("/exportXwSubmit/{cmNo}")
    @ApiOperation("学务导出班会主题列表")
    public void exportXwSubmit(HttpServletResponse response, @PathVariable("cmNo") String cmNo)
    {
        List<ClassMettingThemeSumitListVo> list = rtClassMettingThemeService.selectSubmit(cmNo);
        Long oldId = getDeptId();
        SysDeptMap dept = _deptMap.getOldDeptByNewId(oldId);
        Long deptId;
        if (dept != null) {
            deptId = dept.getOldDeptId();
            list = list.stream().filter(x->x.deptId != null && x.deptId.toString().equals( deptId.toString())).collect(Collectors.toList());
        } else {
            deptId = null;
        }
        ExcelUtil<ClassMettingThemeSumitListVo> util = new ExcelUtil<ClassMettingThemeSumitListVo>(ClassMettingThemeSumitListVo.class);
        util.exportExcel(response, list, "班会主题提交数据");
    }

    /**
     * 获取班会主题详细信息
     */
    //@PreAuthorize("@ss.hasPermi('runtine:ClassMettingTheme:query')")
    @GetMapping(value = "/{cmId}")
    @ApiOperation("获取班会主题详细信息")
    public AjaxResult getInfo(@PathVariable("cmId") Long cmId)
    {
        return success(rtClassMettingThemeService.selectRtClassMettingThemeByCmId(cmId));
    }

    /**
     * 新增班会主题
     */
    //@PreAuthorize("@ss.hasPermi('runtine:ClassMettingTheme:add')")
    @Log(title = "班会主题", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ApiOperation("新增班会主题")
    public AjaxResult add(@RequestBody RtClassMettingTheme rtClassMettingTheme)
    {
        rtClassMettingTheme.setCreateBy(getUsername());
        return toAjax(rtClassMettingThemeService.insertRtClassMettingTheme(rtClassMettingTheme));
    }

    /**
     * 修改班会主题
     */
    //@PreAuthorize("@ss.hasPermi('runtine:ClassMettingTheme:edit')")
    @Log(title = "班会主题", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    @ApiOperation("修改班会主题")
    public AjaxResult edit(@RequestBody RtClassMettingTheme rtClassMettingTheme)
    {
        rtClassMettingTheme.setUpdateBy(getUsername());
        return toAjax(rtClassMettingThemeService.updateRtClassMettingTheme(rtClassMettingTheme));
    }

    /**
     * 删除班会主题
     */
    //@PreAuthorize("@ss.hasPermi('runtine:ClassMettingTheme:remove')")
    @Log(title = "班会主题", businessType = BusinessType.DELETE)
    @PostMapping("/{cmIds}")
    @ApiOperation("删除班会主题")
    public AjaxResult remove(@PathVariable Long[] cmIds)
    {
        return toAjax(rtClassMettingThemeService.deleteRtClassMettingThemeByCmIds(cmIds));
    }
}
