package com.fs.course.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fs.common.core.domain.R;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.PubFun;
import com.fs.common.utils.StringUtils;
import com.fs.course.config.CourseConfig;
import com.fs.course.domain.*;
import com.fs.course.mapper.*;
import com.fs.course.param.FsCourseQuestionAnswerUParam;
import com.fs.course.service.IFsCourseQuestionBankService;
import com.fs.his.domain.FsUser;
import com.fs.his.mapper.FsUserMapper;
import com.fs.his.param.WxSendRedPacketParam;
import com.fs.his.service.IFsStorePaymentService;
import com.fs.system.service.ISysConfigService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 题库Service业务层处理
 *
 * @author fs
 * @date 2024-09-07
 */
@Service
public class FsCourseQuestionBankServiceImpl implements IFsCourseQuestionBankService
{
    @Autowired
    private FsCourseQuestionBankMapper fsCourseQuestionBankMapper;
    @Autowired
    private FsUserMapper fsUserMapper;
    @Autowired
    private IFsStorePaymentService paymentService;
    @Autowired
    private FsCourseAnswerLogsMapper courseAnswerLogsMapper;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private FsCourseRedPacketLogMapper redPacketLogMapper;
    @Autowired
    private FsUserCourseVideoRedPackageMapper fsUserCourseVideoRedPackageMapper;
    @Autowired
    private FsUserCourseVideoMapper courseVideoMapper;
    @Autowired
    private FsCourseWatchLogMapper courseWatchLogMapper;

    /**
     * 查询题库
     *
     * @param id 题库主键
     * @return 题库
     */
    @Override
    public FsCourseQuestionBank selectFsCourseQuestionBankById(Long id)
    {
        return fsCourseQuestionBankMapper.selectFsCourseQuestionBankById(id);
    }

    /**
     * 查询题库列表
     *
     * @param fsCourseQuestionBank 题库
     * @return 题库
     */
    @Override
    public List<FsCourseQuestionBank> selectFsCourseQuestionBankList(FsCourseQuestionBank fsCourseQuestionBank)
    {
        return fsCourseQuestionBankMapper.selectFsCourseQuestionBankList(fsCourseQuestionBank);
    }

    /**
     * 新增题库
     *
     * @param fsCourseQuestionBank 题库
     * @return 结果
     */
    @Override
    public int insertFsCourseQuestionBank(FsCourseQuestionBank fsCourseQuestionBank)
    {
        fsCourseQuestionBank.setCreateTime(DateUtils.getNowDate());
        return fsCourseQuestionBankMapper.insertFsCourseQuestionBank(fsCourseQuestionBank);
    }

    /**
     * 修改题库
     *
     * @param fsCourseQuestionBank 题库
     * @return 结果
     */
    @Override
    public int updateFsCourseQuestionBank(FsCourseQuestionBank fsCourseQuestionBank)
    {
        return fsCourseQuestionBankMapper.updateFsCourseQuestionBank(fsCourseQuestionBank);
    }

    /**
     * 批量删除题库
     *
     * @param ids 需要删除的题库主键
     * @return 结果
     */
    @Override
    public int deleteFsCourseQuestionBankByIds(Long[] ids)
    {
        return fsCourseQuestionBankMapper.deleteFsCourseQuestionBankByIds(ids);
    }

    /**
     * 删除题库信息
     *
     * @param id 题库主键
     * @return 结果
     */
    @Override
    public int deleteFsCourseQuestionBankById(Long id)
    {
        return fsCourseQuestionBankMapper.deleteFsCourseQuestionBankById(id);
    }

    @Override
    @Transactional
    public R courseAnswer(FsCourseQuestionAnswerUParam param) {
        //获取配置参数
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);

        //本次答题正确个数
        int thisRightCount = 0;
        //用户答错次数
        int errorCount = 0;
        List<FsCourseQuestionBank> incorrectQuestions = new ArrayList<>();
        //日志id
        Long logId = null;

        FsCourseAnswerLogs rightLog = new FsCourseAnswerLogs();
        //判断短链类型
        if (param.getLinkType()!=null&&param.getLinkType()==1){
            rightLog = courseAnswerLogsMapper.selectRightLogByCourseVideo(param.getVideoId(), param.getUserId(),null);
            if (rightLog!=null){
                return R.error("该课程已答题完成，不可重复答题");
            }
            errorCount = courseAnswerLogsMapper.selectErrorCountByCourseVideo(param.getVideoId(), param.getUserId(),null);

        }else {
            FsCourseWatchLog log = courseWatchLogMapper.getWatchCourseVideo(param.getUserId(),param.getVideoId(),param.getQwUserId(),param.getQwExternalId());
            if (log==null){
                return R.error("无记录");
            }
            if (log.getLogType()!=2){
                return R.error("未完课");
            }
            logId = log.getLogId();

            rightLog = courseAnswerLogsMapper.selectRightLogByCourseVideo(param.getVideoId(), param.getUserId(), param.getQwUserId());
            if (rightLog != null) {
                if (log.getRewardType() != null) {
                    return R.error("该课程已答题完成，不可重复答题");
                } else {
                    return R.ok("答题成功");
                }
            }
            errorCount = courseAnswerLogsMapper.selectErrorCountByCourseVideo(param.getVideoId(), param.getUserId(),param.getQwUserId());
        }


        if (errorCount >= config.getAnswerErrorCount()) {
            return R.error("该课题到达答错次数限制");
        }
        int remainCount = config.getAnswerErrorCount()-errorCount-1;

        // 一次性获取所有问题的正确答案
        Map<Long, FsCourseQuestionBank> correctAnswersMap = fsCourseQuestionBankMapper.selectFsCourseQuestionBankByIds(
                param.getQuestions().stream().map(FsCourseQuestionBank::getId).collect(Collectors.toList())
        ).stream().collect(Collectors.toMap(FsCourseQuestionBank::getId, question -> question));

        for (FsCourseQuestionBank questionBank : param.getQuestions()) {
            FsCourseQuestionBank correctAnswer = correctAnswersMap.get(questionBank.getId());
            if (correctAnswer.getType() == 1) {
                if (questionBank.getAnswer().equals(correctAnswer.getAnswer())) {
                    thisRightCount++;
                } else {
                    correctAnswer.setAnswer(null);
                    incorrectQuestions.add(correctAnswer);
                }
            } else if (correctAnswer.getType() == 2) {
                String[] userAnswers = convertStringToArray(questionBank.getAnswer());
                String[] correctAnswers = convertStringToArray(correctAnswer.getAnswer());

                Arrays.sort(userAnswers);
                Arrays.sort(correctAnswers);

                if (Arrays.equals(userAnswers, correctAnswers)) {
                    thisRightCount++;
                } else {
                    correctAnswer.setAnswer(null);
                    incorrectQuestions.add(correctAnswer);
                }
            }
        }

        FsCourseAnswerLogs logs = new FsCourseAnswerLogs();
        logs.setWatchLogId(logId);
        logs.setUserId(param.getUserId());
        logs.setVideoId(param.getVideoId());
        logs.setCourseId(param.getCourseId());
        logs.setCompanyId(param.getCompanyId());
        logs.setCompanyUserId(param.getCompanyUserId());
        logs.setQwUserId(param.getQwUserId() != null ? param.getQwUserId() : null );
        logs.setQuestionJson(JSONObject.toJSONString(param.getQuestions()));
        logs.setCreateTime(new Date());

        if (thisRightCount == param.getQuestions().size()) {
            logs.setIsRight(1);
            courseAnswerLogsMapper.insertFsCourseAnswerLogs(logs);
            return R.ok("答题成功");
        } else {
            logs.setIsRight(0);
            courseAnswerLogsMapper.insertFsCourseAnswerLogs(logs);
            return R.ok("答题失败").put("incorrectQuestions", incorrectQuestions).put("remain",remainCount);
        }
    }


    public static String[] convertStringToArray(String inputString) {
        String cleanString = inputString.replaceAll("[\\[\\]\"\\s]", "");
        return cleanString.split(",");
    }
}
