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

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
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 yangtz.cs.liu.campus.domain.schoolClass.SchoolClassMentor;
import yangtz.cs.liu.campus.domain.schoolLab.SchoolLabClassYear;
import yangtz.cs.liu.campus.domain.schoolLab.SchoolLabClassYearRelation;
import yangtz.cs.liu.campus.service.schoolClass.ISchoolClassMentorService;
import yangtz.cs.liu.campus.service.schoolLab.ISchoolExperimentPlanService;
import yangtz.cs.liu.campus.service.schoolLab.ISchoolLabClassYearRelationService;
import yangtz.cs.liu.campus.service.schoolLab.ISchoolLabClassYearService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import yangtz.cs.liu.campus.service.schoolgrade.ISchoolGradeService;
import yangtz.cs.liu.campus.vo.schoolLab.SchoolExperimentPlanVo;
import yangtz.cs.liu.campus.vo.schoolLab.SchoolLabClassYearVo;

/**
 * 年级实验室预约Controller
 *
 * @author ruoyi
 * @date 2023-08-29
 */
@RestController
@RequestMapping("/schoolLabClassYear")
public class SchoolLabClassYearController extends BaseController
{

    @Autowired
    private ISchoolLabClassYearService schoolLabClassYearService;
    @Autowired
    private ISchoolExperimentPlanService schoolExperimentPlanService;
    @Autowired
    private ISchoolLabClassYearRelationService schoolLabClassYearRelationService;
    @Autowired
    private ISchoolGradeService gradeService;
    @Autowired
    private ISchoolClassMentorService classMentorService;

    /**
     * 查询年级实验室预约列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SchoolLabClassYearVo schoolLabClassYearVo)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        //如果是管理员返回全部数据
        if (user.isAdmin()){
            startPage();
            List<SchoolLabClassYearVo> list = schoolLabClassYearService.selectLabClassYearListAdmin(schoolLabClassYearVo);
            list.forEach(list1 -> {
                String semester = "";
                if (list1.getSemester().equals("1")){
                    semester = "上学期";
                }else {
                    semester = "下学期";
                }
                list1.setSchoolYearSemester(list1.getSchoolYear() + semester);
                list1.setPlannedTime(format.format(list1.getPlannedStartTime()) + "至" + format.format(list1.getPlannedEndTime()));
                if (list1.getDeclareState().equals("3")){
                    LambdaQueryWrapper<SchoolLabClassYearRelation> lqw = new LambdaQueryWrapper<>();
                    lqw.eq(SchoolLabClassYearRelation::getLabClassYearId,list1.getId());
                    List<SchoolLabClassYearRelation> relations = schoolLabClassYearRelationService.list(lqw);
                    list1.setSchoolLabClassYearRelationList(relations);
                }
            });
            return getDataTable(list);
        }
        //获取最新学年
        int schoolYear = gradeService.isNewSchoolYear();
        //教师级部
        List<Map<String, Object>> gradeList = schoolExperimentPlanService.getGrade(schoolYear,user.getUserId());
        if (StringUtils.isNull(gradeList) || gradeList.size() == 0) {
            throw new ServiceException("没有您所在的级部信息");
        }
        //级部id集合
        List<Long> gradeIds = new ArrayList<>();
        gradeList.forEach(gradeList1 -> {
            Long gradeId = Long.valueOf(String.valueOf(gradeList1.get("id")));
            gradeIds.add(gradeId);
        });

        schoolLabClassYearVo.setGradeIds(gradeIds);
        schoolLabClassYearVo.setUserId(user.getUserId());
        startPage();
        List<SchoolLabClassYearVo> list =  schoolLabClassYearService.selectSchoolLabClassYearList(schoolLabClassYearVo);

        list.forEach(list1 -> {
            String semester = "";
            if (list1.getSemester().equals("1")){
                semester = "上学期";
            }else {
                semester = "下学期";
            }
            list1.setSchoolYearSemester(list1.getSchoolYear() + semester);
            list1.setPlannedTime(format.format(list1.getPlannedStartTime()) + "至" + format.format(list1.getPlannedEndTime()));
            if (list1.getDeclareState().equals("3")){
                LambdaQueryWrapper<SchoolLabClassYearRelation> lqw = new LambdaQueryWrapper<>();
                lqw.eq(SchoolLabClassYearRelation::getLabClassYearId,list1.getId());
                List<SchoolLabClassYearRelation> relations = schoolLabClassYearRelationService.list(lqw);
                list1.setSchoolLabClassYearRelationList(relations);
            }
        });
        return getDataTable(list);
    }

    /**
     * 导出年级实验室预约列表
     */
    @Log(title = "年级实验室预约", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SchoolLabClassYearVo schoolLabClassYearVo)
    {
        List<SchoolLabClassYearVo> list = schoolLabClassYearService.selectSchoolLabClassYearList(schoolLabClassYearVo);
        ExcelUtil<SchoolLabClassYearVo> util = new ExcelUtil<SchoolLabClassYearVo>(SchoolLabClassYearVo.class);
        util.exportExcel(response, list, "年级实验室预约数据");
    }

    /**
     * 获取年级实验室预约详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        SchoolLabClassYearVo schoolLabClassYearVo = schoolLabClassYearService.selectSchoolLabClassYearById(id);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String semester = "";
        if (schoolLabClassYearVo.getSemester().equals("1")){
            semester = "上学期";
        }else {
            semester = "下学期";
        }
        schoolLabClassYearVo.setSchoolYearSemester(schoolLabClassYearVo.getSchoolYear() + semester);
        schoolLabClassYearVo.setPlannedTime(format.format(schoolLabClassYearVo.getPlannedStartTime()) + "至" + format.format(schoolLabClassYearVo.getPlannedEndTime()));
        if (schoolLabClassYearVo.getDeclareState().equals("3")){
            LambdaQueryWrapper<SchoolLabClassYearRelation> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SchoolLabClassYearRelation::getLabClassYearId,id);
            List<SchoolLabClassYearRelation> schoolLabClassYearRelations = schoolLabClassYearRelationService.list(wrapper);
            schoolLabClassYearVo.setSchoolLabClassYearRelationList(schoolLabClassYearRelations);
        }
        return AjaxResult.success(schoolLabClassYearVo);
    }

    /**
     * 新增年级实验室预约
     */
    @Log(title = "年级实验室预约", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody SchoolLabClassYear schoolLabClassYear)
    {
        return toAjax(schoolLabClassYearService.insertSchoolLabClassYearVo(schoolLabClassYear));
    }

    /**
     * 修改年级实验室预约
     */
    @Log(title = "年级实验室预约", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody SchoolLabClassYear schoolLabClassYear)
    {
        return toAjax(schoolLabClassYearService.updateSchoolLabClassYearVo(schoolLabClassYear));
    }

    /**
     * 删除年级实验室预约
     */
    @Log(title = "年级实验室预约", businessType = BusinessType.DELETE)
    @PostMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(schoolLabClassYearService.deleteSchoolLabClassYearByIds(ids));
    }

    /**
     * 获取实验名称下拉框
     */
    @GetMapping("/getLab")
    public AjaxResult getLab(SchoolExperimentPlanVo schoolExperimentPlanVo){
        schoolExperimentPlanVo.setIsAppointment("0");
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //如果是管理员，查询全部列表
        if (user.isAdmin()){
            startPage();
            List<SchoolExperimentPlanVo> list = schoolExperimentPlanService.selectSchoolExperimentPlanList(schoolExperimentPlanVo);
            list.forEach(list1 -> {
                String semester = "";
                if (list1.getSemester().equals("1")){
                    semester = "上学期";
                }else {
                    semester = "下学期";
                }
                list1.setSchoolYearSemester(list1.getSchoolYear() + semester);
                list1.setPlannedTime(list1.getPlannedStartTime() + "至" + list1.getPlannedEndTime());
            });
            return AjaxResult.success(list);
        }

        //获取最新学年
        int schoolYear = gradeService.isNewSchoolYear();
        //教师级部
        List<Map<String, Object>> gradeList = schoolExperimentPlanService.getGrade(schoolYear,user.getUserId());
        if (StringUtils.isNull(gradeList) || gradeList.size() == 0) {
            throw new ServiceException("没有您所在的级部信息");
        }

        //级部id集合
        List<Long> gradeIds = new ArrayList<>();
        gradeList.forEach(gradeList1 -> {
            Object id = gradeList1.get("id");
            Long gradeId = Long.valueOf(String.valueOf(id));
            gradeIds.add(gradeId);
        });

//        //查询级部成员信息
//        LambdaQueryWrapper<SchoolGradeMentor> wrapper = new LambdaQueryWrapper<>();
//        wrapper.in(SchoolGradeMentor::getGradeId,gradeIds)
//                .eq(SchoolGradeMentor::getTeacherId,user.getUserId());
//        List<SchoolGradeMentor> schoolGradeMentors = schoolGradeMentorService.list(wrapper);

        schoolExperimentPlanVo.setGradeIds(gradeIds);
        schoolExperimentPlanVo.setTeacherId(getUserId());
        List<SchoolExperimentPlanVo> list = schoolExperimentPlanService.selectSchoolExperimentPlanList(schoolExperimentPlanVo);

//        List<SchoolExperimentPlanVo> listNew = new ArrayList<>();
//
//        //去除用户所在级部和所在学科组不匹配的数据
//        if (StringUtils.isNotNull(schoolGradeMentors)){
//            for (SchoolExperimentPlanVo experimentPlanVo : list) {
//                for (SchoolGradeMentor schoolGradeMentor : schoolGradeMentors) {
//                    if (schoolGradeMentor.getGradeId().equals(experimentPlanVo.getGradeId())){
//                        if (StringUtils.isNotBlank(schoolGradeMentor.getSubGroup())){
//                            if (!(schoolGradeMentor.getSubGroup().equals(experimentPlanVo.getSub()))){
//                                listNew.add(experimentPlanVo);
//                            }
//                        }else {
//                            listNew.add(experimentPlanVo);
//                        }
//                    }
//                }
//            }
//        }
//
//        if (listNew.size() > 0){
//            for (SchoolExperimentPlanVo experimentPlanVo : listNew) {
//                list.remove(experimentPlanVo);
//            }
//        }

        list.forEach(list1 -> {
            String semester = "";
            if (list1.getSemester().equals("1")){
                semester = "上学期";
            }else {
                semester = "下学期";
            }
            list1.setSchoolYearSemester(list1.getSchoolYear() + semester);
            list1.setPlannedTime(list1.getPlannedStartTime() + "至" + list1.getPlannedEndTime());
        });
        return AjaxResult.success(list);
    }

    /**
     * 实验室管理-年级实验室预约列表
     */
    @GetMapping("/getLabClassYear")
    public TableDataInfo getLabClassYear(SchoolLabClassYearVo schoolLabClassYearVo){
        startPage();
        return getDataTable(schoolLabClassYearService.getLabClassYear(schoolLabClassYearVo));
    }

    /**
     * 实验室管理-年级实验室预约查看详情
     */
    @GetMapping("/getLabClassYear/{id}")
    public AjaxResult getLabClassYearById(@PathVariable("id") Long id){
        return AjaxResult.success(schoolLabClassYearService.getLabClassYearById(id));
    }

    /**
     * 实验室管理-年级实验室-分配实验室
     */
    @PostMapping("/allocationLab")
    public AjaxResult allocationLab(@RequestBody SchoolLabClassYearVo schoolLabClassYearVo){
        return toAjax(schoolLabClassYearService.updateLabClassYear(schoolLabClassYearVo));
    }

    /**
     * 获取实验室
     */
    @GetMapping("/getLabList")
    public AjaxResult getLabList(SchoolLabClassYearVo schoolLabClassYearVo){
        return AjaxResult.success(schoolLabClassYearService.getLabList(schoolLabClassYearVo));
    }

    /**
     * 教师-实验室安排列表
     */
    @GetMapping("/getTeacherLabList")
    public TableDataInfo getTeacherLabList(SchoolLabClassYearVo schoolLabClassYearVo){
        SysUser user = SecurityUtils.getLoginUser().getUser();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        //如果是管理员返回全部数据
        if (user.isAdmin()){
            startPage();
            List<SchoolLabClassYearVo> list = schoolLabClassYearService.selectSchoolLabClassYearList(schoolLabClassYearVo);
            list.forEach(list1 -> {
                String semester = "";
                if (list1.getSemester().equals("1")){
                    semester = "上学期";
                }else {
                    semester = "下学期";
                }
                list1.setSchoolYearSemester(list1.getSchoolYear() + semester);
                list1.setPlannedTime(format.format(list1.getPlannedStartTime()) + "至" + format.format(list1.getPlannedEndTime()));
                if (list1.getDeclareState().equals("3") || list1.getDeclareState().equals("2")){
                    LambdaQueryWrapper<SchoolLabClassYearRelation> lqw = new LambdaQueryWrapper<>();
                    lqw.eq(SchoolLabClassYearRelation::getLabClassYearId,list1.getId());
                    List<SchoolLabClassYearRelation> relations = schoolLabClassYearRelationService.list(lqw);
                    list1.setSchoolLabClassYearRelationList(relations);
                }
            });
            return getDataTable(list);
        }
        //学科集合
        List<String> subs = new ArrayList<>();
        // 查询该教师属于哪个班级，教哪门课
        LambdaQueryWrapper<SchoolClassMentor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SchoolClassMentor::getTeacherId,user.getUserId())
                .in(SchoolClassMentor::getCourseName,"物理","化学","生物");
        List<SchoolClassMentor> schoolClassMentors = classMentorService.list(wrapper);
        if (StringUtils.isNotNull(schoolClassMentors)){
            for (SchoolClassMentor schoolClassMentor : schoolClassMentors) {
                switch (schoolClassMentor.getCourseName()){
                    case "物理" : subs.add("1");break;
                    case "化学" : subs.add("2");break;
                    case "生物" : subs.add("3");break;
                    default:break;
                }
            }
        }
        schoolLabClassYearVo.setApplyId(user.getUserId());
        if(subs.size() > 0){
            schoolLabClassYearVo.setSubs(subs);
        }
        startPage();
        List<SchoolLabClassYearVo> list = schoolLabClassYearService.getTeacherLabList(schoolLabClassYearVo);
        list.forEach(list1 -> {
            String semester = "";
            if (list1.getSemester().equals("1")){
                semester = "上学期";
            }else {
                semester = "下学期";
            }
            list1.setSchoolYearSemester(list1.getSchoolYear() + semester);
            list1.setPlannedTime(format.format(list1.getPlannedStartTime()) + "至" + format.format(list1.getPlannedEndTime()));
            if (list1.getDeclareState().equals("3") || list1.getDeclareState().equals("2")){
                LambdaQueryWrapper<SchoolLabClassYearRelation> lqw = new LambdaQueryWrapper<>();
                lqw.eq(SchoolLabClassYearRelation::getLabClassYearId,list1.getId());
                List<SchoolLabClassYearRelation> relations = schoolLabClassYearRelationService.list(lqw);
                list1.setSchoolLabClassYearRelationList(relations);
            }
        });
        return getDataTable(list);
    }

}
