package com.yizhi.application.research.controller;

import com.yizhi.application.point.constant.MQqueuesEnum;
import com.yizhi.application.point.constant.PointEventEnum;
import com.yizhi.core.application.cache.RedisCache;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.point.application.feign.PointRedisFeignClients;
import com.yizhi.point.application.vo.PointParamVO;
import com.yizhi.research.application.feign.ResearchAnswerClient;
import com.yizhi.research.application.feign.ResearchClient;
import com.yizhi.research.application.model.AnswerModel;
import com.yizhi.research.application.vo.api.AnswerVo;
import com.yizhi.research.application.vo.api.ViewAnswerVo;
import com.yizhi.research.application.vo.domain.ResearchVo;
import com.yizhi.site.application.feign.api.EventTrackApiClients;
import com.yizhi.util.application.domain.Response;
import com.yizhi.util.application.enums.i18n.Constants;
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.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;

/**
 * @Author: shengchenglong
 * @Date: 2018/3/19 10:30
 */
@Api(tags = "调研--答案接口")
@RestController
@RequestMapping("/api/researchAnswer")
public class ResearchAnswerController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ResearchController.class);

    @Autowired
    private ResearchAnswerClient researchAnswerClient;
    @Autowired
    private ResearchClient researchClient;
    @Autowired
    private PointRedisFeignClients pointRedisFeignClients;

    @Autowired
    private EventTrackApiClients eventTrackApiClients;
    @Autowired
    private RedisCache redisCache;
    /*@Autowired
    private AmqpTemplate amqpTemplate;*/

    @PostMapping("/submit")
    @ApiOperation(value = "学员提交调研答案")
    public Response<Integer> submitAnswer(HttpServletRequest request,
                                          @ApiParam(name = "answerVo", value = "答案vo", required = true) @RequestBody AnswerVo answerVo
    ) {
        try {
            if (answerVo.getResearchId() == null || CollectionUtils.isEmpty(answerVo.getQuestions())) {
                return Response.fail("", "参数不全，请查看参数是否合规！！");
            }
            AnswerModel model = new AnswerModel();
            RequestContext context = ContextHolder.get();
            model.setAnswerVo(answerVo);
            model.setContext(context);
            model.setDate(new Date());

            int num = researchAnswerClient.submitAnswer(model);
            if (num >= 1) {
                ResearchVo research = researchClient.viewOne(answerVo.getResearchId());
                //考试交卷后积分发放
                try {
                    Integer point = research.getPoint();
                    PointParamVO pointParamVO = new PointParamVO();
                    pointParamVO.setEventName(PointEventEnum.POINTRESEARCH.getKey());    //事件名称
                    pointParamVO.setActivityType("调研通过积分发放");                //事件类型
                    pointParamVO.setActivitySource("调研");                            //学习活动来源
                    pointParamVO.setActivityName(research.getName());                //学习活动名称
                    pointParamVO.setReleaseCondition("指定积分发放");                    //发放条件
                    pointParamVO.setReleaseRules("调研通过");                    //发放规则
                    pointParamVO.setCreatePointTime(model.getDate());                            //积分创建时间
                    pointParamVO.setSourceId(research.getId());                        //积分来源ID，（业务ID主键）
                    pointParamVO.setOperatingPoint(point);                //积分数量，  正数 加积分，  负数减积分
                    pointParamVO.setAccountId(model.getContext().getAccountId());        //学员ID
                    pointParamVO.setAccountName(model.getContext().getAccountName());    //学员名称
                    pointParamVO.setCompanyId(model.getContext().getCompanyId());        //企业ID
                    pointParamVO.setSiteId(model.getContext().getSiteId());                //站点ID
                    pointParamVO.setOrgId(model.getContext().getOrgId());                //组织ID
                    String sitePointId = null;
                    if (null != point && 0 != point) {
                        sitePointId = pointRedisFeignClients.addPointRedis(pointParamVO);    //调用积分接口添加积分
                    }
                    String sitePointId1 = pointRedisFeignClients.addPointRedis(pointParamVO);
                    if (null != sitePointId) {
                        //amqpTemplate.convertAndSend(MQqueuesEnum.RESEARCH.getKey(), sitePointId);    //发送积分获取消息
                    }
                    if (null != sitePointId1) {
                       // amqpTemplate.convertAndSend(MQqueuesEnum.EXPERIENCERESERCH.getKey(), sitePointId1);    //发送积分获取消息
                    }
                } catch (Exception e) {
                    LOGGER.error("调研积分发放失败：", e);
                }
                return Response.ok(Constants.MSG_SUCCESS);
            }
            if (num == -2) {
                return Response.fail(Constants.RESEARCH_MSG_QUESTION_NOT_ANSWER);
            }
            if (num == -111) {
                return Response.fail(Constants.RESEARCH_MSG_SUBMIT_REPEATITION);
            }
            if (num == -3) {
                return Response.fail(Constants.RESEARCH_MSG_ANSWER_TOO_SHORT);
            }
            // 添加调研埋点
            if(request.getHeader("Cookie")!=null&& Objects.equals(redisCache.get(request.getHeader("Cookie").replace("JSESSIONID=","")),"2")){
                eventTrackApiClients.addEvent("event_research",ContextHolder.get().getAccountId());
            }
            return Response.fail(Constants.RESEARCH_MSG_BIZ_ERROR);
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail(Constants.RESEARCH_MSG_BIZ_ERROR);
        }
    }

    @GetMapping("/view")
    @ApiOperation(value = "查看提交的问卷答案", response = ViewAnswerVo.class)
    public Response<ViewAnswerVo> view(
            @ApiParam(name = "researchId", value = "调研id", required = true) @RequestParam("researchId") Long researchId
    ) {
        try {
            return Response.ok(researchAnswerClient.viewResearch(researchId, ContextHolder.get().getAccountId()));
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail(Constants.RESEARCH_MSG_BIZ_ERROR);
        }
    }

}
