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

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysDictData;
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 yangtz.cs.liu.campus.domain.schoolAnnualAssessment.SchoolAnnualAssessment;
import yangtz.cs.liu.campus.mapper.schoolAnnualAssessment.SchoolAnnualAssessmentMapper;
import yangtz.cs.liu.campus.service.schoolAnnualAssessment.ISchoolAnnualAssessmentService;
import yangtz.cs.liu.campus.vo.schoolAnnualAssessment.SchoolAnnualAssessmentVo;

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

/**
 * 年度考核Service业务层处理
 *
 * @author ruoyi
 * @date 2023-12-05
 */
@Service
public class SchoolAnnualAssessmentServiceImpl extends ServiceImpl<SchoolAnnualAssessmentMapper,SchoolAnnualAssessment> implements ISchoolAnnualAssessmentService {

    @Autowired
    private SchoolAnnualAssessmentMapper schoolAnnualAssessmentMapper;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;

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

    /**
     * 查询年度考核
     *
     * @param id 年度考核主键
     * @return 年度考核
     */
    @Override
    public SchoolAnnualAssessment selectSchoolAnnualAssessmentById(Long id)
    {
        return schoolAnnualAssessmentMapper.selectSchoolAnnualAssessmentById(id);
    }

    /**
     * 查询年度考核列表
     *
     * @param schoolAnnualAssessmentVo 年度考核
     * @return 年度考核
     */
    @Override
    public List<SchoolAnnualAssessment> selectSchoolAnnualAssessmentList(SchoolAnnualAssessmentVo schoolAnnualAssessmentVo)
    {
        return schoolAnnualAssessmentMapper.selectSchoolAnnualAssessmentList(schoolAnnualAssessmentVo);
    }

    /**
     * 新增年度考核
     *
     * @param schoolAnnualAssessment 年度考核
     * @return 结果
     */
    @Override
    public int insertSchoolAnnualAssessment(SchoolAnnualAssessment schoolAnnualAssessment)
    {
        schoolAnnualAssessment.setCreateBy(SecurityUtils.getUsername());
        schoolAnnualAssessment.setCreateTime(DateUtils.getNowDate());
        return schoolAnnualAssessmentMapper.insertSchoolAnnualAssessment(schoolAnnualAssessment);
    }

    /**
     * 修改年度考核
     *
     * @param schoolAnnualAssessment 年度考核
     * @return 结果
     */
    @Override
    public int updateSchoolAnnualAssessment(SchoolAnnualAssessment schoolAnnualAssessment)
    {
        schoolAnnualAssessment.setUpdateBy(SecurityUtils.getUsername());
        schoolAnnualAssessment.setUpdateTime(DateUtils.getNowDate());
        return schoolAnnualAssessmentMapper.updateSchoolAnnualAssessment(schoolAnnualAssessment);
    }

    /**
     * 批量删除年度考核
     *
     * @param ids 需要删除的年度考核主键
     * @return 结果
     */
    @Override
    public int deleteSchoolAnnualAssessmentByIds(Long[] ids)
    {
        return schoolAnnualAssessmentMapper.deleteSchoolAnnualAssessmentByIds(ids);
    }

    /**
     * 删除年度考核信息
     *
     * @param id 年度考核主键
     * @return 结果
     */
    @Override
    public int deleteSchoolAnnualAssessmentById(Long id)
    {
        return schoolAnnualAssessmentMapper.deleteSchoolAnnualAssessmentById(id);
    }

    /**
     * 校验导入数据
     * @param list
     */
    @Override
    public void checkImport(List<SchoolAnnualAssessment> list) {
        //检验是否为空
        if (StringUtils.isNull(list) || list.size() == 0) {
            throw new ServiceException("导入数据不能为空");
        }
        //查询考核结果类型字典键值
        List<SysDictData> checkResult = sysDictDataMapper.selectDictDataByType("check_result");
        // 准备记录日志数据
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        for (SchoolAnnualAssessment schoolAnnualAssessment : list) {
            if (StringUtils.isNull(schoolAnnualAssessment.getYear())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、年度为空,请您重新输入! ");
            } else if (StringUtils.isEmpty(schoolAnnualAssessment.getName())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、姓名为空,请您重新输入! ");
            } else if (StringUtils.isEmpty(schoolAnnualAssessment.getIdCard())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、身份证号为空,请您重新输入! ");
            } else if (StringUtils.isEmpty(schoolAnnualAssessment.getCheckResult())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、考核结果为空,请您重新输入! ");
            } else if (schoolAnnualAssessment.getIdCard().length() != 18 && schoolAnnualAssessment.getIdCard().length() != 15){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、身份证号输入错误,请您重新输入! ");
            } else {
                //校验年度是否符合
                if (schoolAnnualAssessment.getYear().toString().length() != 4){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、年度输入错误,请您重新输入! ");
                }else {
                    for (int i = 0; i < 4; i++) {
                        if (!Character.isDigit(schoolAnnualAssessment.getYear().toString().charAt(i))){
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、年度输入错误,请您重新输入! ");
                            break;
                        }
                    }
                    if(schoolAnnualAssessment.getIdCard().length() == 18){
                        //校验前十七位是否为数字
                        for (int i = 0; i < 17; i++) {
                            if (!Character.isDigit(schoolAnnualAssessment.getIdCard().charAt(i))){
                                failureNum++;
                                failureMsg.append("<br/>" + failureNum + "、身份证号输入错误,请您重新输入! ");
                                break;
                            }
                        }
                    }
                    String checkResult1 = "";
                    //判断考核结果是否输入正确
                    for (SysDictData sysDictData : checkResult) {
                        if (schoolAnnualAssessment.getCheckResult().equals(sysDictData.getDictLabel())){
                            checkResult1 = sysDictData.getDictValue();
                        }
                    }
                    if (StringUtils.isEmpty(checkResult1)){
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、考核结果输入错误,请您重新输入! ");
                    }else {
                        schoolAnnualAssessment.setCheckResult(checkResult1);
                    }
                }
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共" + failureNum + "条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
    }

    /**
     * 导入数据
     * @param list
     * @return
     */
    @Override
    public String importData(List<SchoolAnnualAssessment> list) {
        //判断数据是否为更新或新增
        //查询年度考核所有数据
//        List<SchoolAnnualAssessment> schoolAnnualAssessmentList = schoolAnnualAssessmentMapper.selectSchoolAnnualAssessmentList(new SchoolAnnualAssessmentVo());
//        for (SchoolAnnualAssessment schoolAnnualAssessment : list) {
//            //根据年度、姓名、身份证、去查询是否有记录，有则更新，无则新增
//            for (SchoolAnnualAssessment annualAssessment : schoolAnnualAssessmentList) {
//                if (schoolAnnualAssessment.getYear().equals(annualAssessment.getYear()) &&
//                    schoolAnnualAssessment.getName().equals(annualAssessment.getName()) &&
//                    schoolAnnualAssessment.getIdCard().equals(annualAssessment.getIdCard())){
//                    schoolAnnualAssessment.setId(annualAssessment.getId());
//                }
//            }
//        }
        StringBuilder successMsg = new StringBuilder();
        //批量导入年度考核数据
        boolean b = saveOrUpdateBatch(list);
        if (!b){
            throw new ServiceException("导入失败");
        }
        successMsg.insert(0, "恭喜您，数据已导入成功！");
        return successMsg.toString();
    }

    /**
     * 下载模板
     * @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());
        }
    }
}
