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

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
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.SysRole;
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.*;
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.schoolgrade.SchoolGradeMentor;

import yangtz.cs.liu.campus.service.schoolLab.ISchoolExperimentPlanService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import yangtz.cs.liu.campus.service.schoolLab.ISchoolTeacherLabApplyService;
import yangtz.cs.liu.campus.service.schoolgrade.ISchoolGradeMentorService;
import yangtz.cs.liu.campus.service.schoolgrade.ISchoolGradeService;
import yangtz.cs.liu.campus.vo.schoolLab.SchoolExperimentPlanVo;
import yangtz.cs.liu.campus.vo.schoolLab.SchoolTeacherLabApplyVo;


/**
 * 实验计划Controller
 *
 * @author ruoyi
 * @date 2023-08-29
 */
@RestController
@RequestMapping("/experimentPlan")
public class SchoolExperimentPlanController extends BaseController
{
    @Autowired
    private ISchoolExperimentPlanService schoolExperimentPlanService;
    @Autowired
    private ISchoolGradeService schoolGradeService;
    @Autowired
    private ISchoolTeacherLabApplyService schoolTeacherLabApplyService;
    @Autowired
    private ISchoolGradeService gradeService;
    @Autowired
    private ISchoolGradeMentorService schoolGradeMentorService;

    /**
     * 查询实验计划列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SchoolExperimentPlanVo schoolExperimentPlanVo)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //如果是管理员，查询全部列表
        if (user.isAdmin()){
            startPage();
            List<SchoolExperimentPlanVo> list = schoolExperimentPlanService.selectExperimentPlanListAdmin(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 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 -> {
            Object id = gradeList1.get("id");
            Long gradeId = Long.valueOf(String.valueOf(id));
            gradeIds.add(gradeId);
        });

        schoolExperimentPlanVo.setGradeIds(gradeIds);
        schoolExperimentPlanVo.setTeacherId(user.getUserId());

        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 getDataTable(list);
    }

    /**
     * 导出实验计划列表
     */
    @Log(title = "实验计划", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SchoolExperimentPlanVo schoolExperimentPlanVo)
    {
        List<SchoolExperimentPlanVo> list = schoolExperimentPlanService.selectSchoolExperimentPlanList(schoolExperimentPlanVo);
        ExcelUtil<SchoolExperimentPlanVo> util = new ExcelUtil<SchoolExperimentPlanVo>(SchoolExperimentPlanVo.class);
        util.exportExcel(response, list, "实验计划数据");
    }

    /**
     * 获取实验计划详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        SchoolExperimentPlanVo schoolExperimentPlanVo = schoolExperimentPlanService.selectSchoolExperimentPlanById(id);
        String semester = "";
        if (schoolExperimentPlanVo.getSemester().equals("1")){
            semester = "上学期";
        }else {
            semester = "下学期";
        }
        schoolExperimentPlanVo.setSchoolYearSemester(schoolExperimentPlanVo.getSchoolYear() + semester);
        schoolExperimentPlanVo.setPlannedTime(schoolExperimentPlanVo.getPlannedStartTime() + "至" + schoolExperimentPlanVo.getPlannedEndTime());
        return AjaxResult.success(schoolExperimentPlanVo);
    }

    /**
     * 新增实验计划
     */
    @Log(title = "实验计划", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody SchoolExperimentPlanVo schoolExperimentPlanVo)
    {
        return toAjax(schoolExperimentPlanService.insertSchoolExperimentPlan(schoolExperimentPlanVo));
    }

    /**
     * 修改实验计划
     */
    @Log(title = "实验计划", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody SchoolExperimentPlanVo schoolExperimentPlanVo)
    {
        return toAjax(schoolExperimentPlanService.updateSchoolExperimentPlan(schoolExperimentPlanVo));
    }

    /**
     * 删除实验计划
     */
    @Log(title = "实验计划", businessType = BusinessType.DELETE)
    @PostMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(schoolExperimentPlanService.deleteSchoolExperimentPlanByIds(ids));
    }

    /**
     * 查询级部下拉框
     */
    @GetMapping("/getGrade")
    public AjaxResult getGrade(){
        //获取最新学年
        int schoolYear = schoolGradeService.isNewSchoolYear();
        return AjaxResult.success(schoolExperimentPlanService.getGrade(schoolYear,null));
    }

    /**
     * 查询级部下拉框(搜索条件)
     */
    @GetMapping("/getGradeList")
    public AjaxResult getGradeList(){
        //获取最新学年
        int schoolYear = schoolGradeService.isNewSchoolYear();
        return AjaxResult.success(schoolExperimentPlanService.getGradeList(schoolYear));
    }

    /**
     * 根据级部查询对应班级
     */
    @GetMapping("/getClass/{gradeId}")
    public AjaxResult getSchoolClass(@PathVariable("gradeId") Long gradeId){
        return AjaxResult.success(schoolExperimentPlanService.getSchoolClass(gradeId));
    }

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

    /**
     * 级部-获取学科下拉框
     */
    @GetMapping("/getSub/{gradeId}")
    public AjaxResult getSub(@PathVariable("gradeId") Long gradeId){
        return AjaxResult.success(schoolExperimentPlanService.getSub(gradeId));
    }

    /**
     * 实验室管理-级部实验计划查看列表
     */
    @GetMapping("/getExperimentList")
    public TableDataInfo getExperimentList(SchoolExperimentPlanVo schoolExperimentPlanVo){
        startPage();
        return getDataTable(schoolExperimentPlanService.getExperimentList(schoolExperimentPlanVo));
    }

    /**
     * 领导-查看实验室完成情况列表
     */
    @GetMapping("/countExperiment")
    public TableDataInfo countExperiment(SchoolExperimentPlanVo schoolExperimentPlanVo){
        startPage();
        return getDataTable(schoolExperimentPlanService.countExperiment(schoolExperimentPlanVo));
    }

    /**
     * 查看班级完成详情
     */
    @GetMapping("/getClassDetails")
    public TableDataInfo getClassDetails(SchoolTeacherLabApplyVo schoolTeacherLabApplyVo){
        return getDataTable(schoolTeacherLabApplyService.getClassDetails(schoolTeacherLabApplyVo));
    }

    /**
     * 教师实验统计
     */
    @GetMapping("/getCountTeacher")
    public TableDataInfo getCountTeacher(SchoolTeacherLabApplyVo schoolTeacherLabApplyVo){
        startPage();
        return getDataTable(schoolTeacherLabApplyService.getCountTeacher(schoolTeacherLabApplyVo));
    }

    /**
     * 实验室管理-查看实验室完成情况列表
     */
    @GetMapping("/countExperimentLabAdmin")
    public TableDataInfo countExperimentAdmin(SchoolExperimentPlanVo schoolExperimentPlanVo){
        startPage();
        return getDataTable(schoolExperimentPlanService.countExperimentAdmin(schoolExperimentPlanVo));
    }

    /**
     * 实验室管理员-实验记录列表
     */
    @GetMapping("/getExperimentRecord")
    public TableDataInfo getExperimentRecord(SchoolTeacherLabApplyVo schoolTeacherLabApplyVo){
        schoolTeacherLabApplyVo.setApplyState("1");
        startPage();
        return getDataTable(schoolTeacherLabApplyService.getTeacherLabApplyList(schoolTeacherLabApplyVo));
    }

    /**
     * 级部-实验室完成情况明细
     */
    @GetMapping("/gradeCountExperiment")
    public TableDataInfo gradeCountExperiment(SchoolExperimentPlanVo schoolExperimentPlanVo){
        //获取登录用户
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //管理员角色返回全部数据
        if (user.isAdmin()){
            startPage();
            List<Map<String, Object>> list = schoolExperimentPlanService.countExperimentListAdmin(schoolExperimentPlanVo);
            list.forEach(list1 -> {
                //总班级数
                int totalClass = Integer.parseInt(list1.get("totalClass").toString());
                //已完成班级数
                int completeClass = Integer.parseInt(list1.get("completeClass").toString());
                //计算完成比例
                if (totalClass == 0){
                    list1.put("ratio","0%");
                }else {
                    //计算完成比例
                    double totalClass1 = totalClass * 100.0;
                    double completeClass2 = completeClass * 100.0;
                    NumberFormat percentInstance = NumberFormat.getPercentInstance();
                    // 设置保留几位小数，这里设置的是保留两位小数
                    percentInstance.setMinimumFractionDigits(0);
                    String percent = percentInstance.format(completeClass2 / totalClass1);
                    list1.put("ratio",percent);
                }
                String semester = "";
                if (list1.get("semester").equals("1")){
                    semester = "上学期";
                }else {
                    semester = "下学期";
                }
                list1.put("schoolYearSemester",list1.get("schoolYear") + semester);
            });
            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 -> {
            Object id = gradeList1.get("id");
            Long gradeId = Long.valueOf(String.valueOf(id));
            gradeIds.add(gradeId);
        });

        schoolExperimentPlanVo.setGradeIds(gradeIds);
        schoolExperimentPlanVo.setTeacherId(user.getUserId());
        startPage();
        List<Map<String, Object>> list = schoolExperimentPlanService.gradeCountExperiment(schoolExperimentPlanVo);

        list.forEach(list1 -> {
            //总班级数
            int totalClass = Integer.parseInt(list1.get("totalClass").toString());
            //已完成班级数
            int completeClass = Integer.parseInt(list1.get("completeClass").toString());
            //计算完成比例
            if (totalClass == 0){
                list1.put("ratio","0%");
            }else {
                //计算完成比例
                double totalClass1 = totalClass * 100.0;
                double completeClass2 = completeClass * 100.0;
                NumberFormat percentInstance = NumberFormat.getPercentInstance();
                // 设置保留几位小数，这里设置的是保留两位小数
                percentInstance.setMinimumFractionDigits(0);
                String percent = percentInstance.format(completeClass2 / totalClass1);
                list1.put("ratio",percent);
            }
            String semester = "";
            if (list1.get("semester").equals("1")){
                semester = "上学期";
            }else {
                semester = "下学期";
            }
            list1.put("schoolYearSemester",list1.get("schoolYear") + semester);
        });
        return getDataTable(list);
    }

    /**
     * 级部-班级完成情况明细
     */
    @GetMapping("/gradeCountClass")
    public TableDataInfo gradeCountClass(SchoolTeacherLabApplyVo schoolTeacherLabApplyVo){
        //获取登录用户
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //管理员角色返回全部数据
        if (user.isAdmin()){
            startPage();
            List<Map<String, Object>> list = schoolTeacherLabApplyService.gradeCountClassListAdmin(schoolTeacherLabApplyVo);
            list.forEach(list1 -> {
                //计划实验数
                int jhsys = Integer.parseInt(list1.get("jhsys").toString());
                //已完成实验数
                int ywcsys = Integer.parseInt(list1.get("ywcsys").toString());
                //计算完成比例
                if (jhsys == 0){
                    list1.put("ratio","0%");
                }else {
                    double jhsys1 = jhsys * 100.0;
                    double ywcsys1 = ywcsys * 100.0;
                    NumberFormat percentInstance = NumberFormat.getPercentInstance();
                    // 设置保留几位小数，这里设置的是保留两位小数
                    percentInstance.setMinimumFractionDigits(0);
                    String percent = percentInstance.format(ywcsys1 / jhsys1);
                    list1.put("ratio",percent);
                }
                String semester = "";
                if (list1.get("semester").equals("1")){
                    semester = "上学期";
                }else {
                    semester = "下学期";
                }
                list1.put("schoolYearSemester",list1.get("schoolYear") + semester);
            });
            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 -> {
            Object id = gradeList1.get("id");
            Long gradeId = Long.valueOf(String.valueOf(id));
            gradeIds.add(gradeId);
        });

        schoolTeacherLabApplyVo.setGradeIds(gradeIds);
        schoolTeacherLabApplyVo.setTeacherId(user.getUserId());
        startPage();
        List<Map<String, Object>> list = schoolTeacherLabApplyService.gradeCountClass(schoolTeacherLabApplyVo);
        list.forEach(list1 -> {
            //计划实验数
            int jhsys = Integer.parseInt(list1.get("jhsys").toString());
            //已完成实验数
            int ywcsys = Integer.parseInt(list1.get("ywcsys").toString());
            //计算完成比例
            if (jhsys == 0){
                list1.put("ratio","0%");
            }else {
                double jhsys1 = jhsys * 100.0;
                double ywcsys1 = ywcsys * 100.0;
                NumberFormat percentInstance = NumberFormat.getPercentInstance();
                // 设置保留几位小数，这里设置的是保留两位小数
                percentInstance.setMinimumFractionDigits(0);
                String percent = percentInstance.format(ywcsys1 / jhsys1);
                list1.put("ratio",percent);
            }
            String semester = "";
            if (list1.get("semester").equals("1")){
                semester = "上学期";
            }else {
                semester = "下学期";
            }
            list1.put("schoolYearSemester",list1.get("schoolYear") + semester);
        });

        return getDataTable(list);
    }

    /**
     * 级部-班级完成情况明细-查看班级完成情况详情
     */
    @GetMapping("/getGradeClassDetails")
    public TableDataInfo getGradeClassDetails(SchoolTeacherLabApplyVo schoolTeacherLabApplyVo){
        //查询完成的班级实验信息
        schoolTeacherLabApplyVo.setState("1");
        return getDataTable(schoolTeacherLabApplyService.getGradeClassDetails(schoolTeacherLabApplyVo));
    }
}
