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.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.ResearchAuthorizeClient;
import com.yizhi.research.application.feign.ResearchClient;
import com.yizhi.research.application.feign.ResearchQuestionClient;
import com.yizhi.research.application.vo.api.AnswerQuestionVo;
import com.yizhi.research.application.vo.api.CheckResearchStateVo;
import com.yizhi.research.application.vo.api.MyQuestion;
import com.yizhi.research.application.vo.domain.ResearchVo;
import com.yizhi.research.application.vo.domain.TrResearchAuthorizeVo;
import com.yizhi.research.application.vo.domain.TrResearchQuestionVo;
import com.yizhi.research.application.vo.domain.VoteRankingVo;
import com.yizhi.util.application.constant.ReturnCode;
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.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: shengchenglong
 * @Date: 2018/3/17 17:26
 */
@Api(tags = "调研--问题接口")
@RestController
@RequestMapping("/api/researchQuestion")
public class ResearchQuestionsController {

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

    @Autowired
    private ResearchQuestionClient researchQuestionClient;

    @Autowired
    private ResearchClient researchClient;

    @Autowired
    private ResearchAuthorizeClient researchAuthorizeClient;

    @Autowired
    private ResearchAnswerClient researchAnswerClient;

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

    /**
     * 调研问题列表
     *
     * @param researchId
     * @return
     */

    //2018.09.13添加扫码查看接口
    @GetMapping("/list/scan")
    @ApiOperation(value = "调研问题列表扫码进入", notes = "所有问题扫码进入", response = TrResearchQuestionVo.class)
    public Response<TrResearchQuestionVo> listScan(
            @ApiParam(name = "researchId", value = "调研id", required = true) @RequestParam(name = "researchId") Long researchId
    ) {
        RequestContext res = ContextHolder.get();
        Long accountId = res.getAccountId();
        List<Long> relationIds = res.getRelationIds();
        Long siteId = res.getSiteId();
        ResearchVo research = researchClient.viewOne(researchId);
        Date startTime = research.getStartTime();
        Date endTime = research.getEndTime();
        if (System.currentTimeMillis() >= startTime.getTime() && System.currentTimeMillis() <= endTime.getTime()) {
            boolean isPass = false;
            Integer range = research.getVisibleRange();
            if (range != null && range == 1) {
                if (siteId != null && research.getSiteId() != null && siteId.equals(research.getSiteId())) {
                    isPass = true;
                }
            } else if (range != null && range == 2) {
                List<TrResearchAuthorizeVo> trResearchAuthorizes = researchAuthorizeClient.getResearchAuthorize(researchId);
                List<Long> rangeIds = trResearchAuthorizes.stream().map(TrResearchAuthorizeVo::getRelationId).collect(Collectors.toList());
                if (rangeIds.contains(accountId)) {
                    isPass = true;
                } else {
                    for (Long relationId : relationIds) {
                        if (rangeIds.contains(relationId)) {
                            isPass = true;
                            break;
                        }
                    }
                }
            }
            if (isPass) {
                return list(researchId);
            } else {
                return Response.fail("4001", "无权访问");
            }
        } else {
            return Response.fail("4001", "无权访问");
        }
    }

    @GetMapping("/list")
    @ApiOperation(value = "调研问题列表", notes = "所有问题", response = TrResearchQuestionVo.class)
    public Response<TrResearchQuestionVo> list(
            @ApiParam(name = "researchId", value = "调研id", required = true) @RequestParam(name = "researchId") Long researchId
    ) {
        try {
            RequestContext context = ContextHolder.get();
            CheckResearchStateVo vo = new CheckResearchStateVo();
            vo.setResearchId(researchId);
            vo.setContext(context);
            Integer state = researchClient.checkResearchState(vo);
            if (state != 2) {
                return Response.ok(1);
            }
            return Response.ok(researchQuestionClient.listAll(researchId));
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

    @GetMapping("/list/all")
    @ApiOperation(value = "调研问题列表pc端", notes = "所有问题", response = TrResearchQuestionVo.class)
    public Response<TrResearchQuestionVo> listAll(
            @ApiParam(name = "pageNo", value = "当前页") @RequestParam(name = "pageNo", required = false) Integer pageNo,
            @ApiParam(name = "pageSize", value = "每页的个数") @RequestParam(name = "pageSize", required = false) Integer pageSize,
            @ApiParam(name = "researchId", value = "调研id", required = true) @RequestParam(name = "researchId") Long researchId
    ) {
        try {
            return Response.ok(researchQuestionClient.listByPage(pageSize, pageNo, researchId));
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail(Constants.RESEARCH_MSG_BIZ_ERROR);
        }
    }

    /**
     * 开始调研，返回第一题前端传参：
     * 调研ID（researchId）:researchId
     * <p>
     * 下一题前端传参：
     * 调研ID（researchId）:researchId
     * 下一题题号（num）:num设置为null
     * 用户回答的内容（AnswerQuestionVo）:为用户回答的内容（该对象是否为null来判断是否是重新调研）
     * AnswerQuestionVo.questionId:当前回答问题的id
     * AnswerQuestionVo.isFirst:前端从返回的TrResearchQuestion对象中取isFirst属性作为参数传入，
     * 是否是重新调研，如果是（状态：1）则需要删除上一次退出时保存的答案
     * AnswerQuestionVo.isLast:前端从返回的TrResearchQuestion对象中取isLast属性作为参数传入。
     * 是否是最后一题，用来判断是否是提交而不是下一题
     * AnswerQuestionVo.questionItems：回答的选项(上一题时不需要保存，所以不传)
     * <p>
     * 上一题前端传参：
     * 调研ID（researchId）:researchId
     * 上一题题号（num）:前端从返回的TrResearchQuestion对象中取lastNo属性作为参数传入给num
     * 用户回答的内容（AnswerQuestionVo）:
     * AnswerQuestionVo.questionId:当前回答问题的id
     *
     * @return question：用来返回上一题或下一题对象
     */
    @PostMapping("/last/next")
    @ApiOperation(value = "逐题显示调研问题", notes = "下一题或者上一题", response = TrResearchQuestionVo.class)
    public Response<MyQuestion> lastAndNext(
            @RequestBody MyQuestion myQuestion
    ) {
        try {
            if (myQuestion.getResearchId() == null) {
                return Response.fail("", "调研不存在！！");
            }
            RequestContext context = ContextHolder.get();
            CheckResearchStateVo vo = new CheckResearchStateVo();
            vo.setResearchId(myQuestion.getResearchId());
            vo.setContext(context);
            Integer state = researchClient.checkResearchState(vo);
            if (state != 2) {
                return Response.ok(1);
            }
            myQuestion.setContext(context);
            AnswerQuestionVo answerQuestionVo = myQuestion.getAnswerQuestionVo();
            Integer last = 0;
            if (answerQuestionVo != null) {
                last = answerQuestionVo.getIsLast();
            }
            myQuestion = researchQuestionClient.lastAndNext(myQuestion);
            if (myQuestion != null && last == 1) {
                ResearchVo research = researchClient.viewOne(myQuestion.getResearchId());
                //调研提交后积分发放
                if (null != research.getPoint() || !research.getPoint().equals(0)) {
                    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(new Date());                            //积分创建时间
                        pointParamVO.setSourceId(research.getId());                        //积分来源ID，（业务ID主键）
                        pointParamVO.setOperatingPoint(point);                //积分数量，  正数 加积分，  负数减积分
                        pointParamVO.setAccountId(context.getAccountId());        //学员ID
                        pointParamVO.setAccountName(context.getAccountName());    //学员名称
                        pointParamVO.setCompanyId(context.getCompanyId());        //企业ID
                        pointParamVO.setSiteId(context.getSiteId());                //站点ID
                        pointParamVO.setOrgId(context.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();
            }
            return Response.ok(myQuestion);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("调研提交发生错误----", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }

    }

    /**
     * 获取投票结果
     * @param researchId
     * @return
     */
    @GetMapping("/getVoteResult")
    Response<VoteRankingVo> getVoteResult(@RequestParam("researchId") Long researchId,
                                          @ApiParam(name = "pageNo", value = "当前页") @RequestParam(name = "pageNo", required = false) Integer pageNo,
                                          @ApiParam(name = "pageSize", value = "每页的个数") @RequestParam(name = "pageSize", required = false) Integer pageSize) {
    	VoteRankingVo result = researchQuestionClient.getVoteResult(researchId, pageNo, pageSize);
    	return Response.ok(result);
    }
    
    /**
     * 获取投票排行榜
     * @param researchId
     * @return
     */
    @GetMapping("/getVoteTop")
    Response<VoteRankingVo> getVoteTop(@RequestParam("researchId") Long researchId) {
    	VoteRankingVo result = researchQuestionClient.getVoteTop(researchId);
    	return Response.ok(result);
    }

}
