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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yangtz.cs.liu.campus.domain.accessory.SchoolAccessory;
import yangtz.cs.liu.campus.domain.schoolRewardsPunishments.SchoolScDiscipline;
import yangtz.cs.liu.campus.mapper.accessory.AccessoryMapper;
import yangtz.cs.liu.campus.mapper.schoolRewardsPunishments.SchoolScDisciplineMapper;
import yangtz.cs.liu.campus.service.impl.schoolNewTeacherDzdn.SchoolXteachingAchievementsServiceImpl;
import yangtz.cs.liu.campus.service.schoolRewardsPunishments.ISchoolScDisciplineService;
import yangtz.cs.liu.campus.vo.schoolRewardsPunishments.SchoolScDisciplineVo;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 学生违纪Service业务层处理
 *
 * @author ruoyi
 * @date 2023-11-06
 */
@Service
public class SchoolScDisciplineServiceImpl extends ServiceImpl<SchoolScDisciplineMapper,SchoolScDiscipline> implements ISchoolScDisciplineService
{
    @Autowired
    private SchoolScDisciplineMapper schoolScDisciplineMapper;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;
    @Autowired
    private AccessoryMapper accessoryMapper;

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

    /**
     * 查询学生违纪
     *
     * @param id 学生违纪主键
     * @return 学生违纪
     */
    @Override
    public SchoolScDisciplineVo selectSchoolScDisciplineById(Long id)
    {
        SchoolScDiscipline schoolScDiscipline = schoolScDisciplineMapper.selectSchoolScDisciplineById(id);
        LambdaQueryWrapper<SchoolAccessory> wrapper = new LambdaQueryWrapper<SchoolAccessory>();
        wrapper.eq(SchoolAccessory::getAccessoryType,"学生违纪附件");
        wrapper.eq(SchoolAccessory::getBusinessId,id);
        List<SchoolAccessory> list = accessoryMapper.selectList(wrapper);
        //转vo
        SchoolScDisciplineVo schoolScDisciplineVo = new SchoolScDisciplineVo();
        BeanUtils.copyProperties(schoolScDiscipline,schoolScDisciplineVo);
        schoolScDisciplineVo.setSchoolAccessoryList(list);
        return schoolScDisciplineVo;
    }

    /**
     * 查询学生违纪列表
     *
     * @param schoolScDiscipline 学生违纪
     * @return 学生违纪
     */
    @Override
    public List<SchoolScDiscipline> selectSchoolScDisciplineList(SchoolScDiscipline schoolScDiscipline)
    {
        return schoolScDisciplineMapper.selectSchoolScDisciplineList(schoolScDiscipline);
    }

    /**
     * 查询学生违纪列表(查看已通过)
     *
     * @param schoolScDiscipline 学生违纪
     * @return 学生违纪
     */
    @Override
    public List<SchoolScDiscipline> selectSchoolScDisciplineListTg(SchoolScDiscipline schoolScDiscipline)
    {
        return schoolScDisciplineMapper.selectSchoolScDisciplineListTg(schoolScDiscipline);
    }

    /**
     * 新增学生违纪
     *
     * @param schoolScDisciplineVo 学生违纪
     * @return 结果
     */
    @Override
    @Transactional
    public int insertSchoolScDiscipline(SchoolScDisciplineVo schoolScDisciplineVo)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        schoolScDisciplineVo.setApplyId(user.getUserId());
        schoolScDisciplineVo.setApplyName(user.getUserName());
        schoolScDisciplineVo.setApplyTime(DateUtils.getNowDate());
        schoolScDisciplineVo.setCreateBy(user.getUserName());
        schoolScDisciplineVo.setCreateTime(DateUtils.getNowDate());
        int i = schoolScDisciplineMapper.insertSchoolScDiscipline(schoolScDisciplineVo);
        insertSchoolAccessory(schoolScDisciplineVo);
        return i;
    }

    /**
     * 新增学生违纪附件
     * @param schoolScDisciplineVo
     */
    private void insertSchoolAccessory(SchoolScDisciplineVo schoolScDisciplineVo) {
        List<SchoolAccessory> schoolAccessoryList = schoolScDisciplineVo.getSchoolAccessoryList();
        Long id = schoolScDisciplineVo.getId();
        if (StringUtils.isNotNull(schoolAccessoryList))
        {
            List<SchoolAccessory> list = new ArrayList<SchoolAccessory>();
            for (SchoolAccessory schoolAccessory : schoolAccessoryList)
            {
                schoolAccessory.setBusinessId(id);
                schoolAccessory.setModuleName("学生违纪");
                schoolAccessory.setAccessoryType("学生违纪附件");
                schoolAccessory.setCreateBy(SecurityUtils.getUsername());
                schoolAccessory.setCreateTime(DateUtils.getNowDate());
                list.add(schoolAccessory);
            }
            if (list.size() > 0)
            {
                schoolScDisciplineMapper.batchSchoolAccessory(list);
            }
        }
    }

    /**
     * 修改学生违纪
     *
     * @param schoolScDisciplineVo 学生违纪
     * @return 结果
     */
    @Override
    public int updateSchoolScDiscipline(SchoolScDisciplineVo schoolScDisciplineVo)
    {
        schoolScDisciplineVo.setUpdateBy(SecurityUtils.getUsername());
        schoolScDisciplineVo.setUpdateTime(DateUtils.getNowDate());
        //删除学生违纪附件
        schoolScDisciplineMapper.deleteSchoolAccessoryByBusinessId(schoolScDisciplineVo.getId());
        //新增学生违纪附件
        insertSchoolAccessory(schoolScDisciplineVo);
        return schoolScDisciplineMapper.updateSchoolScDiscipline(schoolScDisciplineVo);
    }

    /**
     * 批量删除学生违纪
     *
     * @param ids 需要删除的学生违纪主键
     * @return 结果
     */
    @Override
    public int deleteSchoolScDisciplineByIds(Long[] ids)
    {
        //删除学生违纪附件
        schoolScDisciplineMapper.deleteSchoolAccessoryByBusinessIds(ids);
        return schoolScDisciplineMapper.deleteSchoolScDisciplineByIds(ids);
    }

    /**
     * 删除学生违纪信息
     *
     * @param id 学生违纪主键
     * @return 结果
     */
    @Override
    public int deleteSchoolScDisciplineById(Long id)
    {
        //删除学生违纪附件
        schoolScDisciplineMapper.deleteSchoolAccessoryByBusinessId(id);
        return schoolScDisciplineMapper.deleteSchoolScDisciplineById(id);
    }

    /**
     * 获取最新三个年级
     * @return
     */
    @Override
    public List<Map<String, Object>> getGrade() {
        return schoolScDisciplineMapper.getGrade();
    }

    /**
     * 根据年级获取班级
     * @param gradeId
     * @return
     */
    @Override
    public List<Map<String, Object>> getClassList(Long gradeId) {
        return schoolScDisciplineMapper.getClassList(gradeId);
    }

    /**
     * 下载模板
     * @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
    public void checkImport(List<SchoolScDisciplineVo> list) {
        //检验是否为空
        if (StringUtils.isNull(list) || list.size() == 0) {
            throw new ServiceException("导入数据不能为空");
        }
        //查询学期字典键值
        List<SysDictData> semester = sysDictDataMapper.selectDictDataByType("semester_jsdzda");
        //查询年级字典键值
        List<SysDictData> gradeNames = sysDictDataMapper.selectDictDataByType("grade_da");
        //查询班级类型字典键值
        List<SysDictData> classType = sysDictDataMapper.selectDictDataByType("class_type_wj");
        //查询违纪类别字典键值
        List<SysDictData> wjlb = sysDictDataMapper.selectDictDataByType("violate_type");
        //查询违纪次数字典键值
        List<SysDictData> wjcs = sysDictDataMapper.selectDictDataByType("violate_num");
        //查询处分结果字典键值
        List<SysDictData> cfjg = sysDictDataMapper.selectDictDataByType("punish_result");
        // 准备记录日志数据
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        for (SchoolScDisciplineVo schoolScDisciplineVo : list) {
            if (StringUtils.isEmpty(schoolScDisciplineVo.getSchoolYear())){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、学年为空,请您重新输入! ");
            }else if (StringUtils.isEmpty(schoolScDisciplineVo.getSemester())){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、学期为空,请您重新输入! ");
            }else if (StringUtils.isEmpty(schoolScDisciplineVo.getGradeYear())){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、届别为空,请您重新输入! ");
            }else if (StringUtils.isEmpty(schoolScDisciplineVo.getGradeName())){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、年级为空,请您重新输入! ");
            }else if (StringUtils.isEmpty(schoolScDisciplineVo.getClassName())){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、班级为空,请您重新输入! ");
            }else if (StringUtils.isEmpty(schoolScDisciplineVo.getClassType())){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、班级类型为空,请您重新输入! ");
            }else if (StringUtils.isEmpty(schoolScDisciplineVo.getName())){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、姓名为空,请您重新输入! ");
            }else if (StringUtils.isEmpty(schoolScDisciplineVo.getIdCard())){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、身份证号为空,请您重新输入! ");
            }else if (StringUtils.isEmpty(schoolScDisciplineVo.getViolateType())){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、违纪行为为空,请您重新输入! ");
            }else if (StringUtils.isEmpty(schoolScDisciplineVo.getViolateNum())){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、违纪次数为空,请您重新输入! ");
            }else if (StringUtils.isEmpty(schoolScDisciplineVo.getPunishResult())){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、处分结果为空,请您重新输入! ");
            }else if (StringUtils.isNull(schoolScDisciplineVo.getPunishTime())){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、处分时间为空或输入错误,请您重新输入! ");
            }else if (schoolScDisciplineVo.getIdCard().length() != 18 && schoolScDisciplineVo.getIdCard().length() != 15){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、身份证号输入错误,请您重新输入! ");
            }else {

                //判断学年输入是否正确
                String schoolYear = schoolScDisciplineVo.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 (schoolScDisciplineVo.getSemester().equals(sysDictData.getDictLabel())){
                                semester1 = sysDictData.getDictValue();
                            }
                        }
                        if (StringUtils.isEmpty(semester1)){
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、学期输入错误,请您重新输入! ");
                        }else {
                            schoolScDisciplineVo.setSemester(semester1);
                            //判断届别输入是否正确
                            if (!schoolScDisciplineVo.getGradeYear().matches("\\d+")){
                                failureNum++;
                                failureMsg.append("<br/>" + failureNum + "、届别输入错误,请您重新输入! ");
                            }else {
                                //判断年级输入是否正确
                                String gradeName = "";
                                for (SysDictData sysDictData : gradeNames) {
                                    if (schoolScDisciplineVo.getGradeName().equals(sysDictData.getDictLabel())){
                                        gradeName = sysDictData.getDictValue();
                                    }
                                }

                                //判断班级类别输入是否正确
                                String classType1 = "";
                                for (SysDictData sysDictData : classType) {
                                    if (schoolScDisciplineVo.getClassType().equals(sysDictData.getDictLabel())){
                                        classType1 = sysDictData.getDictValue();
                                    }
                                }

                                String sex = "";
                                if (StringUtils.isNotEmpty(schoolScDisciplineVo.getSex())){
                                    if (schoolScDisciplineVo.getSex().equals("男") || schoolScDisciplineVo.getSex().equals("女")){
                                        sex = schoolScDisciplineVo.getSex();
                                    }
                                }

                                if (StringUtils.isEmpty(gradeName)){
                                    failureNum++;
                                    failureMsg.append("<br/>" + failureNum + "、年级输入错误,请您重新输入! ");
                                }else if (StringUtils.isEmpty(classType1)){
                                    failureNum++;
                                    failureMsg.append("<br/>" + failureNum + "、班级类型输入错误,请您重新输入! ");
                                }else if (StringUtils.isEmpty(sex) && StringUtils.isNotEmpty(schoolScDisciplineVo.getSex())){
                                    failureNum++;
                                    failureMsg.append("<br/>" + failureNum + "、性别输入错误,请您重新输入! ");
                                }else {
                                    schoolScDisciplineVo.setGradeName(gradeName);
                                    schoolScDisciplineVo.setClassType(classType1);
                                    schoolScDisciplineVo.setSex(sex);
                                    //判断身份证号输入是否正确
                                    String idCard = "";
                                    if(schoolScDisciplineVo.getIdCard().length() == 18){
                                        //校验前十七位是否为数字
                                        for (int i = 0; i < 17; i++) {
                                            if (!Character.isDigit(schoolScDisciplineVo.getIdCard().charAt(i))){
                                                failureNum++;
                                                failureMsg.append("<br/>" + failureNum + "、身份证号输入错误,请您重新输入! ");
                                                idCard += i;
                                                break;
                                            }
                                        }
                                    }
                                    if (StringUtils.isEmpty(idCard)){
//                                        //判断违纪类别输入是否正确
//                                        String wjlb1 = "";
//                                        for (SysDictData sysDictData : wjlb) {
//                                            if (schoolScDisciplineVo.getViolateType().equals(sysDictData.getDictLabel())){
//                                                wjlb1 = sysDictData.getDictValue();
//                                            }
//                                        }

                                        //判断违纪次数输入是否正确
                                        String wjcs1 = "";
                                        for (SysDictData sysDictData : wjcs) {
                                            if (schoolScDisciplineVo.getViolateNum().equals(sysDictData.getDictLabel())){
                                                wjcs1 = sysDictData.getDictValue();
                                            }
                                        }

                                        //判断处分结果输入是否正确
                                        String cfjg1 = "";
                                        for (SysDictData sysDictData : cfjg) {
                                            if (schoolScDisciplineVo.getPunishResult().equals(sysDictData.getDictLabel())){
                                                cfjg1 = sysDictData.getDictValue();
                                            }
                                        }

                                        if (StringUtils.isEmpty(wjcs1)){
                                            failureNum++;
                                            failureMsg.append("<br/>" + failureNum + "、违纪次数输入错误,请您重新输入! ");
                                        }else if (StringUtils.isEmpty(cfjg1)){
                                            failureNum++;
                                            failureMsg.append("<br/>" + failureNum + "、处分结果输入错误,请您重新输入! ");
                                        }else {
                                            schoolScDisciplineVo.setViolateNum(wjcs1);
                                            schoolScDisciplineVo.setPunishResult(cfjg1);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            schoolScDisciplineVo.setAuditState("2");
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共" + failureNum + "条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
    }

    /**
     * 导入数据
     * @param list
     * @return
     */
    @Override
    public String importData(List<SchoolScDisciplineVo> list) {
        StringBuilder successMsg = new StringBuilder();
        List<SchoolScDiscipline> schoolScDisciplineList = new ArrayList<>();
        for (SchoolScDisciplineVo schoolScDisciplineVo : list) {
            //转实体对象
            SchoolScDiscipline schoolScDiscipline = new SchoolScDiscipline();
            BeanUtils.copyProperties(schoolScDisciplineVo,schoolScDiscipline);
            schoolScDisciplineList.add(schoolScDiscipline);
        }
        boolean b = saveBatch(schoolScDisciplineList);
        if (!b){
            throw new ServiceException("导入失败");
        }
        successMsg.insert(0, "恭喜您，数据已导入成功！");
        return successMsg.toString();
    }
}
