package yangtz.cs.liu.campus.controller.schoolgrade;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.core.utils.HolidayDateUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysDeptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import yangtz.cs.liu.campus.controller.patrol.SchoolPatrolController;
import yangtz.cs.liu.campus.domain.schoolgrade.SchoolGrade;
import yangtz.cs.liu.campus.service.schoolgrade.ISchoolGradeMentorService;
import yangtz.cs.liu.campus.service.schoolgrade.ISchoolGradeService;
import yangtz.cs.liu.campus.service.student.ISchoolStudentService;
import yangtz.cs.liu.campus.vo.schoolgrade.GradeTreeSelect;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import static com.ruoyi.common.utils.StringUtils.isNull;
import static yangtz.cs.liu.campus.constant.EmployeeType.EMPLOYEE;
import static yangtz.cs.liu.campus.constant.EmployeeType.TEACH;
import static yangtz.cs.liu.campus.constant.GradeConstant.NEWTERM;
import static yangtz.cs.liu.campus.constant.GradeConstant.UNNEW;

/**
 * 级部管理
 */
@RestController
@RequestMapping("/schoolGrade")
public class SchoolGradeController extends BaseController {
    @Autowired
    private ISchoolGradeService schoolGradeService;

    @Autowired
    private ISchoolStudentService schoolStudentService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISchoolGradeMentorService gradeMentorService;

    /**
     * 查询学校年级级部列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SchoolGrade schoolGrade) {
        startPage();
        List<SchoolGrade> list = schoolGradeService.queryList(schoolGrade);
        return getDataTable(list);
    }

    /**
     * 根据登录人职工类型，判断返回级部信息还是处室信息
     */
    @GetMapping("/getList")
    public AjaxResult getList() {
        String employeeType = getLoginUser().getUser().getEmployeeType();
        //是教工
        if (employeeType.equals(TEACH)) {
            int schoolYear = HolidayDateUtil.getSchoolYear();
            SchoolGrade schoolGrade = new SchoolGrade();
            //schoolGrade.setSfzxxn(NEWTERM);
            schoolGrade.setSchoolYear(String.valueOf(schoolYear));
            List<SchoolGrade> list = schoolGradeService.queryList(schoolGrade);
            List<GradeTreeSelect> gradeTreeSelectList = new ArrayList<>();
            if (StringUtils.isNotNull(list)) {
                gradeTreeSelectList = schoolGradeService.buildGradeTreeList(list);
            }
            return AjaxResult.success(gradeTreeSelectList);
        }
        //职工
        return AjaxResult.success(deptService.selectDeptTreeList(new SysDept()));
    }

    /**
     * 级部信息
     */
    @GetMapping("/getGradeTree")
    public AjaxResult getGradeTree() {
        int schoolYear = HolidayDateUtil.getSchoolYear();
        SchoolGrade schoolGrade = new SchoolGrade();
        schoolGrade.setSchoolYear(String.valueOf(schoolYear));
        List<SchoolGrade> list = schoolGradeService.queryList(schoolGrade);
        List<GradeTreeSelect> gradeTreeSelectList = new ArrayList<>();
        if (StringUtils.isNotNull(list)) {
            gradeTreeSelectList = schoolGradeService.buildGradeTreeList(list);
        }
        return AjaxResult.success(gradeTreeSelectList);
    }
    /**
     * 级部成员所在级部树
     */
    @GetMapping("/getUserGradeTree")
    public AjaxResult getUserGradeTree() {
        //获取当前学年
        int schoolYear = HolidayDateUtil.getSchoolYear();
        List<SchoolGrade> grades = gradeMentorService.selectGrades(getUserId(),schoolYear);
        List<GradeTreeSelect> gradeTreeSelectList = new ArrayList<>();
        if (StringUtils.isNotNull(grades)) {
            gradeTreeSelectList = schoolGradeService.buildGradeTreeList(grades);
        }
        return AjaxResult.success(gradeTreeSelectList);
    }

    /**
     * 获取级部成员所在级部id
     */
    @GetMapping("/getMemberGrade")
    public AjaxResult getMemberGrade() {
        return AjaxResult.success(schoolGradeService.getMemberGrade(getUserId()));
    }

    /**
     * 获取教师所在级部id
     */
    @GetMapping("/getGrade")
    public AjaxResult getGrade() {
        return AjaxResult.success(schoolGradeService.getGradeId(getUserId()));
    }


    /**
     * 获取当前登录人所在部门或级部
     */
    @GetMapping("/getDeptOrGrade")
    public AjaxResult getDeptOrGrade() {
        String employeeType = getLoginUser().getUser().getEmployeeType();
        //是教工
        if (employeeType.equals(TEACH)) {
            //判断所在班级所在级部（存在一个老师跨几个级部教学，比如体育老师，所以获取教授班级所在级部，随便选择某个级部即可）
            return AjaxResult.success(schoolGradeService.getGradeId(getUserId()));
        }
        //职工
        return AjaxResult.success(getDeptId());
    }

    /**
     * 获取学校年级级部详细信息
     */
    @GetMapping(value = "/getInfo/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(schoolGradeService.getById(id));
    }

    /**
     * 新增学校年级级部
     */
    @Log(title = "学校年级级部", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody SchoolGrade schoolGrade) {
        checkGradeUnique(schoolGrade);
        //是否是最新学年
        String sfzxxn = isNewTerm(schoolGrade.getSchoolYear());
        schoolGrade.setSfzxxn(sfzxxn);
        return toAjax(schoolGradeService.save(schoolGrade));
    }

    /**
     * 修改学校年级级部
     */
    @Log(title = "学校年级级部", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody SchoolGrade schoolGrade) {
        if (StringUtils.isNull(schoolGrade.getId())) {
            throw new BaseException("年级id不能为空");
        }
        checkGradeUnique(schoolGrade);
        //是否是最新学年
        String sfzxxn = isNewTerm(schoolGrade.getSchoolYear());
        schoolGrade.setSfzxxn(sfzxxn);
        return toAjax(schoolGradeService.updateById(schoolGrade));
    }

    /**
     * 新增或修改学校年级级部时校验是否已经存在年级
     */
    private void checkGradeUnique(SchoolGrade schoolGrade) {
        LambdaQueryWrapper<SchoolGrade> lqw = new LambdaQueryWrapper<>();
        lqw
                .eq(SchoolGrade::getSchoolYear, schoolGrade.getSchoolYear())
                .eq(SchoolGrade::getGradeValue, schoolGrade.getGradeValue())
        ;
        SchoolGrade grade = schoolGradeService.getOne(lqw);
        if (StringUtils.isNotNull(grade)) {
            if (StringUtils.isNotNull(schoolGrade.getId()) && schoolGrade.getId().equals(grade.getId())) {
                return;
            }
            throw new ServiceException("年级已存在");
        }

        //处于最同一学年的年级名称不能相同
        LambdaQueryWrapper<SchoolGrade> judgeName = new LambdaQueryWrapper<>();
        judgeName.eq(SchoolGrade::getGradeName, schoolGrade.getGradeName())
                .eq(SchoolGrade::getSchoolYear, schoolGrade.getSchoolYear());
        //.eq(SchoolGrade::getSfzxxn,NEWTERM);
        SchoolGrade s = schoolGradeService.getOne(judgeName);
        if (StringUtils.isNotNull(s)) {
            if (StringUtils.isNotNull(schoolGrade.getId()) && schoolGrade.getId().equals(s.getId())) {
                return;
            }
            throw new ServiceException("该学年年级名称已存在");
        }
    }

    /**
     * 删除学校年级级部
     */
    @PreAuthorize("@ss.hasPermi('system:grade:remove')")
    @Log(title = "学校年级级部", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(schoolGradeService.removeByIds(ids));
    }

    /**
     * 判断是否是最新学年
     */
    private String isNewTerm(String year) {
        Calendar cal = Calendar.getInstance();
        //获取当前年月
        int nowYear = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        //设置当前学期
        int term = 1;
        //2-7为第二学期，8-1为第一学期
        //如果当前月份小于8月，则该学年应为当前年-1 到 当前年,例如当前年月为2023年7月，则该学年为2022-2023年的第二学期
        if (month < 8) {
            nowYear = nowYear - 1;
        }
        if (month >= 2 && month < 8) {
            term = 2;
        }
        //如果获取的year与当前学年的起始年份相同，则设置当前学年是最新学年
        if (year.equals("" + nowYear)) {
            return NEWTERM;
        }
        return UNNEW;
    }

    /**
     * 获取最新学年值
     */
    @GetMapping("/getNewYear")
    public AjaxResult getNewYear() {
       /* AjaxResult ajaxResult = AjaxResult.success();
        LambdaQueryWrapper<SchoolGrade> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolGrade::getSfzxxn,NEWTERM).orderByDesc(SchoolGrade::getSchoolYear);
        List<SchoolGrade> list = schoolGradeService.list(lqw);
        if(isNull(list) || list.size() == 0){
            throw new ServiceException("获取最新学年值异常，请检查级部相关信息");
        }
        ajaxResult.put("schoolYear",list.get(0).getSchoolYear());
        return ajaxResult;*/


        Calendar cal = Calendar.getInstance();
        //获取当前年月
        int nowYear = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        //设置当前学期
        int term = 1;
        //2-7为第二学期，8-1为第一学期
        //如果当前月份小于8月，则该学年应为当前年-1 到 当前年,例如当前年月为2023年7月，则该学年为2022-2023年的第二学期
        if (month < 8) {
            nowYear = nowYear - 1;
        }
        if (month >= 2 && month < 8) {
            term = 2;
        }
        AjaxResult ajaxResult = AjaxResult.success();
        ajaxResult.put("schoolYear", nowYear);
        return ajaxResult;
    }

    /**
     * 升级
     * （初始化三条数据后，可进行升级操作，新插入一条级部信息，上两个级部的学年和年级自动+1）
     * 级部信息发生变化，对应所在本级部的班级的有关级部的信息也要发生改变
     * */
    @PutMapping("/upgrade")
    public AjaxResult upgrade() {
        return toAjax(schoolGradeService.upgrade());
    }


}
