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

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.QuestionLibrarySubjectClient;
import com.yizhi.exam.application.vo.ExamQuestionLibraryVO;
import com.yizhi.exam.application.vo.QuestionLibrarySubjectVO;
import com.yizhi.exam.application.vo.TrQuestionLibrarySubjectVO;
import com.yizhi.util.application.constant.ReturnCode;
import com.yizhi.util.application.domain.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 〈一句话功能简述〉<br> 
 * 〈管理端-题库〉
 *
 * @author fanchunhui
 * @create 2018/3/30
 * @since 1.0.0
 */
@Api(tags = "管理端-题库接口", description = "管理端-题库接口")
@RestController
@RequestMapping("/manage/question/exam")
public class QuestionLibrarySubjectController {

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

    @Autowired
    QuestionLibrarySubjectClient questionLibrarySubjectClient;

    @ApiOperation(value = "获取题库试题列表", notes = "获取题库试题列表",response = ExamQuestionLibraryVO.class)
    @GetMapping("/list")
    public Response<ExamQuestionLibraryVO> getLibraryQuestion(
            @ApiParam(name = "id", value = "题库id") @RequestParam(name = "id",required = false) Long id,
            @ApiParam(name = "examId", value = "考试id") @RequestParam(name = "examId",required = false) Long examId,
            @ApiParam(name = "pageNo", value = "当前页") @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @ApiParam(name = "pageSize", value = "每页的数据") @RequestParam(name = "pageSize", defaultValue = "20") Integer pageSize,
            @ApiParam(name = "key", value = "关键字") @RequestParam(name = "key",required = false)String key,
            @ApiParam(name = "type", value = "试题类型：0全部 1单选 2多选 3判断 4问答") @RequestParam(name = "type",required = false)Integer type
    ) {
        Pair<List<ExamQuestionLibraryVO>, Map<String, Integer>> pair = null;
        List<ExamQuestionLibraryVO> list = null;
        Map<String,Integer> page = null;
        try {
        	/*URL url = new URL("https://fulan-test.oss-cn-hangzhou.aliyuncs.com/%E8%AF%95%E9%A2%98%E5%AF%BC%E5%85%A5.xlsx");
			HttpURLConnection conn = (HttpURLConnection)url.openConnection(); 
			conn.setDoInput(true);
			conn.setConnectTimeout(10000);
			conn.connect();
	        InputStream inputStream = conn.getInputStream();
	        
	        Workbook book = null;
	        book = WorkbookFactory.create(inputStream);
	        if(book != null){
		        Sheet sheet = book.getSheetAt(0);
		        Row row = sheet.getRow(1);
		        Cell cell = row.getCell(0);
		        String v = cell.getStringCellValue();
		        book.close();
		        inputStream.close();
		        LOGGER.info("********************************************************  " + v);
	        }*/
	        
         /*   RequestContext requestContext = ContextHolder.get();
            Long orgId = requestContext.getOrgId();
            Long siteId = requestContext.getSiteId();
            Long companyId = requestContext.getCompanyId();
            orgId = 0L;*/
            Map<String,Object> map = questionLibrarySubjectClient.getLibraryQuestion(id,examId,pageNo,pageSize,key,type);
            if(map != null){
                if (null != map.get("list")){
                    list = (List<ExamQuestionLibraryVO>) map.get("list");
                }
                if (null != map.get("page")){
                    page = (Map<String, Integer>) map.get("page");
                }
            }
            pair = new MutablePair<List<ExamQuestionLibraryVO>, Map<String, Integer>>(list, page);
            return Response.ok(pair);
        } catch (Exception e) {
            LOGGER.error("", e);
            e.printStackTrace();
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }

    @ApiOperation(value = "新增题库试题", notes = "新增题库试题")
    @PostMapping("/insert")
    public Response<String> saveQuestionLibrarySubject(@RequestBody TrQuestionLibrarySubjectVO trQuestionLibrarySubjectVO){
       try {
           RequestContext requestContext = ContextHolder.get();
           trQuestionLibrarySubjectVO.setAccountId(requestContext.getAccountId());
           trQuestionLibrarySubjectVO.setAccountName(requestContext.getAccountName());
           trQuestionLibrarySubjectVO.setCompanyId(requestContext.getCompanyId());
           trQuestionLibrarySubjectVO.setOrgId(requestContext.getOrgId());
           trQuestionLibrarySubjectVO.setSiteId(requestContext.getSiteId());
           Long id = questionLibrarySubjectClient.insert(trQuestionLibrarySubjectVO);
           if (null != id){
               return Response.ok(ReturnCode.SUCCESS);
           }else{
               return Response.fail(ReturnCode.SAVE_FAIL.getMsg());
           }
       }catch (Exception e){
           return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
       }

    }

    @ApiOperation(value = "获取试题详情",notes = "获取试题详情",response = QuestionLibrarySubjectVO.class)
    @GetMapping("/get/question")
    public Response<QuestionLibrarySubjectVO> selectById( @ApiParam(name = "id", value = "试题ID",required = true) @RequestParam(name = "id")Long id){
        QuestionLibrarySubjectVO questionLibrarySubjectVO;
       try {
           questionLibrarySubjectVO = questionLibrarySubjectClient.selectById(id);
           if (questionLibrarySubjectVO == null){
               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());
       }
       return Response.ok(questionLibrarySubjectVO);
    }

    @ApiOperation(value = "修改试题",notes = "修改试题")
    @PostMapping("/update")
    public Response<String> updateById(@RequestBody TrQuestionLibrarySubjectVO trQuestionLibrarySubjectVO){
        try {
        	  RequestContext requestContext = ContextHolder.get();
              trQuestionLibrarySubjectVO.setAccountId(requestContext.getAccountId());
              trQuestionLibrarySubjectVO.setAccountName(requestContext.getAccountName());
              trQuestionLibrarySubjectVO.setCompanyId(requestContext.getCompanyId());
              trQuestionLibrarySubjectVO.setOrgId(requestContext.getOrgId());
              trQuestionLibrarySubjectVO.setSiteId(requestContext.getSiteId());
              
            int deleteCount = questionLibrarySubjectClient.isUse(trQuestionLibrarySubjectVO.getId());
            if(deleteCount > 0){
                return  Response.fail("0", InternationalEnums.QUERTIONLIBRARYCONTROLLER1.getName());
            }
            int count = questionLibrarySubjectClient.update(trQuestionLibrarySubjectVO);
            if (count > 0){
                return Response.ok();
            }else{
                return Response.fail(ReturnCode.UPDATE_FAIL.getCode(),ReturnCode.UPDATE_FAIL.getMsg());
            }
        }catch (Exception e){
            e.printStackTrace();
            return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
        }
    }

}