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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.core.utils.LogfieldUtil;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
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.epidemic.EpidemicDetail;
import yangtz.cs.liu.campus.domain.exam.ExamDetail;
import yangtz.cs.liu.campus.mapper.epidemic.EpidemicDetailMapper;
import yangtz.cs.liu.campus.mapper.exam.ExamDetailMapper;
import yangtz.cs.liu.campus.service.epidemic.IEpidemicDetailService;
import yangtz.cs.liu.campus.service.exam.IExamDetailService;
import yangtz.cs.liu.campus.vo.epidemic.EpidemicDetailVo;
import yangtz.cs.liu.campus.vo.exam.ExamDetailVo;

import javax.validation.Validator;
import java.util.Arrays;
import java.util.List;

import static com.ruoyi.common.utils.StringUtils.isNotNull;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static yangtz.cs.liu.campus.constant.QuestionType.MCQ;
import static yangtz.cs.liu.campus.constant.QuestionType.SCQ;

@Service
public class EpidemicDetailServiceImpl extends ServiceImpl<EpidemicDetailMapper, EpidemicDetail> implements IEpidemicDetailService {


    @Autowired
    private EpidemicDetailMapper epidemicDetailMapper;

    /**
     * 获取问卷内容
     *
     * @param epidemicDetail
     * @return
     */
    @Override
    public List<EpidemicDetail> queryList(EpidemicDetail epidemicDetail) {
        LambdaQueryWrapper<EpidemicDetail> lqw = new LambdaQueryWrapper<>();
        lqw
                .eq(isNotNull(epidemicDetail.getEpidemicId()), EpidemicDetail::getEpidemicId, epidemicDetail.getEpidemicId())
                .like(isNotBlank(epidemicDetail.getSubjectTitle()),EpidemicDetail::getSubjectTitle,epidemicDetail.getSubjectTitle())
                .orderByAsc(EpidemicDetail::getSort)
        ;
        return epidemicDetailMapper.selectList(lqw);
    }


    /**
     * 统计结果
     *
     * @param epidemicId
     * @return
     */
    @Override
    public List<EpidemicDetailVo> selectResult(Long epidemicId) {
        return epidemicDetailMapper.selectResult(epidemicId);
    }

//    /**
//     * 查询试题详细列表
//     *
//     * @param examDetail 试题详细
//     * @return 试题详细集合
//     */
//    public List<ExamDetail> selectExamDetailList(ExamDetail examDetail) {
//        return examDetailMapper.selectExamDetailList(examDetail);
//    }
//
//
//    /**
//     * 新增试题详细
//     *
//     * @param examDetail 试题详细
//     * @return 结果
//     */
//    public int insertExamDetail(ExamDetail examDetail) {
//        return examDetailMapper.insertExamDetail(examDetail);
//    }
//
//    /**
//     * 修改试题详细
//     *
//     * @param examDetail 试题详细
//     * @return 结果
//     */
//    public int updateExamDetail(ExamDetail examDetail) {
//        return examDetailMapper.updateExamDetail(examDetail);
//    }




    @Autowired
    protected Validator validator;

    private static final Logger log = LoggerFactory.getLogger(EpidemicDetailServiceImpl.class);

    @Override
    public String importData(List<EpidemicDetail> detailList, Long examId) {
        // 准备记录日志数据
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        // 遍历并逐个导入
        for (EpidemicDetail epidemicDetail : detailList) {
            epidemicDetail.setEpidemicId(examId);
            try {
                // 验证是否存在这个题目
                EpidemicDetail detail = new EpidemicDetail();
                detail.setSubjectType(epidemicDetail.getSubjectType());
                detail.setSubjectTitle(epidemicDetail.getSubjectTitle());
                detail.setEpidemicId(examId);
                List<EpidemicDetail> epidemicDetailList = epidemicDetailMapper.selectEpidemicDetailList(detail);
                if (StringUtils.isNotNull(epidemicDetailList) || epidemicDetailList.size() == 0) {
                    BeanValidators.validateWithException(validator, epidemicDetail);
                    LogfieldUtil.insert(epidemicDetail);
                    epidemicDetailMapper.insertEpidemicDetail(epidemicDetail);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、问题 " + epidemicDetail.getSubjectTitle() + " 导入成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、问题 " + epidemicDetail.getSubjectTitle() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、问题 " + epidemicDetail.getSubjectTitle() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
                throw new ServiceException("导入失败");
            }
        }
        successMsg.insert(0, "恭喜您，数据已导入成功！共有 " + successNum + " 条，数据如下：");
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(successMsg.toString() + "<br/>" + failureMsg.toString());
        }
        return successMsg.toString();
    }

    @Override
    public void check(List<EpidemicDetail> detailList, Long epidemicId) {
        // 检验是否为空
        if (StringUtils.isNull(detailList) || detailList.size() == 0) {
            throw new ServiceException("导入数据不能为空");
        }
        // 准备记录日志数据
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        for (EpidemicDetail epidemicDetail : detailList) {
            epidemicDetail.setEpidemicId(epidemicId);
            if (epidemicDetail.getSubjectTitle() == null || StringUtils.isEmpty(epidemicDetail.getSubjectTitle())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、题目标题为空,请您重新输入! ");
            } else if (epidemicDetail.getAnswer() == null || StringUtils.isEmpty(epidemicDetail.getAnswer())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、正确答案为空,请您重新输入! ");
            } else if (null == epidemicDetail.getSubjectType() || StringUtils.isEmpty(epidemicDetail.getSubjectType())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、题型为空,请您重新输入! ");
            } else if (!SCQ.equals(epidemicDetail.getSubjectType()) && !MCQ.equals(epidemicDetail.getSubjectType())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、题型错误,请您重新输入! ");
            } else if (SCQ.equals(epidemicDetail.getSubjectType())) {
                if (!"ABCDEFGH".contains(epidemicDetail.getAnswer())) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、正确答案解析错误,单选题正确答案为ABCDEFGH其中一种! ");
                }
            } else if (MCQ.equals(epidemicDetail.getSubjectType())) {
                String questionAnswer = epidemicDetail.getAnswer();
                char[] chars = questionAnswer.toCharArray();
                Arrays.sort(chars);
                epidemicDetail.setAnswer(new String(chars));
            }

        }
    }
}
