package com.yizhi.application.testInfo.controller;

import com.alibaba.fastjson.JSON;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.course.application.feign.*;
import com.yizhi.course.application.vo.*;
import com.yizhi.course.application.vo.domain.ChapterEntityVo;
import com.yizhi.course.application.vo.domain.CourseEntityVo;
import com.yizhi.point.application.feign.PointRedisFeignClients;
import com.yizhi.point.application.vo.PointParamVO;
import com.yizhi.util.application.domain.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: XieHaijun
 * @Description:
 * @Date: Created in 17:30 2018/10/15
 * @Modified By
 */
@Api(tags = "测验学员端-学员接口")
@RestController
@RequestMapping("/student/testInfo")
public class TestInfoController {

    private static final Logger LOG = LoggerFactory.getLogger(TestInfoController.class);

    @Autowired
    TestInfoClient testInfoClient;

    @Autowired
    TestCaseClient testCaseClient;

    @Autowired
    CourseClient courseClient;

    @Autowired
    PointRedisFeignClients pointRedisFeignClients;
/*
    @Autowired
    AmqpTemplate amqpTemplate;*/

    @Autowired
    RecordeClient recordeClient;

    @Autowired
    private CourseStudyClient courseStudyClient;


    @ApiOperation(value = "查看测验详细信息", notes = "根据测验id查询" ,response = TestInfoViewRespVO.class)
    @GetMapping("/test/view")
    public Response<TestInfoViewRespVO> testInfoView(@ApiParam(name = "id", value = "测验id", required = true)
                                                     @RequestParam(value = "id") Long id ){
        return Response.ok(testInfoClient.testInfoView(id));
    }

    @ApiOperation(value = "查看测验详细信息(学员端 测验详细信息（测验基本，测验试题，试题的答案选项等全部信息）)", notes = "根据测验id查询",
    response = TestInfoViewRespVO.class)
    @GetMapping("/test/all/view")
    public Response<TestInfoViewRespVO> testInfoViewAll(@ApiParam(name = "id", value = "测验id", required = true)
                                                         @RequestParam(value = "id") Long id ){
        return Response.ok(testInfoClient.viewAll(id));
    }

    @ApiOperation(value = "提交作答的测验试题(总结性一次提交)", notes = "包含测验以及每题的答案" ,response = TestCaseSubmitVO.class)
    @PostMapping("/testCase/submit")
    public Response<TestCaseSubmitVO> testSubmit(@ApiParam(name = "vo", value = "测验作答的信息")
                                            @RequestBody TestCaseVO vo){
        TestCaseSubmitVO retVo = testCaseClient.testSubmit(vo);
        return Response.ok(retVo);
    }

    private void sendBonusPointsAndStatus(TestCaseVO vo, RequestContext rt) {
        //LOG.info("上下文内容={}",JSON.toJSONString(rt));
        //RequestContext rt = ContextHolder.get();
        LOG.info("当前提交的章节id={}",vo.getChapterId());
        List<ChapterEntityVo> data = courseClient.chapterList(vo.getCourseId());
        if(! CollectionUtils.isEmpty(data) ){
            if(data.size()==1){
                LOG.info("只有一个章节,准备发送课程完成状态，该章节信息={}",JSON.toJSONString(data));
                RecordeVO recorde = new RecordeVO();
                recorde.setDuration(0);
                recorde.setAccountId(rt.getAccountId());
                recorde.setCompanyId(rt.getCompanyId());
                recorde.setCourseId(vo.getCourseId());
                recorde.setOvered(1);
//                toProject(recorde,rt.getSiteId());
            } else{
                Set<Long> chapterIdSet = new HashSet<>();
                // 课程的章节
                // List<Chapter> data1 = courseClient.chapterList(vo.getCourseId());

                // 查询学习记录
                LOG.info("查询学习记录,查询的课程id={}，查询的账号id={}",vo.getCourseId(),rt.getAccountId());
                List<RecordeListVo> recordeListVos = recordeClient.getMyRecorde(vo.getCourseId(),rt.getAccountId());

                // 查询非测验的章节
                List<Long> chapterIds = new ArrayList<>();
                List<Long> testChapterIds = new ArrayList<>();
                for(ChapterEntityVo itemObj : data){
                    Integer source = itemObj.getSource();
                    if(Objects.nonNull(source) && source.intValue()==9){
                        testChapterIds.add(itemObj.getId());
                    }else {
                        chapterIds.add(itemObj.getId());
                    }

                }
                LOG.info("测验章节ids={},非测验的章节ids={}",JSON.toJSONString(testChapterIds),JSON.toJSONString(chapterIds));

                // 查询出学习完成的章节记录
                int sum = 0;
                Set<Long> studyIds = null;
                if(!CollectionUtils.isEmpty(recordeListVos)){
                    recordeListVos.removeIf(itemVo->(itemVo.getOvered()==null || itemVo.getOvered().intValue()!=1) );
                    sum = recordeListVos.stream().filter(item2->item2.getDuration()!=null).map(item3->item3.getDuration()).
                            reduce((a, b) -> a.intValue() + b.intValue()).orElseGet(() -> 0);
                    studyIds = recordeListVos.stream().map(item1->item1.getChapterId()).collect(Collectors.toSet());
                    if(!CollectionUtils.isEmpty(studyIds)){
                        chapterIdSet.addAll(studyIds);
                    }
                    LOG.info("获得非测验的学习完成的章节ids={}",JSON.toJSONString(chapterIdSet));
                }

                chapterIds.removeAll(chapterIdSet);
                LOG.info("移除学习完成的非测验章节ids=",JSON.toJSONString(chapterIds));
                //RecordeListVo recorde1 = recordeListVos.get(0);
                RecordeVO recorde = new RecordeVO();
                //BeanUtils.copyProperties(recorde1,recorde);
                recorde.setDuration(sum);
                recorde.setAccountId(vo.getAccountId());
                recorde.setOvered(1);
                recorde.setCompanyId(vo.getCompanyId());
                recorde.setCourseId(vo.getCourseId());
                recorde.setSiteId(vo.getSiteId());
                recorde.setOrgId(vo.getOrgId());
                // 素材学习完成
                if(CollectionUtils.isEmpty(chapterIds)){
                    if(!CollectionUtils.isEmpty(testChapterIds)){
                        LOG.info("测验的章节ids={},当前提交的测验的章节id={}",JSON.toJSONString(testChapterIds),vo.getChapterId());
//                        if(testChapterIds.size()==1){
//                            LOG.info("只有一个测验的，该测验提交通过，直接发送课程更新状态");
//                            toProject(recorde, vo.getSiteId());
//                        }
                        testChapterIds.remove(vo.getChapterId());
                        ChaptersPassReqVO vo1 = new ChaptersPassReqVO();
                        vo1.setChapterIds(testChapterIds);
                        vo1.setAccountId(vo.getAccountId());
                        boolean pass = testCaseClient.chaptersIsSucceed(vo1);
                        LOG.info("除当前测验，测验章节ids={},是否通过的结果={}",JSON.toJSONString(testChapterIds),pass);
//                        if(pass){
//                            LOG.info("有多个章节，章节全部通过，发送课程状态");
//                            toProject(recorde, vo.getSiteId());
//                        }
                    }
                }

            }
        }
    }

    @ApiOperation(value = "提交作答的测验试题（过程性单次提交）", notes = "包含测验以及每题的答案" ,response = TestCaseSimpleSubmitVO.class)
    @PostMapping("/testCase/simple/submit")
    public Response<TestCaseSimpleSubmitVO> testSimpleSubmit(@ApiParam(name = "vo", value = "测验作答的信息")
                                                 @RequestBody TestCaseSimpleSubmitVO vo){
        return Response.ok(testCaseClient.testCaseSimpleSubmit(vo));
    }

    @ApiOperation(value = "查看测验答卷记录详细信息", notes = "根据测验答卷id查询" ,response = TestCaseRecordVO.class)
    @GetMapping("/testcase/recordInfo/get")
    public Response<TestCaseRecordVO> testCaseRecord(@ApiParam(name = "id", value = "测验答卷id", required = true)
                                                     @RequestParam(value = "id") Long id ){
        return Response.ok(testCaseClient.getRecordInfo(id));
    }

    /**
     * 给项目发送课程完成消息
     */
//    private void toProject(Recorde recorde, Long siteId) {
//
//        taskExecutor.asynExecute(new AbstractTaskHandler() {
//            @Override
//            public void handle() {
//                try {
//                    cloudEventPublisher.publish(QueueConstant.TRAINING_PROJECT_EVENT_QUEUE, new EventWrapper<TrainingProjectEvent>(recorde.getCourseId(),
//                            TrainingProjectEvent.getInstanceCourse(recorde.getCourseId(), recorde.getAccountId(), new Date(),
//                                    recorde.getDuration().longValue(),
//                                    recorde.getOvered() == 1 ? Boolean.TRUE : Boolean.FALSE, siteId)));
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        });
//    }

    private void getPoint(Long chapterId, String accountName,
                          Long accountId, Long companyId, Long siteId, Long orgId) {
        try {
            ChapterEntityVo chapter = courseClient.chapterGet(chapterId);
            if (Objects.nonNull(chapter) && Objects.nonNull(chapter.getScore())) {
                //Material material = materialClient.view(chapter.getMaterialId());
                //if (!StringUtils.isEmpty(material)) {

            PointParamVO pointParamVO = new PointParamVO();
            //事件名称
            pointParamVO.setEventName("pointCourse");
            //事件类型
            pointParamVO.setActivityType("课程章节测验通过发放积分");
            //学习活动来源
            pointParamVO.setActivitySource("课程测验");
            //学习活动名
            StringBuilder activityName = new StringBuilder();

            CourseEntityVo course = courseClient.view(chapter.getCourseId());
            if (!StringUtils.isEmpty(course)) {
                activityName.append(course.getName());
                activityName.append(":");
            }
            activityName.append(chapter.getName());
            pointParamVO.setActivityName(activityName.toString());
            //发放条件
            pointParamVO.setReleaseCondition("课程章节完成发放");
            //发放规则
            pointParamVO.setReleaseRules("按照章节获取取积分");
            //积分创建时间
            pointParamVO.setCreatePointTime(new Date());
            //积分来源ID，（业务ID主键）
            pointParamVO.setSourceId(chapter.getId());
            //积分数量，  正数 加积分，  负数减积分
            pointParamVO.setOperatingPoint(chapter.getScore());
            //学员ID
            pointParamVO.setAccountId(accountId);
            //学员名称
            pointParamVO.setAccountName(accountName);
            pointParamVO.setSiteId(siteId);
            pointParamVO.setCompanyId(companyId);
            pointParamVO.setOrgId(orgId);
            //调用积分接口添加积分
            String sitePointId = pointRedisFeignClients.addPointRedis(pointParamVO);
            if (null != sitePointId) {
                //发送积分获取消息
                //amqpTemplate.convertAndSend("course", sitePointId);
            }
        }


        } catch (Exception e) {
            LOG.error("章节" + chapterId + "积分消息发送失败！");
        }

    }
}
