package com.ruoyi.web.controller.dz;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BoolValues;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.dz.domain.DzSchool;
import com.ruoyi.dz.domain.DzTeacher;
import com.ruoyi.dz.domain.DzTeacherClass;
import com.ruoyi.dz.mapper.DzSchoolMapper;
import com.ruoyi.dz.service.IDzTeacherClassService;
import com.ruoyi.enums.UserTypeEnum;
import io.lettuce.core.dynamic.annotation.Param;
import org.springframework.security.access.prepost.PreAuthorize;
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.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.dz.domain.DzClasses;
import com.ruoyi.dz.service.IDzClassesService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 学生班级Controller
 *
 * @author ruoyi
 * @date 2025-09-29
 */
@RestController
@RequestMapping("/dz/classes")
public class DzClassesController extends BaseController
{
    @Autowired
    private IDzClassesService dzClassesService;
    @Autowired
    private IDzTeacherClassService teacherClassService;
    @Autowired
    private DzSchoolMapper dzSchoolMapper;

    /**
     * 查询学生班级列表
     */
    // @PreAuthorize("@ss.hasPermi('dz:classes:list')")
    @GetMapping("/list")
    public TableDataInfo list(DzClasses dzClasses)
    {
        startPage();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (!UserTypeEnum.isSys(sysUser.getUserType())) {
            dzClasses.setDeptId(sysUser.getDeptId());
            if (UserTypeEnum.isSchool(sysUser.getUserType())) {
                dzClasses.setSchoolId(sysUser.getUserTypeId());
            }
        }
        if(null != dzClasses.getSchoolId()) {
            DzSchool dzSchool = dzSchoolMapper.selectDzSchoolById(dzClasses.getSchoolId());
            if (null == dzSchool.getDeptId()) {
                dzClasses.setDeptId(0L);
            } else {
                dzClasses.setDeptId(dzSchool.getDeptId());
            }
        }
        List<DzClasses> list = dzClassesService.selectDzClassesList(dzClasses);
        return getDataTable(list);
    }

    @GetMapping("/listAll")
    public AjaxResult listAll(DzClasses dzClasses)
    {
        List<DzClasses> list = dzClassesService.selectDzClassesList(dzClasses);
//        if (null!=dzClasses.getTeacherId()){
//            DzTeacherClass query = new DzTeacherClass().setTeacherId(dzClasses.getTeacherId());
//            Long[] classIds = teacherClassService.selectDzTeacherClassList(query).stream()
//                    .map(DzTeacherClass::getClassId)
//                    .filter(Objects::nonNull)
//                    .distinct() // 去重（如果需要）
//                    .toArray(Long[]::new);
//            list.stream().forEach(c->c.setClassIds(classIds));
//        }
        return AjaxResult.success(list);
    }

    @GetMapping("/getClassesBySchoolId")
    public AjaxResult getClassesBySchoolId(@RequestParam("schoolId") Long schoolId)
    {
        List<DzClasses> list = dzClassesService.selectDzClassesListBySchoolId(schoolId);
        return AjaxResult.success(list);
    }

    @GetMapping("/getClassesByCampusId")
    public AjaxResult getClassesByCampusId(@RequestParam("campusId") Long campusId)
    {
        List<DzClasses> list = dzClassesService.selectDzClassesListByCampusId(campusId);
        return AjaxResult.success(list);
    }

    /**
     * 导出学生班级列表
     */
    @PreAuthorize("@ss.hasPermi('dz:classes:export')")
    @Log(title = "学生班级", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DzClasses dzClasses)
    {
        List<DzClasses> list = dzClassesService.selectDzClassesList(dzClasses);
        ExcelUtil<DzClasses> util = new ExcelUtil<DzClasses>(DzClasses.class);
        util.exportExcel(response, list, "学生班级数据");
    }

    /**
     * 获取学生班级详细信息
     */
    @PreAuthorize("@ss.hasPermi('dz:classes:query')")
    @GetMapping(value = "/{classId}")
    public AjaxResult getInfo(@PathVariable("classId") Long classId)
    {
        return success(dzClassesService.selectDzClassesByClassId(classId));
    }

    /**
     * 新增学生班级
     */
    @PreAuthorize("@ss.hasPermi('dz:classes:add')")
    @Log(title = "学生班级", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DzClasses dzClasses)
    {
        String name = dzClasses.getName();
        DzSchool dzSchool = dzSchoolMapper.selectDzSchoolById(dzClasses.getSchoolId());
        dzClasses.setDeptId(dzSchool.getDeptId());
        if(StringUtils.isNotEmpty(name)){
            // 校验每个班级名称是否重复
            String[] nameArray = name.split(",");
            for (String s : nameArray) {
                String trimmedName = s.trim();
                if (StringUtils.isNotEmpty(trimmedName)) {
                    // 校验班级名称是否重复
                    if (!dzClassesService.checkClassName(dzClasses.getSchoolId(), trimmedName, null)) {
                        return error("班级名称【" + trimmedName + "】在该学校下已存在，请使用其他名称");
                    }
                }
            }
            // 校验通过后，创建班级
            for (String s : nameArray) {
                String trimmedName = s.trim();
                if (StringUtils.isNotEmpty(trimmedName)) {
                    dzClasses.setName(trimmedName);
                    dzClasses.setIsDefault(BoolValues.no.getValue());
                    dzClassesService.insertDzClasses(dzClasses);
                }
            }
            //把创建的默认旧班级删除
//            if (null!=dzClasses.getSchoolId()){
//                DzClasses query = new DzClasses();
//                query.setIsDefault(BoolValues.yes.getValue());
//                query.setSchoolId(dzClasses.getSchoolId());
//                List<DzClasses> dzClassesList = dzClassesService.selectDzClassesList(query);
//                if (CollectionUtil.isNotEmpty(dzClassesList)) {
//                    Long[] classesIds = dzClassesList.stream().map(DzClasses::getClassId).filter(id -> id != null).toArray(Long[]::new);
//                    if (null!=classesIds&&classesIds.length>0){
//                        dzClassesService.deleteDzClassesByClassIds(classesIds);
//                    }
//                }
//            }
        }
        return toAjax(1);
    }

    /**
     * 修改学生班级
     */
    @PreAuthorize("@ss.hasPermi('dz:classes:edit')")
    @Log(title = "学生班级", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DzClasses dzClasses)
    {
        // 校验班级名称是否重复
        if (StringUtils.isNotEmpty(dzClasses.getName()) && dzClasses.getSchoolId() != null) {
            String trimmedName = dzClasses.getName().trim();
            if (!dzClassesService.checkClassName(dzClasses.getSchoolId(), trimmedName, dzClasses.getClassId())) {
                return error("班级名称【" + trimmedName + "】在该学校下已存在，请使用其他名称");
            }
        }
        return toAjax(dzClassesService.updateDzClasses(dzClasses));
    }

    /**
     * 删除学生班级
     */
    @PreAuthorize("@ss.hasPermi('dz:classes:remove')")
    @Log(title = "学生班级", businessType = BusinessType.DELETE)
    @DeleteMapping("/{classIds}")
    public AjaxResult remove(@PathVariable Long[] classIds)
    {
        return toAjax(dzClassesService.deleteDzClassesByClassIds(classIds));
    }

    /**
     * 校验班级名称在同一学校下是否唯一
     */
    @GetMapping("/checkClassName")
    public AjaxResult checkClassName(@RequestParam("schoolId") Long schoolId,
                                     @RequestParam("name") String name,
                                     @RequestParam(value = "classId", required = false) Long classId)
    {
        boolean isUnique = dzClassesService.checkClassName(schoolId, name, classId);
        return AjaxResult.success(isUnique);
    }
}
