package yangtz.cs.liu.campus.service.impl.schoolLab;

import com.ruoyi.framework.util.UserInfoUtil;
import com.ruoyi.system.mapper.SysUserMapper;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Map;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import yangtz.cs.liu.campus.domain.schoolLab.SchoolExperimentPlanClass;
import yangtz.cs.liu.campus.domain.schoolgrade.SchoolGrade;
import yangtz.cs.liu.campus.domain.schoolgrade.SchoolGradeMentor;
import yangtz.cs.liu.campus.mapper.schoolLab.SchoolExperimentPlanMapper;
import yangtz.cs.liu.campus.domain.schoolLab.SchoolExperimentPlan;
import yangtz.cs.liu.campus.mapper.schoolLab.SchoolLabMapper;
import yangtz.cs.liu.campus.mapper.schoolgrade.SchoolGradeMentorMapper;
import yangtz.cs.liu.campus.service.schoolLab.ISchoolExperimentPlanService;
import yangtz.cs.liu.campus.service.schoolgrade.ISchoolGradeService;
import yangtz.cs.liu.campus.vo.schoolLab.SchoolExperimentPlanVo;

/**
 * 实验计划Service业务层处理
 *
 * @author ruoyi
 * @date 2023-08-29
 */
@Service
public class SchoolExperimentPlanServiceImpl extends ServiceImpl<SchoolExperimentPlanMapper, SchoolExperimentPlan> implements ISchoolExperimentPlanService
{
    @Autowired
    private SchoolExperimentPlanMapper schoolExperimentPlanMapper;
    @Autowired
    private SchoolLabMapper schoolLabMapper;
    @Autowired
    private SchoolGradeMentorMapper schoolGradeMentorMapper;
    @Autowired
    UserInfoUtil userInfoUtil;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private ISchoolGradeService schoolGradeService;
    /**
     * 查询实验计划
     *
     * @param id 实验计划主键
     * @return 实验计划
     */
    @Override
    public SchoolExperimentPlanVo selectSchoolExperimentPlanById(Long id)
    {
        return schoolExperimentPlanMapper.selectSchoolExperimentPlanById(id);
    }

    /**
     * 查询实验计划列表
     *
     * @param schoolExperimentPlanVo 实验计划
     * @return 实验计划
     */
    @Override
    public List<SchoolExperimentPlanVo> selectSchoolExperimentPlanList(SchoolExperimentPlanVo schoolExperimentPlanVo)
    {
        return schoolExperimentPlanMapper.selectSchoolExperimentPlanList(schoolExperimentPlanVo);
    }

    /**
     * 查询实验计划列表(管理员)
     *
     * @param schoolExperimentPlanVo 实验计划
     * @return 实验计划
     */
    @Override
    public List<SchoolExperimentPlanVo> selectExperimentPlanListAdmin(SchoolExperimentPlanVo schoolExperimentPlanVo)
    {
        return schoolExperimentPlanMapper.selectExperimentPlanListAdmin(schoolExperimentPlanVo);
    }

    /**
     * 获取计划下拉列表
     * @param schoolExperimentPlanVo
     * @return
     */
    @Override
    public List<Map<String, String>> selectNameByVo(SchoolExperimentPlanVo schoolExperimentPlanVo) {
        //判斷當前老師所在的级部
        Long userId = userInfoUtil.getMpLoginUser().getUserId();
        Long gradeId = schoolGradeService.getGradeId(userId);
        schoolExperimentPlanVo.setGradeId(gradeId);
        return schoolExperimentPlanMapper.selectNameByVo(schoolExperimentPlanVo);
    }

    /**
     * 新增实验计划
     *
     * @param schoolExperimentPlanVo 实验计划
     * @return 结果
     */
    @Transactional
    @Override
    public int insertSchoolExperimentPlan(SchoolExperimentPlanVo schoolExperimentPlanVo)
    {
        if (StringUtils.isNull(schoolExperimentPlanVo.getGradeId())){
            throw new ServiceException("级部不能为空");
        }
        schoolExperimentPlanVo.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserName());
        schoolExperimentPlanVo.setCreateTime(DateUtils.getNowDate());
        int rows = schoolExperimentPlanMapper.insertSchoolExperimentPlan(schoolExperimentPlanVo);
        insertSchoolExperimentPlanClass(schoolExperimentPlanVo);
        return rows;
    }

    /**
     * 修改实验计划
     *
     * @param schoolExperimentPlanVo 实验计划
     * @return 结果
     */
    @Transactional
    @Override
    public int updateSchoolExperimentPlan(SchoolExperimentPlanVo schoolExperimentPlanVo)
    {
        schoolExperimentPlanVo.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
        schoolExperimentPlanVo.setUpdateTime(DateUtils.getNowDate());
        SchoolExperimentPlan schoolExperimentPlan = new SchoolExperimentPlan();
        BeanUtils.copyProperties(schoolExperimentPlanVo,schoolExperimentPlan);
        schoolExperimentPlanMapper.deleteSchoolExperimentPlanClassByExperimentPlanId(schoolExperimentPlanVo.getId());
        insertSchoolExperimentPlanClass(schoolExperimentPlanVo);
        return schoolExperimentPlanMapper.updateById(schoolExperimentPlan);
    }

    /**
     * 批量删除实验计划
     *
     * @param ids 需要删除的实验计划主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteSchoolExperimentPlanByIds(Long[] ids)
    {
        //判断实验计划是否已预约，已预约的不可删除
        LambdaQueryWrapper<SchoolExperimentPlan> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SchoolExperimentPlan::getId,ids);
        List<SchoolExperimentPlan> schoolExperimentPlans = schoolExperimentPlanMapper.selectList(wrapper);
        schoolExperimentPlans.forEach(schoolExperimentPlan -> {
            if (schoolExperimentPlan.getIsAppointment().equals("1")){
                throw new ServiceException("实验计划已预约，不可删除");
            }
        });
        schoolExperimentPlanMapper.deleteSchoolExperimentPlanClassByExperimentPlanIds(ids);
        return schoolExperimentPlanMapper.deleteSchoolExperimentPlanByIds(ids);
    }

    /**
     * 删除实验计划信息
     *
     * @param id 实验计划主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteSchoolExperimentPlanById(Long id)
    {
        schoolExperimentPlanMapper.deleteSchoolExperimentPlanClassByExperimentPlanId(id);
        return schoolExperimentPlanMapper.deleteSchoolExperimentPlanById(id);
    }

    /**
     * 新增实验计划与班级关系信息
     *
     * @param schoolExperimentPlanVo 实验计划对象
     */
    public void insertSchoolExperimentPlanClass(SchoolExperimentPlanVo schoolExperimentPlanVo)
    {
        List<SchoolExperimentPlanClass> schoolExperimentPlanClassList = schoolExperimentPlanVo.getSchoolExperimentPlanClassList();
        if (StringUtils.isNull(schoolExperimentPlanClassList) || schoolExperimentPlanClassList.size() == 0){
            throw new ServiceException("实验班级不能为空");
        }
        Long id = schoolExperimentPlanVo.getId();
        List<SchoolExperimentPlanClass> list = new ArrayList<SchoolExperimentPlanClass>();
        for (SchoolExperimentPlanClass schoolExperimentPlanClass : schoolExperimentPlanClassList)
        {
            schoolExperimentPlanClass.setExperimentPlanId(id);
            list.add(schoolExperimentPlanClass);
        }
        if (list.size() > 0)
        {
            schoolExperimentPlanMapper.batchSchoolExperimentPlanClass(list);
        }
    }

    /**
     * 查询级部
     * @param schoolYear
     * @return
     */
    @Override
    public List<Map<String, Object>> getGrade(int schoolYear,Long userId) {
        SysUser user = null;
        //获取当前登录用户
        if(null == userId){
             user = SecurityUtils.getLoginUser().getUser();
        }else {
            user = sysUserMapper.selectUserById(userId);
        }
        //管理员级部
        if(1L == user.getUserId()){
            List<Map<String, Object>> gradeList = schoolExperimentPlanMapper.getGrade(schoolYear,null);
            if(StringUtils.isNull(gradeList) || gradeList.size() == 0){
                throw new ServiceException("当前学年为" + schoolYear + "学年，该学年没有级部信息");
            }
            return gradeList;
        }
        //教师级部
        List<Map<String, Object>> gradeList = schoolExperimentPlanMapper.getGrade(schoolYear,user.getUserId());
        if (StringUtils.isNull(gradeList) || gradeList.size() == 0) {
            throw new ServiceException("当前学年为" + schoolYear + "学年，该学年没有您所在的级部信息");
        }
        return gradeList;
    }

    /**
     * 查询级部（搜索条件）
     * @param schoolYear
     * @return
     */
    @Override
    public List<Map<String, Object>> getGradeList(int schoolYear) {
        List<Map<String, Object>> gradeList = schoolExperimentPlanMapper.getGrade(schoolYear,null);
        if(StringUtils.isNull(gradeList) || gradeList.size() == 0){
            throw new ServiceException("当前学年为" + schoolYear + "学年，该学年没有级部信息");
        }
        return gradeList;
    }

    /**
     * 根据级部查询对应班级
     * @param gradeId
     * @return
     */
    @Override
    public List<Map<String, Object>> getSchoolClass(Long gradeId) {
        List<Map<String, Object>> schoolClass = schoolExperimentPlanMapper.getSchoolClass(gradeId);
        if (StringUtils.isNull(schoolClass) || schoolClass.size() == 0) {
            throw new ServiceException("该级部还未有班级");
        }
        return schoolClass;
    }

    /**
     * 级部-获取学科下拉框
     * @return
     */
    @Override
    public List<Map<String, String>> getSub(Long gradeId) {
        List<Map<String, String>> list = new ArrayList<>();
        //获取当前登录用户
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if(user.isAdmin()){
            return schoolLabMapper.getSubAll();
        }
        LambdaQueryWrapper<SchoolGradeMentor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SchoolGradeMentor::getGradeId,gradeId)
                .eq(SchoolGradeMentor::getTeacherId,user.getUserId());
        SchoolGradeMentor schoolGradeMentor = schoolGradeMentorMapper.selectOne(wrapper);
        //无学科组返回提示
        if (StringUtils.isBlank(schoolGradeMentor.getSubGroup())){
            throw new ServiceException("您还未加入学科组！");
        }
        if (schoolGradeMentor.getSubGroup().equals("1")){
            list.add(schoolLabMapper.getSub("1"));
        }else if (schoolGradeMentor.getSubGroup().equals("2")){
            list.add(schoolLabMapper.getSub("2"));
        }else if (schoolGradeMentor.getSubGroup().equals("3")){
            list.add(schoolLabMapper.getSub("3"));
        }
        return list;
    }

    /**
     * 实验室管理-级部实验计划查看列表
     * @param schoolExperimentPlanVo
     * @return
     */
    @Override
    public List<SchoolExperimentPlanVo> getExperimentList(SchoolExperimentPlanVo schoolExperimentPlanVo) {
        //获取当前登录用户
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //获取用户角色集合
        List<SysRole> roles = user.getRoles();
        if (user.isAdmin()){
            List<SchoolExperimentPlanVo> list = schoolExperimentPlanMapper.getExperimentList(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 list;
        }
        List<String> labSubs = new ArrayList<>();
        for (SysRole role : roles) {
            if (role.getRoleKey().equals("admin")){
                List<SchoolExperimentPlanVo> list = schoolExperimentPlanMapper.getExperimentList(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 list;
            }
            switch (role.getRoleKey()){
                case "phy_lab_admin":
                    labSubs.add("1");
                    break;
                case "che_lab_admin":
                    labSubs.add("2");
                    break;
                case "bio_lab_admin":
                    labSubs.add("3");
                    break;
                default:break;
            }
        }
        if (labSubs.size() > 0){
            schoolExperimentPlanVo.setSubs(labSubs);
        }
        List<SchoolExperimentPlanVo> list = schoolExperimentPlanMapper.getExperimentList(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 list;
    }

    /**
     * 领导-查看实验室完成情况列表
     * @param schoolExperimentPlanVo
     * @return
     */
    @Override
    public List<Map<String, Object>> countExperiment(SchoolExperimentPlanVo schoolExperimentPlanVo) {
        List<Map<String, Object>> list = schoolExperimentPlanMapper.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 list;
    }

    /**
     * 实验室管理-查看实验室完成情况列表
     * @param schoolExperimentPlanVo
     * @return
     */
    @Override
    public List<Map<String, Object>> countExperimentAdmin(SchoolExperimentPlanVo schoolExperimentPlanVo) {
        //获取登录用户
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //获取用户角色集合
        List<SysRole> roles = user.getRoles();
        //管理员角色返回全部数据
        if (user.isAdmin()){
            List<Map<String, Object>> list = schoolExperimentPlanMapper.countExperiment(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 list;
        }
        List<String> labSubs = new ArrayList<>();
        //根据用户角色返回对应数据
        for (SysRole role : roles) {
            if (role.getRoleKey().equals("admin")){
                List<Map<String, Object>> list = schoolExperimentPlanMapper.countExperiment(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 list;
            }
            switch (role.getRoleKey()){
                case "phy_lab_admin":
                    labSubs.add("1");
                    break;
                case "che_lab_admin":
                    labSubs.add("2");
                    break;
                case "bio_lab_admin":
                    labSubs.add("3");
                    break;
                default:break;
            }

        }
        if (labSubs.size() > 0){
            schoolExperimentPlanVo.setSubs(labSubs);
        }
        List<Map<String, Object>> list = schoolExperimentPlanMapper.countExperiment(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 list;
    }

    /**
     * 级部-实验室完成情况明细
     * @param schoolExperimentPlanVo
     * @return
     */
    @Override
    public List<Map<String, Object>> gradeCountExperiment(SchoolExperimentPlanVo schoolExperimentPlanVo) {
        return schoolExperimentPlanMapper.countExperiment(schoolExperimentPlanVo);
    }

    /**
     * 实验室完成情况明细(管理员)
     * @param schoolExperimentPlanVo
     * @return
     */
    @Override
    public List<Map<String, Object>> countExperimentListAdmin(SchoolExperimentPlanVo schoolExperimentPlanVo) {
        return schoolExperimentPlanMapper.countExperimentListAdmin(schoolExperimentPlanVo);
    }
}
