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

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SchoolTeacher;
import com.ruoyi.common.core.domain.entity.SysDictData;
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 com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysDictDataMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yangtz.cs.liu.campus.domain.schoolNewTeacherDzdn.SchoolXteachingAchievements;
import yangtz.cs.liu.campus.mapper.schoolNewTeacherDzdn.SchoolXteachingAchievementsMapper;
import yangtz.cs.liu.campus.mapper.teacher.SchoolTeacherMapper;
import yangtz.cs.liu.campus.service.impl.schoolAnnualAssessment.SchoolAnnualAssessmentServiceImpl;
import yangtz.cs.liu.campus.service.schoolNewTeacherDzdn.ISchoolXteachingAchievementsService;
import yangtz.cs.liu.campus.vo.schoolNewTeacherDzdn.SchoolXteachingAchievementsVo;

import javax.servlet.http.HttpServletResponse;

/**
 * 教学成绩Service业务层处理
 *
 * @author ruoyi
 * @date 2023-12-06
 */
@Service
public class SchoolXteachingAchievementsServiceImpl extends ServiceImpl<SchoolXteachingAchievementsMapper,SchoolXteachingAchievements> implements ISchoolXteachingAchievementsService
{
    @Autowired
    private SchoolXteachingAchievementsMapper schoolXteachingAchievementsMapper;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;
    @Autowired
    private SchoolTeacherMapper schoolTeacherMapper;

    private Logger log = LoggerFactory.getLogger(SchoolXteachingAchievementsServiceImpl.class);

    /**
     * 查询教学成绩
     *
     * @param id 教学成绩主键
     * @return 教学成绩
     */
    @Override
    public SchoolXteachingAchievementsVo selectSchoolXteachingAchievementsById(Long id)
    {
        return schoolXteachingAchievementsMapper.selectSchoolXteachingAchievementsById(id);
    }

    /**
     * 查询教学成绩列表
     *
     * @param schoolXteachingAchievementsVo 教学成绩
     * @return 教学成绩
     */
    @Override
    public List<SchoolXteachingAchievementsVo> selectSchoolXteachingAchievementsList(SchoolXteachingAchievementsVo schoolXteachingAchievementsVo)
    {
        return schoolXteachingAchievementsMapper.selectSchoolXteachingAchievementsList(schoolXteachingAchievementsVo);
    }

    /**
     * 新增教学成绩
     *
     * @param schoolXteachingAchievements 教学成绩
     * @return 结果
     */
    @Override
    @Transactional
    public int insertSchoolXteachingAchievements(SchoolXteachingAchievements schoolXteachingAchievements)
    {
        //根据身份证号查询用户，是否存在
//        SchoolTeacher schoolTeacher = schoolTeacherMapper.selectTeacher(schoolXteachingAchievements.getIdCard());
//        if (StringUtils.isNotNull(schoolTeacher)){
//            schoolXteachingAchievements.setUserId(schoolTeacher.getId());
//        }else {
//            schoolXteachingAchievements.setUserId(null);
//        }
//        if (StringUtils.isNull(schoolTeacher)){
//            throw new ServiceException("用户不存在，请重新输入！");
//        } else if (!schoolTeacher.getTeacherName().contains(schoolXteachingAchievements.getUserName())){
//            throw new ServiceException("姓名和身份证姓名不匹配，请重新输入！");
//        }
        //判断班级是否正确
        String className = schoolXteachingAchievements.getClassName();
        //将所有中文逗号替换成英文逗号
        String newClassName = className.replaceAll("，", ",");
        String[] split = newClassName.split(",");
        for (int i = 0; i < split.length; i++) {
            if (!split[i].matches("\\d+")){
                throw new ServiceException("班级输入错误，请重新输入！");
            }
        }
        schoolXteachingAchievements.setClassName(newClassName);
        //判断考核分是否正确
        if (!schoolXteachingAchievements.getAssessmentScore().toString().matches("\\d+(\\.\\d+)?")){
            throw new ServiceException("考核分输入错误，请重新输入！");
        }
        schoolXteachingAchievements.setCreateBy(SecurityUtils.getUsername());
        schoolXteachingAchievements.setCreateTime(DateUtils.getNowDate());
        return schoolXteachingAchievementsMapper.insertSchoolXteachingAchievements(schoolXteachingAchievements);
    }

    /**
     * 修改教学成绩
     *
     * @param schoolXteachingAchievements 教学成绩
     * @return 结果
     */
    @Override
    @Transactional
    public int updateSchoolXteachingAchievements(SchoolXteachingAchievements schoolXteachingAchievements)
    {
        //根据身份证号查询用户，是否存在
//        SchoolTeacher schoolTeacher = schoolTeacherMapper.selectTeacher(schoolXteachingAchievements.getIdCard());
//        if (StringUtils.isNotNull(schoolTeacher)){
//            schoolXteachingAchievements.setUserId(schoolTeacher.getId());
//        }else {
//            schoolXteachingAchievements.setUserId(null);
//        }
//        if (StringUtils.isNull(schoolTeacher)){
//            throw new ServiceException("用户不存在，请重新输入！");
//        } else if (!schoolTeacher.getTeacherName().contains(schoolXteachingAchievements.getUserName())){
//            throw new ServiceException("姓名和身份证姓名不匹配，请重新输入！");
//        }
        //判断班级是否正确
        String className = schoolXteachingAchievements.getClassName();
        //将所有中文逗号替换成英文逗号
        String newClassName = className.replaceAll("，", ",");
        String[] split = newClassName.split(",");
        for (int i = 0; i < split.length; i++) {
            if (!split[i].matches("\\d+")){
                throw new ServiceException("班级输入错误，请重新输入！");
            }
        }
        schoolXteachingAchievements.setClassName(newClassName);
        //判断考核分是否正确
        if (!schoolXteachingAchievements.getAssessmentScore().toString().matches("\\d+(\\.\\d+)?")){
            throw new ServiceException("考核分输入错误，请重新输入！");
        }
        schoolXteachingAchievements.setUpdateBy(SecurityUtils.getUsername());
        schoolXteachingAchievements.setUpdateTime(DateUtils.getNowDate());
        return schoolXteachingAchievementsMapper.updateSchoolXteachingAchievements(schoolXteachingAchievements);
    }

    /**
     * 批量删除教学成绩
     *
     * @param ids 需要删除的教学成绩主键
     * @return 结果
     */
    @Override
    public int deleteSchoolXteachingAchievementsByIds(Long[] ids)
    {
        return schoolXteachingAchievementsMapper.deleteSchoolXteachingAchievementsByIds(ids);
    }

    /**
     * 删除教学成绩信息
     *
     * @param id 教学成绩主键
     * @return 结果
     */
    @Override
    public int deleteSchoolXteachingAchievementsById(Long id)
    {
        return schoolXteachingAchievementsMapper.deleteSchoolXteachingAchievementsById(id);
    }

    /**
     * 获取所有用户
     * @return
     */
    @Override
    public List<Map<String, Object>> getUserList(SysUser sysUser) {
        return schoolXteachingAchievementsMapper.getUserList(sysUser);
    }

    /**
     * 下载模板
     * @param response
     */
    @Override
    public void importTemplate(HttpServletResponse response) {
        // 以流的形式下载文件。
        try {
            //读取文件
            InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("file/教学成绩导入模板.xlsx");
            InputStream fis = new BufferedInputStream(resourceAsStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.setHeader("Content-Disposition", "attachment;filename="+java.net.URLEncoder.encode("教学成绩导入模板.xlsx", "utf-8"));
            //response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + buffer.length);
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException e) {
            log.info(e.getMessage());
        }
    }

    /**
     * 校验教学成绩数据
     * @param list
     */
    @Override
    @Transactional
    public void checkImport(List<SchoolXteachingAchievements> list) {
        //检验是否为空
        if (StringUtils.isNull(list) || list.size() == 0) {
            throw new ServiceException("导入数据不能为空");
        }
        //查询学期字典键值
        List<SysDictData> semester = sysDictDataMapper.selectDictDataByType("semester_jsdzda");
        //查询考试类型字典键值
        List<SysDictData> examType = sysDictDataMapper.selectDictDataByType("exam_typeda");
        //查询年级字典键值
        List<SysDictData> grade = sysDictDataMapper.selectDictDataByType("grade_da");
        //查询学科字典键值
        List<SysDictData> sub = sysDictDataMapper.selectDictDataByType("sub_dzdn");
        //查询班级类型字典键值
        List<SysDictData> type = sysDictDataMapper.selectDictDataByType("class_type");
        // 准备记录日志数据
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        for (SchoolXteachingAchievements schoolXteachingAchievements : list) {
            if (StringUtils.isNull(schoolXteachingAchievements.getSchoolYear())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、学年为空,请您重新输入! ");
            } else if (StringUtils.isEmpty(schoolXteachingAchievements.getSemester())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、学期为空,请您重新输入! ");
            } else if (StringUtils.isNull(schoolXteachingAchievements.getExamTime())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、考试时间为空或输入错误,请您重新输入! ");
            } else if (StringUtils.isEmpty(schoolXteachingAchievements.getExamType())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、考试类型为空,请您重新输入! ");
            } else if (StringUtils.isEmpty(schoolXteachingAchievements.getYear())){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、届别为空,请您重新输入! ");
            } else if (StringUtils.isEmpty(schoolXteachingAchievements.getGrade())){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、年级为空,请您重新输入! ");
            } else if (StringUtils.isEmpty(schoolXteachingAchievements.getUserName())){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、姓名为空,请您重新输入! ");
            } else if (StringUtils.isEmpty(schoolXteachingAchievements.getIdCard())){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、身份证号为空,请您重新输入! ");
            } else if (StringUtils.isEmpty(schoolXteachingAchievements.getSub())){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、学科为空,请您重新输入! ");
            } else if (StringUtils.isEmpty(schoolXteachingAchievements.getClassName())){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、班级为空,请您重新输入! ");
            } else if (StringUtils.isEmpty(schoolXteachingAchievements.getClassType())){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、班级类型为空,请您重新输入! ");
            } else if (StringUtils.isNull(schoolXteachingAchievements.getAssessmentScore())){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、考核分为空,请您重新输入! ");
            } else if (schoolXteachingAchievements.getIdCard().length() != 18 && schoolXteachingAchievements.getIdCard().length() != 15){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、身份证号输入错误,请您重新输入! ");
            } else {
                //判断学年输入是否正确
                String schoolYear = schoolXteachingAchievements.getSchoolYear();
                if (!schoolYear.contains("-")){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、学年输入格式错误,请您重新输入! ");
                }else {
                    String[] split = schoolYear.split("-");
                    if (split.length != 2){
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、学年输入格式错误,请您重新输入! ");
                    } else if (!(split[0].matches("\\d+") && split[1].matches("\\d+"))){
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、学年输入格式错误,请您重新输入! ");
                    }else {
                        //判断学期是否正确
                        String semester1 = "";
                        for (SysDictData sysDictData : semester) {
                            if (schoolXteachingAchievements.getSemester().equals(sysDictData.getDictLabel())){
                                semester1 = sysDictData.getDictValue();
                            }
                        }
                        if (StringUtils.isEmpty(semester1)){
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、学期输入错误,请您重新输入! ");
                        }else {
                            schoolXteachingAchievements.setSemester(semester1);

                            //判断考试类型是否正确
                            String examType1 = "";
                            for (SysDictData sysDictData : examType) {
                                if (schoolXteachingAchievements.getExamType().equals(sysDictData.getDictLabel())){
                                    examType1 = sysDictData.getDictValue();
                                }
                            }
                            if (StringUtils.isEmpty(examType1)){
                                failureNum++;
                                failureMsg.append("<br/>" + failureNum + "、考试类型输入错误,请您重新输入! ");
                            }else {
                                schoolXteachingAchievements.setExamType(examType1);

                                //判断届别是否正确
                                if (!schoolXteachingAchievements.getYear().matches("\\d+")){
                                    failureNum++;
                                    failureMsg.append("<br/>" + failureNum + "、届别输入错误,请您重新输入! ");
                                }else {
                                    //判断年级是否正确
                                    String grade1 = "";
                                    for (SysDictData sysDictData : grade) {
                                        if (schoolXteachingAchievements.getGrade().equals(sysDictData.getDictLabel())){
                                            grade1 = sysDictData.getDictValue();
                                        }
                                    }

                                    //判断学科是否正确
                                    String sub1 = "";
                                    for (SysDictData sysDictData : sub) {
                                        if (schoolXteachingAchievements.getSub().equals(sysDictData.getDictLabel())){
                                            sub1 = sysDictData.getDictValue();
                                        }
                                    }

                                    if (StringUtils.isEmpty(grade1)){
                                        failureNum++;
                                        failureMsg.append("<br/>" + failureNum + "、年级输入错误,请您重新输入! ");
                                    }else if (StringUtils.isEmpty(sub1)){
                                        failureNum++;
                                        failureMsg.append("<br/>" + failureNum + "、学科输入错误,请您重新输入! ");
                                    }else {
                                        schoolXteachingAchievements.setGrade(grade1);
                                        schoolXteachingAchievements.setSub(sub1);
                                        //判断班级是否正确
                                        String className = schoolXteachingAchievements.getClassName();
                                        //将所有中文逗号替换成英文逗号
                                        String newClassName = className.replaceAll("，", ",");
                                        String[] spl = newClassName.split(",");
                                        for (int i = 0; i < spl.length; i++) {
                                            if (!spl[i].matches("\\d+")){
                                                failureNum++;
                                                failureMsg.append("<br/>" + failureNum + "、班级输入错误,请您重新输入! ");
                                                break;
                                            }
                                        }
                                        schoolXteachingAchievements.setClassName(newClassName);

                                        //判断班级类型是否正确
                                        String classType1 = "";
                                        String classType = schoolXteachingAchievements.getClassType();
                                        //将所有中文逗号换成英文逗号
                                        String newClassType = classType.replaceAll("，", ",");
                                        String[] split1 = newClassType.split(",");
                                        for (String ctype : split1) {
                                            for (SysDictData sysDictData : type) {
                                                if (ctype.equals(sysDictData.getDictLabel())){
                                                    classType1 += ctype;
                                                }
                                            }
                                        }
                                        if (StringUtils.isEmpty(classType1)){
                                            failureNum++;
                                            failureMsg.append("<br/>" + failureNum + "、班级类型输入错误,请您重新输入! ");
                                        }else if (!schoolXteachingAchievements.getAssessmentScore().toString().matches("\\d+(\\.\\d+)?")){
                                                failureNum++;
                                                failureMsg.append("<br/>" + failureNum + "、考核分输入错误,请您重新输入! ");
                                        }else if(schoolXteachingAchievements.getIdCard().length() == 18){
                                            //校验前十七位是否为数字
                                            for (int i = 0; i < 17; i++) {
                                                if (!Character.isDigit(schoolXteachingAchievements.getIdCard().charAt(i))){
                                                    failureNum++;
                                                    failureMsg.append("<br/>" + failureNum + "、身份证号输入错误,请您重新输入! ");
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共" + failureNum + "条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
    }

    /**
     * 导入教学成绩数据
     * @param list
     * @return
     */
    @Override
    @Transactional
    public String importData(List<SchoolXteachingAchievements> list) {
        StringBuilder successMsg = new StringBuilder();
        //批量导入年度考核数据
        boolean b = saveBatch(list);
        if (!b){
            throw new ServiceException("导入失败");
        }
        successMsg.insert(0, "恭喜您，数据已导入成功！");
        return successMsg.toString();
    }

    /**
     * 查询本部门下所有教师id
     * @param deptId
     * @return
     */
    @Override
    public List<Long> getUserIdsByDeptId(Long deptId) {
        return schoolXteachingAchievementsMapper.getUserIdsByDeptId(deptId);
    }

    /**
     * 查询本部门下所有教师手机号
     * @param deptId
     * @return
     */
    @Override
    public List<String> getUserPhonesByDeptId(Long deptId) {
        return schoolXteachingAchievementsMapper.getUserPhonesByDeptId(deptId);
    }

    /**
     * 查询所有级部id
     * @return
     */
    @Override
    public List<Long> getJbDeptId() {
        return schoolXteachingAchievementsMapper.getJbDeptId();
    }

    /**
     * 查询所有科室id
     * @return
     */
    @Override
    public List<Long> getKsDeptId() {
        return schoolXteachingAchievementsMapper.getKsDeptId();
    }
}
