/**
 * Copyright(C),2015-2018,XXX有限公司
 * FileName:QuestionLibraryController
 * Author:phone
 * Date:2018/3/2919:58
 * Description:题库
 * History:
 * <author><time><version><desc>
 * 作者姓名修改时间版本号描述
 */
package com.yizhi.application.exam.controller;

import java.util.List;
import java.util.Map;

import com.yizhi.core.application.enums.InternationalEnums;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.exam.application.feign.QuestionLibraryClient;
import com.yizhi.exam.application.feign.QuestionLibrarySubjectClient;
import com.yizhi.exam.application.vo.ContextAndPageSizeVO;
import com.yizhi.exam.application.vo.ListLibraryVO;
import com.yizhi.exam.application.vo.QuestionLibraryVO;
import com.yizhi.exam.application.vo.TypeAndCountVo;
import com.yizhi.exam.application.vo.domain.QuestionLibrary;
import com.yizhi.util.application.constant.ReturnCode;
import com.yizhi.util.application.domain.Response;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.commons.lang3.tuple.Pair;
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.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.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 *〈一句话功能简述〉<br>
 *〈题库〉
 *
 *@authorfanchunhui
 *@create2018/3/29
 *@since1.0.0
 */
@Api(tags = "管理端-题库接口", description = "管理端-题库接口")
@RestController("webQuestionLibraryController")
@RequestMapping("/manage/question")
public class QuestionLibraryController {

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

    @Autowired
    QuestionLibraryClient questionLibraryClient;

    @Autowired
    QuestionLibrarySubjectClient questionLibrarySubjectClient;

    @ApiOperation(value = "删除题库(单个)", notes = "删除题库(单个)")
    @GetMapping(value = "/delete")
    public Response<String> delete(@ApiParam(value = "题库主键") @RequestParam Long id) {
        Boolean b;
        try {
            b = questionLibraryClient.delete(id);
            return Response.ok(b);
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }

    @ApiOperation(value = "删除题库(批量)", notes = "删除题库(批量)")
    @GetMapping(value = "/deletes")
    public Response<String> batchDelete(@ApiParam(value = "题库主键数组") @RequestParam Long[] ids) {
        Boolean b;
        try {
            b = questionLibraryClient.batchDelete(ids);
            return Response.ok(b);
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }

    /*@ApiOperation(value = "导入题库试题", notes = "导入题库试题")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileDir", value = "上传文件路径", paramType = "body"),
            @ApiImplicitParam(name = "fileName", value = "文件名", paramType = "body"),
            @ApiImplicitParam(name = "id", value = "考试ID", paramType = "body")
    })
    @PostMapping(value = "/exam/import")
    public Response<String> insertByFile(ImportVO importVO) {
        Boolean b = false;
        try {
            b = questionLibraryClient.insertByFile(importVO.getFileDir(), importVO.getFileName(), importVO.getId());
            return Response.ok(b);
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }*/

    @ApiOperation(value = "删除题库试题", notes = "删除题库试题")
    @PostMapping(value = "/exam/deletes")
    public Response<String> batchExamDelete(@ApiParam(value = "批量删除试题主键") @RequestBody List<Long> ids) {
        boolean b = false;
        try {
            Integer count = questionLibrarySubjectClient.isUse(ids.get(0));
            if (count > 0){
                return Response.fail("0", InternationalEnums.QUERTIONLIBRARYCONTROLLER1.getName());
            }
            b = questionLibraryClient.batchExamDelete(ids);
            return Response.ok(b);
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }

    @ApiOperation(value = "题库管理列表", notes = "题库管理列表", response = ListLibraryVO.class)
    @GetMapping("/list")
    public Response<ListLibraryVO> list(
            ContextAndPageSizeVO contextAndPageSizeVO) {
        try {
            Pair<List<ListLibraryVO>, Map<String, Integer>> pair = null;
            Map<String, Integer> page;
            RequestContext requestContext = ContextHolder.get();
            Long companyId = requestContext.getCompanyId();
            Long siteId = requestContext.getSiteId();
            List<Long> orgIds = null;
            contextAndPageSizeVO.setCompanyId(companyId);
            contextAndPageSizeVO.setSiteId(siteId);
            if (!requestContext.isAdmin() && !CollectionUtils.isEmpty(orgIds)){
                orgIds = requestContext.getOrgIds();
                contextAndPageSizeVO.setOrgIds(orgIds);
            }
            Map<String, Object> map = questionLibraryClient.list(contextAndPageSizeVO);
            if (null != map) {
                List<ListLibraryVO> list = (List<ListLibraryVO>) map.get("list");
                page = (Map<String, Integer>) map.get("page");
                pair = new MutablePair(list, page);
                return Response.ok(pair);
            } else {
                return Response.fail(ReturnCode.RESOURCE_NOT_FOUND.getCode(),ReturnCode.RESOURCE_NOT_FOUND.getMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }

    @ApiOperation(value = "获取题库ID", notes = "生成题库ID")
    @GetMapping("get/id")
    public Response<Long> getQuestionLibraryId() {
        try {
            Long id = questionLibraryClient.getQuestionLibraryId();
            if (null != id && id > 0) {
                return Response.ok(id);
            } else {
                return Response.fail(InternationalEnums.QUERTIONLIBRARYCONTROLLER2.getName());
            }
        } catch (Exception e) {
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }


    @ApiOperation(value = "创建题库", notes = "创建题库")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "题库ID", paramType = "body"),
            @ApiImplicitParam(name = "name", value = "题库名称", paramType = "body"),
            @ApiImplicitParam(name = "libraryLabel", value = "题库标签，多个用逗号分割", paramType = "body"),
            @ApiImplicitParam(name = "comments", value = "备注", paramType = "body"),
            @ApiImplicitParam(name = "count", value = "题目数量", paramType = "body"),
            @ApiImplicitParam(name = "state", value = "状态，0删除1未使用2已使用，默认1", paramType = "body", defaultValue = "1"),
            @ApiImplicitParam(name = "sumNum", value = "题库总题目", paramType = "body"),
            @ApiImplicitParam(name = "questionLibrarySubjectVOS", value = "试题列表", paramType = "body"),
            @ApiImplicitParam(name = "list", value = "题库列表", paramType = "body")
    })
    @PostMapping("/insert")
    public Response<String> insert(@RequestBody QuestionLibraryVO questionLibraryVO) {
     /*   if(questionLibraryVO.getName() == null || questionLibraryVO.getName().trim() == ""){
            return Response.fail(ExamError.EXAM_ISNULL_CODE,ExamError.EXAM_ISNULL_MSG);
        }*/
        boolean result = false;
        try {
            RequestContext requestContext = ContextHolder.get();
            questionLibraryVO.setCompanyId(requestContext.getCompanyId());
            questionLibraryVO.setAccountId(requestContext.getAccountId());
            questionLibraryVO.setAccountName(requestContext.getAccountName());
            questionLibraryVO.setOrgId(requestContext.getOrgId());
            questionLibraryVO.setSiteId(requestContext.getSiteId());
            result = questionLibraryClient.insert(questionLibraryVO);
            if (result) {
                return Response.ok(result);
            } else {
                return Response.ok(ReturnCode.SAVE_FAIL);
            }
        } catch (Exception e) {
            LOGGER.error("创建题库失败", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }

    @ApiOperation(value = "编辑题库", notes = "编辑题库")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "题库ID", paramType = "body", required = true),
            @ApiImplicitParam(name = "name", value = "题库名称", paramType = "body"),
            @ApiImplicitParam(name = "libraryLabel", value = "题库标签，多个用逗号分割", paramType = "body"),
            @ApiImplicitParam(name = "comments", value = "备注", paramType = "body"),
            @ApiImplicitParam(name = "count", value = "题目数量", paramType = "body"),
            @ApiImplicitParam(name = "state", value = "状态，0删除1未使用2已使用，默认1", paramType = "body", defaultValue = "1"),
            @ApiImplicitParam(name = "sumNum", value = "题库总题目", paramType = "body"),
            @ApiImplicitParam(name = "questionLibrarySubjectVOS", value = "试题列表", paramType = "body"),
            @ApiImplicitParam(name = "list", value = "题库列表", paramType = "body"),
    })
    @PostMapping("/update")
    public Response<String> update(@RequestBody QuestionLibraryVO questionLibraryVO) {
       /* if(questionLibraryVO.getName() == null || questionLibraryVO.getName().trim() == ""){
            return Response.fail(ExamError.EXAM_ISNULL_CODE,ExamError.EXAM_ISNULL_MSG);
        }*/
        boolean result = false;
        try {
            RequestContext requestContext = ContextHolder.get();
            questionLibraryVO.setCompanyId(requestContext.getCompanyId());
            questionLibraryVO.setAccountId(requestContext.getAccountId());
            questionLibraryVO.setAccountName(requestContext.getAccountName());
            questionLibraryVO.setOrgId(questionLibraryVO.getOrgId());
            questionLibraryVO.setSiteId(questionLibraryVO.getSiteId());
            result = questionLibraryClient.update(questionLibraryVO);
            return Response.ok(result);
        } catch (Exception e) {
            LOGGER.error("创建题库失败", e);
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }

    @ApiOperation(value = "获取题库信息", response = QuestionLibraryVO.class)
    @GetMapping("/get/questionLibrary")
    public Response<QuestionLibraryVO> selectQuestionLibraryById(@ApiParam(value = "题库ID") @RequestParam(name = "id") Long id) {
        QuestionLibraryVO questionLibraryVO = questionLibraryClient.selectQuestionLibraryById(id);
        if (null != questionLibraryVO) {
            return Response.ok(questionLibraryVO);
        } else {
            return Response.fail(ReturnCode.RESOURCE_NOT_FOUND.getCode(),ReturnCode.RESOURCE_NOT_FOUND.getMsg());
        }
    }

    @ApiOperation(value = "题库名称是否存在接口")
    @GetMapping("/name/exist")
    public Response<String> nameExist(@RequestParam("name") String name){
        try {
            QuestionLibrary questionLibrary = questionLibraryClient.nameIsExist(name);
            if(null == questionLibrary){
                return Response.ok(false);
            }else{
                return Response.ok(true);
            }
        }catch (Exception e){
            e.printStackTrace();
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }
    
    @ApiOperation(value = "考试题库试题类型及个数", notes = "考试题库试题类型及个数", response = ListLibraryVO.class)
    @GetMapping("/library/type/count")
    public Response<List<TypeAndCountVo>> getLibraryQuestion(
            @ApiParam(value = "考试id" ,required = false)@RequestParam(name = "examId" ,required = false) Long examId,
             @ApiParam(value = "题库id" ,required = false)@RequestParam(name = "libraryId" , required = false) Long libraryId){
        try{
            List<TypeAndCountVo> list= questionLibraryClient.getTypeAndCount(examId,libraryId);
            return Response.ok(list);
        }catch (Exception e){
            LOGGER.error("",e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }
}
