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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import yangtz.cs.liu.campus.domain.schoolClass.SchoolClass;
import yangtz.cs.liu.campus.domain.schoolexam.SchoolExam;
import yangtz.cs.liu.campus.domain.schoolexam.SchoolExamDetail;
import yangtz.cs.liu.campus.domain.schoolgrade.SchoolGrade;
import yangtz.cs.liu.campus.mapper.schoolClass.SchoolClassMapper;
import yangtz.cs.liu.campus.mapper.schoolexam.SchoolExamDetailMapper;
import yangtz.cs.liu.campus.mapper.schoolexam.SchoolExamMapper;
import yangtz.cs.liu.campus.mapper.schoolgrade.SchoolGradeMapper;
import yangtz.cs.liu.campus.service.schoolexam.ISchoolExamService;

import javax.validation.constraints.NotNull;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


import static cn.hutool.core.util.ObjectUtil.isNotNull;
import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNull;
import static com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank;

/**
 * 学校考试信息Service业务层处理
 *
 * @author ruoyi
 * @date 2022-09-29
 */
@Service
public class SchoolExamServiceImpl extends ServiceImpl<SchoolExamMapper, SchoolExam> implements ISchoolExamService {
    @Autowired
    private SchoolExamMapper schoolExamMapper;
    @Autowired
    private SchoolExamDetailMapper schoolExamDetailMapper;

    @Autowired
    private SchoolClassMapper schoolClassMapper;

    private String[] value = {"一", "二", "三", "四", "五", "六", "七", "八", "九"};

    @Override
    public List<SchoolExam> queryList(SchoolExam schoolExam) {
        LambdaQueryWrapper<SchoolExam> lqw = new LambdaQueryWrapper<>();
        lqw
                .like(isNotBlank(schoolExam.getExamName()), SchoolExam::getExamName, schoolExam.getExamName())
                .apply(isNotNull(schoolExam.getParams().get("beginTime")),
                        "date_format(exam_time,'%Y-%m-%d') >= date_format('" + schoolExam.getParams().get("beginTime") + "','%Y-%m-%d') ")
                .apply(isNotNull(schoolExam.getParams().get("endTime")),
                        "date_format(exam_time,'%Y-%m-%d') <= date_format('" + schoolExam.getParams().get("endTime") + "','%Y-%m-%d') ")
                .eq(isNotNull(schoolExam.getClassId()), SchoolExam::getClassId, schoolExam.getClassId())
                .orderByDesc(SchoolExam::getExamTime)
        ;
        List<SchoolExam> list = schoolExamMapper.selectList(lqw);
        return list;
    }

    @Override
    public boolean saveNew(SchoolExam schoolExam) {
        int classValue = Math.toIntExact(schoolExam.getClassValue());
        int gradeValue = Math.toIntExact(schoolExam.getGradeValue());
        schoolExam.setGradeName(value[gradeValue] + "年级");
        schoolExam.setClassName(value[classValue] + "班");

        return (schoolExamMapper.insert(schoolExam) > 0);
    }

    @Override
    public boolean updateByIdNew(SchoolExam schoolExam) {
        int classValue = Math.toIntExact(schoolExam.getClassValue());
        int gradeValue = Math.toIntExact(schoolExam.getGradeValue());
        schoolExam.setGradeName(value[gradeValue] + "年级");
        schoolExam.setClassName(value[classValue] + "班");
        return (schoolExamMapper.updateById(schoolExam) > 0);
    }

//    @Override
//    public void removeAll(List<Long> ids) {
//        LambdaQueryWrapper<SchoolExamDetail> lqw = new LambdaQueryWrapper<>();
//        lqw.in(SchoolExamDetail::getExamId, ids);
//        schoolExamDetailMapper.delete(lqw);
//    }

    @Override
    public String importExamDetail(List<SchoolExam> list) {
        // 准备记录日志数据
        int successNum = 0;
        StringBuilder successMsg = new StringBuilder();
        for (SchoolExam schoolExam : list) {
            try {
                schoolExamMapper.insert(schoolExam);
                successNum++;
                successMsg.append("<br/>" + successNum + "数据" + " 导入成功");
            } catch (Exception e) {
                throw new ServiceException("导入失败");
            }
        }
        successMsg.insert(0, "恭喜您，数据已导入成功！共有 " + successNum + " 条，数据如下：");
        return successMsg.toString();
    }

    @Override
    public void check(List<SchoolExam> list) {
        //是否为空
        if (StringUtils.isNull(list) || list.size() == 0) {
            throw new ServiceException("导入数据不能为空");
        }
        //记录日志数据
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        for (SchoolExam schoolExam : list) {
            if (StringUtils.isNull(schoolExam.getGradeValue())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、年级为空，请你重新输入！");
            } else if (StringUtils.isNull(schoolExam.getClassValue())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、班级为空，请你重新输入！");
            } else if (StringUtils.isNull(schoolExam.getExamTime())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、考试时间为空，请您重新输入！");
            } else if (StringUtils.isNull(schoolExam.getExamName())) {
                failureNum++;
                failureMsg.append("<br/" + failureNum + "、考试名称为空，请你重新输入");
            } else if (isNotNull(schoolExam.getExamTime())) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Date schoolRecipesDate = schoolExam.getExamTime();
                    sdf.format(schoolRecipesDate);
                } catch (Exception e) {
                    throw new ServiceException("格式不对，请检查日期格式");
                }
            }
            LambdaQueryWrapper<SchoolClass> lqw = new LambdaQueryWrapper<>();
            lqw
                    .eq(SchoolClass::getSchoolYear, schoolExam.getSchoolYear())
                    .eq(SchoolClass::getGradeValue, schoolExam.getGradeValue())
                    .eq(SchoolClass::getClassValue, schoolExam.getClassValue());
            SchoolClass schoolClass = schoolClassMapper.selectOne(lqw);
            if (isNull(schoolClass)) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、班级不存在,请您重新输入! ");
            } else {
                schoolExam.setClassId(schoolClass.getId());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共" + failureNum + "条数据格式不正确，错误如下：");
            throw new BaseException(failureMsg.toString());
        }
    }


    /**
     * 公众号：家长获取孩子所有考试成绩
     *
     * @param schoolExam
     * @return
     */
    @Override
    public List<SchoolExam> getChildExam(Long studentId,SchoolExam schoolExam) {
        return schoolExamMapper.getChildExam(studentId,schoolExam);
    }
}
