package com.qmth.teachcloud.mark.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.boot.core.concurrent.service.ConcurrentService;
import com.qmth.boot.core.exception.ParameterException;
import com.qmth.teachcloud.mark.dto.refix.AnswerRefixDomain;
import com.qmth.teachcloud.mark.dto.refix.AnswerRefixVo;
import com.qmth.teachcloud.mark.dto.refix.PageRefixDomain;
import com.qmth.teachcloud.mark.dto.refix.PaperRefixDomain;
import com.qmth.teachcloud.mark.entity.*;
import com.qmth.teachcloud.mark.enums.LockType;
import com.qmth.teachcloud.mark.mapper.ScanRefixBatchMapper;
import com.qmth.teachcloud.mark.service.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xf
 * @since 2023-09-22
 */
@Service
public class ScanRefixBatchServiceImpl extends ServiceImpl<ScanRefixBatchMapper, ScanRefixBatch>
        implements ScanRefixBatchService {

    @Autowired
    private ScanStudentPaperService studentPaperService;

    @Autowired
    private MarkStudentService studentService;

    @Autowired
    private ScanPaperService paperService;

    @Autowired
    private ScanPaperPageService paperPageService;

    @Autowired
    private ConcurrentService concurrentService;

    @Autowired
    private ScanAnswerCardService answerCardService;

    @Autowired
    private ScanAnswerCardSubjectService answerCardSubjectService;

    @Autowired
    private MarkService markService;

    @Transactional
    @Override
    public AnswerRefixVo answerRefix(Long userId, AnswerRefixDomain domain) {
        MarkStudent student = studentService.getById(domain.getStudentId());
        if (student == null) {
            throw new ParameterException("考生信息未找到");
        }
        ScanAnswerCard answerCard = answerCardService.findByExamAndNumber(student.getExamId(), domain.getCardNumber());
        if (answerCard == null) {
            throw new ParameterException("卡格式信息未找到");
        }
        // boolean allowSubject =
        // answerCardSubjectService.checkSubject(answerCard.getExamId(),
        // answerCard.getNumber(),
        // student.getCoursePaperId());
        // if (!allowSubject) {
        // throw new ParameterException("卡格式与考生科目不匹配");
        // }
        if (domain.getPapers().size() != answerCard.getPaperCount()) {
            throw new ParameterException("卡格式张数不一致");
        }

        concurrentService.getReadWriteLock(LockType.STUDENT + "-" + student.getId()).writeLock().lock();
        try {
            List<ScanStudentPaper> studentPaperList = studentPaperService.findByStudentId(student.getId());
            for (ScanStudentPaper studentPaper : studentPaperList) {
                PaperRefixDomain paperDomain = domain.findPaperDomain(studentPaper.getPaperIndex(),
                        studentPaper.getPaperId());
                if (paperDomain == null) {
                    throw new ParameterException("与考生当前paper不一致，paperNumber=" + studentPaper.getPaperIndex());
                }
                ScanPaper paper = paperService.getById(paperDomain.getId());
                if (paper == null) {
                    throw new ParameterException("考生当前paper不存在，paperId=" + paperDomain.getId());
                }
                paper.setCardNumber(answerCard.getNumber());
                paper.setMismatch(paperDomain.getMismatch());
                List<ScanPaperPage> pages = new ArrayList<>();
                for (PageRefixDomain pageDomain : paperDomain.getPages()) {
                    ScanPaperPage page = paperPageService.findPaperIdAndIndex(paper.getId(), pageDomain.getIndex());
                    if (page == null) {
                        throw new ParameterException("与考生当前page不一致，pageIndex=" + pageDomain.getIndex());
                    }
                    pages.add(pageDomain.update(page));
                }
                paperService.savePaperAndPages(paper, pages);
            }
            // 更换卡格式后需要删除阅卷任务
            if (!student.getCardNumber().equals(answerCard.getNumber())) {
                markService.deleteMarkTaskByStudent(student);
            }
            studentService.updateStudentByPaper(userId, student.getId(), true);
            return AnswerRefixVo.create();
        } finally {
            concurrentService.getReadWriteLock(LockType.STUDENT + "-" + student.getId()).writeLock().unlock();
        }
    }

}
