/**
 * Copyright (C), 2015-2018, XXX有限公司
 * FileName: MyExamController
 * Author:   phone
 * Date:     2018/3/30 11:33
 * Description: 我的考试
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.yizhi.application.exam.controller;

import java.util.*;

import com.yizhi.core.application.cache.RedisCache;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.exam.application.feign.ExamClient;
import com.yizhi.exam.application.feign.MyExamClient;
import com.yizhi.exam.application.vo.MyExamParameterVO;
import com.yizhi.exam.application.vo.MyExamVO;
import com.yizhi.exam.application.vo.exam.MyExamPageVO;
import com.yizhi.site.application.feign.api.EventTrackApiClients;
import com.yizhi.site.application.vo.site.PortalHomeSearchVO;
import com.yizhi.training.application.feign.TrainingProjectClient;
import com.yizhi.training.application.vo.domain.TrainingProjectVo;
import com.yizhi.util.application.constant.ReturnCode;
import com.yizhi.util.application.domain.Response;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import javax.servlet.http.HttpServletRequest;

/**
 * 〈一句话功能简述〉<br>
 * 〈我的考试〉
 *
 * @author fanchunhui
 * @create 2018/3/30
 * @since 1.0.0
 */

@Api(tags = "学员端", description = "学员端接口")
@RestController
@RequestMapping("/api/exam")
public class MyExamController {

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

    @Autowired
    MyExamClient myExamClient;

    @Autowired
    ExamClient examClient;

    @Autowired
    TrainingProjectClient trainingProjectClient;

    @Autowired
    private EventTrackApiClients eventTrackApiClients;
    @Autowired
    private RedisCache redisCache;

    @ApiOperation(value = "我的考试（未完成、进行中、已完成、已逾期）", notes = "我的考试（未完成、进行中、已完成、已逾期）", response = MyExamVO.class)
    @PostMapping("/list")
    public Response<MyExamVO> getMyExamList(HttpServletRequest request, @RequestBody MyExamParameterVO myExamParameterVO) {
        Map<String, Integer> page = new HashMap<String, Integer>();
        try {
            RequestContext requestContext = ContextHolder.get();
            List<Long> ids = requestContext.getRelationIds();
            myExamParameterVO.setAccountId(requestContext.getAccountId());
            if (null != ids) {
                myExamParameterVO.setIds(ids);
            } else {
                ids = new ArrayList<Long>();
                ids.add(requestContext.getAccountId());
                myExamParameterVO.setIds(ids);
            }
            myExamParameterVO.setSiteId(requestContext.getSiteId());
            MyExamPageVO myExamPageVO = myExamClient.getMyExamList(myExamParameterVO);
            List<MyExamVO> myExamVOS = new ArrayList<MyExamVO>();
            for (MyExamVO myExamVO : myExamPageVO.getExamVOS()) {
                if (null != myExamVO.getTrainingProjectId()) {
                    TrainingProjectVo trainingProject = trainingProjectClient.getOne(myExamVO.getTrainingProjectId());
                    if (trainingProject != null) {
                        myExamVO.setTrainingProjectName(trainingProject.getName());
                    } else {
                        LOG.info("考试{}({}),关联的项目{}没找到", myExamVO.getName(), myExamVO.getId(), myExamVO.getTrainingProjectId());
                    }
                }
                myExamVOS.add(myExamVO);
            }
            page.put("pageNo", myExamParameterVO.getPageNo());
            page.put("pageSize", myExamParameterVO.getPageSize());
            page.put("pageTotal", myExamPageVO.getPageTotal());

            // 添加培训测试埋点
            if(request.getHeader("Cookie")!=null&& Objects.equals(redisCache.get(request.getHeader("Cookie").replace("JSESSIONID=","")),"2")){
                eventTrackApiClients.addEvent("event_exam",requestContext.getAccountId());
            }
            return Response.ok(myExamVOS, page);
        } catch (Exception e) {
            LOG.error("", e);
            e.printStackTrace();
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }

    }

    @ApiOperation(value = "我的考试搜索", notes = "我的考试搜索", response = PortalHomeSearchVO.class)
    @GetMapping("/search")
    public Response<MyExamVO> examSearch(
            @ApiParam(name = "keyWord", value = "搜索关键字") @RequestParam(value = "keyWord", required = false) String keyWord,
            @ApiParam(name = "pageNo", value = "当前页", required = true) @RequestParam(defaultValue = "1") Integer pageNo,
            @ApiParam(name = "pageSize", value = "每页显示记录数", required = true) @RequestParam(defaultValue = "20") Integer pageSize) {
        Map<String, Integer> page = new HashMap<String, Integer>();
        try {
            RequestContext requestContext = ContextHolder.get();
            List<Long> ids = requestContext.getRelationIds();
            if (null == ids) {
                ids = new ArrayList<Long>();
                ids.add(requestContext.getAccountId());
            }
            MyExamPageVO myExamPageVO = myExamClient.searchMyExamInfo(keyWord, pageNo, pageSize, requestContext.getAccountId(),
                    requestContext.getSiteId(), ids);
            List<MyExamVO> myExamVOS = new ArrayList<MyExamVO>();
            Map<Long, String> projectNameMap = new HashMap<Long, String>();
            Long projectId = null;
            for (MyExamVO myExamVO : myExamPageVO.getExamVOS()) {
                projectId = myExamVO.getTrainingProjectId();
                if (null != projectId) {
                    String name = projectNameMap.get(projectId);
                    if (StringUtils.isBlank(name)) {
                        TrainingProjectVo trainingProject = trainingProjectClient.getOne(myExamVO.getTrainingProjectId());
                        if (null != trainingProject) {
                            name = trainingProject.getName();
                            projectNameMap.put(projectId, name);
                        }
                    } else {
                        name = "--";
                    }
                    myExamVO.setTrainingProjectName(name);
                }
                myExamVOS.add(myExamVO);
            }
            page.put("pageNo", pageNo);
            page.put("pageSize", pageSize);
            page.put("pageTotal", myExamPageVO.getPageTotal());
            return Response.ok(myExamVOS, page);
        } catch (Exception e) {
            LOG.error("", e);
            e.printStackTrace();
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }
}