package com.ssj.service.sys.picturepredeal.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ssj.bean.conch.conch.dto.ProblemDetailDto;
import com.ssj.bean.kmt.kmt.domain.KmtExerciseBook;
import com.ssj.bean.sys.picturepredeal.domain.PicturePreDeal;
import com.ssj.bean.sys.picturepredeal.domain.ProblemSimilarPredeal;
import com.ssj.bean.sys.problem.domain.ProblemPicture;
import com.ssj.bean.sys.problem.dto.ProblemPictureListDto;
import com.ssj.conch.push.util.PushConstants;
import com.ssj.conch.util.AIServiceUtils;
import com.ssj.dao.sys.picturepredeal.dao.ProblemSimilarPreDealDao;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.rabbitmq.TopicRabbitConfig;
import com.ssj.framework.core.rabbitmq.producer.BaseRabbitSend;
import com.ssj.framework.core.util.OSSUtils;
import com.ssj.framework.core.util.PropertiesUtil;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.framework.core.util.StringUtil;
import com.ssj.framework.weixin.util.DateUtil;
import com.ssj.mapper.problem.ProblemMapper;
import com.ssj.service.ai.model.ProblemPicturePreDeal;
import com.ssj.service.conch.conch.service.ConchDerverService;
import com.ssj.service.kmt.exercisesys.dto.Exercise1Dto;
import com.ssj.service.kmt.request.SubmitQueryViaOssResultRequest;
import com.ssj.service.kmt.service.KmtExerciseBookCourseService;
import com.ssj.service.kmt.service.KmtExerciseQuestionService;
import com.ssj.service.sys.picturepredeal.service.ProblemSimilarPreDealService;
import com.ssj.service.sys.problem.service.ProblemPictureService;
import com.ssj.service.sys.push.service.SconXingeService;
import com.ssj.service.weixin.library.service.ILibVipService;
import com.ssj.service.weixin.library.service.LibVipBindService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.solr.common.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @Author: chchen
 * @Description
 * @Date Create in 11:32 2019/10/24
 * @Modified By
 */
@Service(version = "1.0")
@Transactional
public class ProblemSimilarPreDealServiceImpl extends BaseServiceImpl<ProblemSimilarPredeal, String> implements ProblemSimilarPreDealService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ProblemSimilarPreDealDao preDealDao;
    @Autowired
    private ILibVipService vipService;
    @Autowired
    private KmtExerciseBookCourseService kmtExerciseBookCourseService;
    @Autowired
    private ProblemPictureService problemPictureService;
    @Autowired
    private ConchDerverService conchDerverService;
    @Autowired
    private SconXingeService sconXingeService;
    @Autowired
    private LibVipBindService libVipBindService;
    @Autowired
    private KmtExerciseQuestionService kmtExerciseQuestionService;
    @Autowired
    private ProblemMapper problemMapper;

    @Override
    public PagingAndSortingRepository<ProblemSimilarPredeal, String> getDao() {
        return preDealDao;
    }


    @Override
    public void asyncPostRequest2AI(ProblemPicture problemPicture){
        ProblemSimilarPredeal preDeal = this.findPreDealByProblemPictureId(problemPicture.getId());
        if (preDeal == null){
            preDeal = new ProblemSimilarPredeal();
            preDeal.setProblemPictureId(problemPicture.getId());
            preDeal.setCreateTime(new Date());
        }
        preDeal.setTaskStatus(0);
        preDeal.setDealFlag(0);
        preDeal = this.save(preDeal);
        ProblemPicturePreDeal problemPicturePreDeal = new ProblemPicturePreDeal();
        problemPicturePreDeal.setProblemPicture(problemPicture);
        problemPicturePreDeal.setProblemSimilarPredeal(preDeal);
        String uuid= BaseRabbitSend.convertAndTopicSend(
                TopicRabbitConfig.exchange_aijia,
                TopicRabbitConfig.topic_problem_similar_query,
                problemPicturePreDeal);
        logger.error("难题图片识别已加入推送信息队列数据uuid："+uuid+" data:"+ JSONObject.toJSONString(problemPicturePreDeal));
    }

    @Override
    public ProblemSimilarPredeal findPreDealByProblemPictureId(String problemPictureId) {
        return preDealDao.findByProblemPictureId(problemPictureId);
    }

    @Override
    public void postRequest2AI(ProblemPicturePreDeal problemPicturePreDeal) {
        ProblemPicture problemPicture = problemPicturePreDeal.getProblemPicture();
        ProblemSimilarPredeal preDeal = problemPicturePreDeal.getProblemSimilarPredeal();
        String result = null;
        Map<String,String> querys=new HashMap<String, String>();
        String filePathPrefix = PropertiesUtil.getValue("OSS_INTERNAL_PATH");
        String fileStaticPathPrefix = PropertiesUtil.getValue("file_save_path");
        if ("2".equals(PropertiesUtil.getValue("SYS_ENV"))){
            fileStaticPathPrefix = PropertiesUtil.getValue("AI_TEST_SAVE_PATH");
        }
        querys.put("path", fileStaticPathPrefix + problemPicture.getFileKey());
        querys.put("ossPath", filePathPrefix + problemPicture.getFileKey());
        querys.put("subject", problemPicture.getSubject());
        querys.put("grade", "");
        try {
            result = AIServiceUtils.querySimilarQuestion(querys);
            logger.info("{}ai难题识别返回结果{}", problemPicture.getId(), result);
            preDeal.setResponse(result);
            if(result != null) {
                this.recordPostRequestData(preDeal, result);
            }
        } catch (Exception e){
            preDeal.setTaskStatus(2);
            preDeal.setResponse(e.getMessage());
            logger.error("请求ai识别难题异常", e);
        }
        this.recordCourseName(problemPicture, preDeal);
        this.save(preDeal);
    }

    /**
     * 记录发送ai的请求信息
     */
    private void recordPostRequestData (ProblemSimilarPredeal preDeal, String responseStr) {

        JSONObject jsonObject = JSON.parseObject(responseStr);
        if ("success".equals(jsonObject.getString("status"))){
            int flag = jsonObject.getInteger("flag");
            JSONObject data = jsonObject.getJSONObject("data");
            preDeal.setDealFlag(flag);
            preDeal.setTaskStatus(1);
            preDeal.setQuestionIds(data.getString("questionIds"));
        } else {
            preDeal.setTaskStatus(2);
            preDeal.setDealFlag(0);
            logger.warn("ai请求返回失败{}, 失败数据{}", preDeal.getProblemPictureId(), responseStr);
        }
    }

    @Override
    public void recordCourseName (ProblemPicture problemPicture, ProblemSimilarPredeal predeal){
        boolean showExerciseQuestion = false;

        //高于某个阀值要显示练习册的题目
        if (predeal.getDealFlag() == 3){
            showExerciseQuestion = true;
        }

        List<String> questionIdList = JSON.parseArray(predeal.getQuestionIds(), String.class);
//        if (CollectionUtils.isNotEmpty(questionIdList)){
//            KmtExerciseQuestion question = kmtExerciseQuestionService.getById(questionIdList.get(0));
//            if (question != null && StringUtils.isNotBlank(question.getCourseName())){
//                problemPicture.setSubject(question.getCourseName());
//                LibVipBind libVipBind = libVipBindService.findByVipIdAndSubject(problemPicture.getVipId(), question.getCourseName());
//                if (libVipBind != null) {
//                    problemPicture.setTeacherId(libVipBind.getTeacherId());
//                }
//            }
//        }
        if (CollectionUtils.isNotEmpty(questionIdList)) {
            problemPicture.setIsFeedback(1);
        }
        ProblemPicture oldProblemPicture = problemPictureService.getById(problemPicture.getId());
        problemPicture.setTeacherMessage(oldProblemPicture.getTeacherMessage());
        problemPicture = problemPictureService.save(problemPicture);
        //推送小塾
        Map<String, Object> result = new HashMap<>();

        ProblemDetailDto pdd = conchDerverService.getProblemFeedbackData(problemPicture, questionIdList, showExerciseQuestion);
        if (CollectionUtils.isNotEmpty(questionIdList)) {
            result.put("type", "PROBLEM_SIMILAR_FEEDBACK");
            result.put("time", DateUtil.format_yyyyMMddHHmmss(new Date()));
            result.put("data", pdd);
            sconXingeService.asynPushThreadTask(problemPicture.getDerver(), problemPicture.getVipId(), 1, JSON.toJSONString(result), PushConstants.PUSH_PROBLEM);
            this.problemPictureFeedback2Pad(problemPicture, predeal);
        }
    }

    public void problemPictureFeedback2Pad (ProblemPicture problemPicture, ProblemSimilarPredeal predeal){
        Map<String, Object> result = new HashMap<>();
        result.put("type", "PROBLEM_SIMILAR_FEEDBACK");
        result.put("time", DateUtil.format_yyyyMMddHHmmss(new Date()));
        ProblemPictureListDto problemPictureListDto = new ProblemPictureListDto();
        problemPictureListDto.setProblemPictureId(problemPicture.getId());
        problemPictureListDto.setCreateTime(problemPicture.getCreateTime());
        problemPictureListDto.setSubject(problemPicture.getSubject());
        problemPictureListDto.setProblemPicturePath(problemPicture.getFileKey());
        problemPictureListDto.setWeek(DateUtil.getWeekDateToStr(problemPicture.getCreateTime()));
        problemPictureListDto.setTaskStatus(predeal.getTaskStatus());
        problemPictureListDto.setDealFlag(predeal.getDealFlag());
        problemPictureListDto.setType(StringUtils.isEmpty(problemPicture.getTeacherMessage()) ? 0 : 1);
        result.put("data", problemPictureListDto);
        sconXingeService.asynPushPadThreadTask(problemPicture.getVipId(), "你的难题已解析成功快来查看吧！", result);
    }

    @Override
    public void postRequest2AIV1 (ProblemPicturePreDeal problemPicturePreDeal) {
        ProblemPicture problemPicture = problemPicturePreDeal.getProblemPicture();
        ProblemSimilarPredeal preDeal = problemPicturePreDeal.getProblemSimilarPredeal();
        String result = null;
        Map<String,String> querys=new HashMap<String, String>();
        String filePathPrefix = PropertiesUtil.getValue("OSS_INTERNAL_PATH");
        String fileStaticPathPrefix = PropertiesUtil.getValue("file_save_path");
        querys.put("requestMethod", "https://api.sharingschool.com/sz/api/kmt/exercise/submitQuerySimilarQuestionResult");
        if ("2".equals(PropertiesUtil.getValue("SYS_ENV"))){
            fileStaticPathPrefix = PropertiesUtil.getValue("AI_TEST_SAVE_PATH");
            querys.put("requestMethod", "https://xt.sharingschool.com/sz/api/kmt/exercise/submitQuerySimilarQuestionResult");
        }
        querys.put("taskId", preDeal.getId());
        querys.put("path", fileStaticPathPrefix + problemPicture.getFileKey());
        querys.put("ossPath", filePathPrefix + problemPicture.getFileKey());
        querys.put("subject", problemPicture.getSubject());
        querys.put("grade", "");
        try {
            result = AIServiceUtils.querySimilarQuestion(querys);
            logger.info("ai难题识别请求返回结果{}", result);
        } catch (Exception e){
            logger.error("请求ai识别难题请求异常", e);
        }
    }

    @Override
    public ResponseEntity submitQuerySimilarQuestionResult(SubmitQueryViaOssResultRequest request) {
        ResponseEntity responseEntity = new ResponseEntity();
        String requestJSON = JSONObject.toJSONString(request);
        logger.error("作业识别结果={}", requestJSON);
        ProblemSimilarPredeal preDeal = preDealDao.findOne(request.getTaskId());
        if (preDeal != null){
            preDeal.setTaskStatus(1);
            preDeal.setDealFlag(request.getFlag());
            preDeal.setResponse(requestJSON);
            if (CollectionUtils.isNotEmpty(request.getQuestionIds())){
                preDeal.setQuestionIds(JSONObject.toJSONString(request.getQuestionIds()));
            }
            this.save(preDeal);

            ProblemPicture pp = problemPictureService.getById(preDeal.getProblemPictureId());
            this.recordCourseName(pp, preDeal);
        } else {
            logger.error("ai识别结果异常，找不到记录");
        }
        return responseEntity.success("成功");
    }
}
