package jnpf.cultivate.utils;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.ImmutableMap;
import jnpf.base.UserInfo;
import jnpf.cultivate.service.FtbCultivateTestPaperQuestionService;
import jnpf.cultivate.service.FtbCultivateTestPaperService;
import jnpf.cultivate.v2.service.V2CultivateExamService;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.model.cultivate.po.paper.FtbCultivateTestPaperQuestion;
import jnpf.model.enums.CourseEnums;
import jnpf.util.Constants;
import jnpf.util.UserProvider;
import jnpf.utils.FeignHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class AsyncExamQuestionUtils {
    /**
     * 试卷题目关联
     */
    @Lazy
    @Autowired
    private FtbCultivateTestPaperQuestionService paperQuestionService;

    /**
     * 试卷
     */
    @Autowired
    @Lazy
    private FtbCultivateTestPaperService testPaperService;

    @Lazy
    @Autowired
    private V2CultivateExamService v2CultivateExamService;

    /**
     * 异步处理试卷试题
     * @param tenantCode 租户ID
     * @param questionIds 题目集合
     * @param headers
     */
    @Async
    public void asyncPaperQuestion(String tenantCode, List<String> questionIds, Map<String, String> headers) {

        try {
            FeignHolder.set(headers);
            TenantDataSourceUtil.switchTenant(tenantCode);

            //查询题目收录的试卷列表
            QueryWrapper<FtbCultivateTestPaperQuestion> testPaperQuestionQueryWrapper = new QueryWrapper<>();
            testPaperQuestionQueryWrapper.lambda()
                    .in(FtbCultivateTestPaperQuestion::getQuestionId, questionIds)
                    .eq(FtbCultivateTestPaperQuestion::getEnabledMark, CourseEnums.EnabledMarkType.VALID.getCode());
            List<FtbCultivateTestPaperQuestion> testPaperQuestionList = paperQuestionService.list(testPaperQuestionQueryWrapper);
            if (CollectionUtil.isEmpty(testPaperQuestionList)) {
                return;
            }
            //按照试卷id 把题目分组
            Map<String,List<String>> map = new HashMap<>();//试卷ID ->题目列表
            testPaperQuestionList.forEach(paperQuestion -> {
                List<String> questionList = map.get(paperQuestion.getPaperId());
                if (CollectionUtil.isEmpty(questionList)) {
                    questionList =new ArrayList<>();
                }
                questionList.add(paperQuestion.getQuestionId());
                map.put(paperQuestion.getPaperId(), questionList);
            });
            for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                String paperId = entry.getKey();
                List<String> values = entry.getValue();
                testPaperService.batchDeleteQuestionFormPaper(paperId, values);
            }
        } catch (Exception e) {
            log.error("异步处理试卷试题:tenantCode={},questionId={}", tenantCode, questionIds);
        } finally {
            FeignHolder.clear();
        }
    }

    /**
     * 异步处理考试题目
     * @param tenantCode 租户ID
     * @param questionIds 题目集合
     * @param headers 请求头
     */
    @Async
    public void asyncExamQuestion(String tenantCode, List<String> questionIds, Map<String, String> headers) {

        try {
            FeignHolder.set(headers);
            TenantDataSourceUtil.switchTenant(tenantCode);
            v2CultivateExamService.questionChangeDeal(questionIds);
        } catch (Exception e) {
            log.error("异步处理考试题目: tenantCode = {}, questionId = {}", tenantCode, questionIds);
        } finally {
            FeignHolder.clear();
        }
    }

    /**
     * 获取租户ID
     * @return 租户ID
     */
    public String getTenantId() {
        UserInfo userInfo = UserProvider.getUser();
        return userInfo.getTenantId();
    }

    public Map<String, String> getHeadersForLogin() {
        UserInfo userInfo = UserProvider.getUser();
        String token = userInfo.getToken();
        if (StringUtils.isEmpty(token)) {
            token = "";
        }
        return ImmutableMap.of(Constants.AUTHORIZATION.toLowerCase(), token);
    }
}
