package cn.com.qmth.examcloud.core.questions.api.controller;

import cn.com.qmth.examcloud.api.commons.enums.DataRuleType;
import cn.com.qmth.examcloud.api.commons.security.bean.User;
import cn.com.qmth.examcloud.api.commons.security.bean.UserDataRule;
import cn.com.qmth.examcloud.commons.exception.StatusException;
import cn.com.qmth.examcloud.core.questions.base.question.enums.QuesStructType;
import cn.com.qmth.examcloud.core.questions.dao.PaperStructRepo;
import cn.com.qmth.examcloud.core.questions.dao.entity.PaperStruct;
import cn.com.qmth.examcloud.core.questions.dao.entity.PaperStructSearchInfo;
import cn.com.qmth.examcloud.core.questions.service.PaperStructService;
import cn.com.qmth.examcloud.core.questions.service.RandomPaperService;
import cn.com.qmth.examcloud.core.questions.service.bean.dto.QuesNameDto;
import cn.com.qmth.examcloud.web.security.DataRule;
import cn.com.qmth.examcloud.web.support.ControllerSupport;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by songyue on 16/12/28.
 */
@RestController
@RequestMapping("${api_cqb}/")
public class PaperStructController extends ControllerSupport {

    @Autowired
    private PaperStructService paperStructService;
    
    @Autowired
    private RandomPaperService randomPaperService;

    @Autowired
    private PaperStructRepo paperStructRepo;

    /**
     * 获取所有试卷结构
     *
     * @param
     * @return
     */
    @DataRule(type = DataRuleType.COURSE)
    @ApiOperation(value = "获取试卷结构带分页", notes = "获取试卷结构带分页")
    @GetMapping(value = "/paperStruct/{curPage}/{pageSize}")
    public ResponseEntity<Object> getPaperStructs(@ModelAttribute PaperStructSearchInfo searchInfo,
                                                  @PathVariable int curPage,
                                                  @PathVariable int pageSize) {
        User user = getAccessUser();
        UserDataRule userDataRule = super.getUserDataRule(DataRuleType.COURSE);

        searchInfo.setOrgId(user.getRootOrgId().toString());

        Page<PaperStruct> paperStructs = paperStructService.getPaperStructs(searchInfo, curPage, pageSize, userDataRule);
        return new ResponseEntity<>(paperStructs, HttpStatus.OK);
    }

    /**
     * 获取所有试卷结构
     *
     * @param
     * @return
     */
    @DataRule(type = DataRuleType.COURSE)
    @ApiOperation(value = "获取试卷结构不带分页", notes = "获取试卷结构不带分页")
    @GetMapping(value = "/paperStruct")
    public ResponseEntity<Object> getPaperStructs(@ModelAttribute PaperStructSearchInfo searchInfo) {
        User user = getAccessUser();
        UserDataRule ud = getUserDataRule(DataRuleType.COURSE);
        if (user != null) {
            searchInfo.setOrgId(user.getRootOrgId().toString());
        }
        List<PaperStruct> paperStructs = paperStructService.getPaperStructs(searchInfo,ud);
        return new ResponseEntity<>(paperStructs, HttpStatus.OK);
    }

    /**
     * 根据id获取试卷结构
     *
     * @param
     * @return
     */
    @ApiOperation(value = "获取试卷结构", notes = "获取试卷结构")
    @GetMapping(value = "/paperStruct/{id}")
    public ResponseEntity<Object> getPaperStructById(@PathVariable String id) {
        return new ResponseEntity<>(cn.com.qmth.examcloud.core.questions.base.Model.of(paperStructRepo.findById(id)), HttpStatus.OK);
    }

    /**
     * 更新试卷结构
     *
     * @param
     * @return
     */
    @ApiOperation(value = "更新试卷结构", notes = "更新试卷结构")
    @PutMapping(value = "/paperStruct")
    public ResponseEntity<Object> updatePaperStruct(@RequestBody PaperStruct ps) {
        User user = getAccessUser();
        ps.setOrgId(user.getRootOrgId()+"");
        if(randomPaperService.existStruct(ps.getId())) {
        	throw new StatusException("该组卷结构已被抽题模板使用，不能修改");
        }
        PaperStruct paperStruct = paperStructService.save(ps, user);
        if (paperStruct == null) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        } else {
            return new ResponseEntity<>(paperStruct, HttpStatus.OK);
        }
    }

    /**
     * 新增试卷结构
     *
     * @param ps
     * @return
     */
    @ApiOperation(value = "新增试卷结构", notes = "新增试卷结构")
    @PostMapping(value = "/paperStruct")
    public ResponseEntity<Object> addPaperStruct(@RequestBody PaperStruct ps) {
        User user = getAccessUser();
        ps.setOrgId(user.getRootOrgId()+"");
        PaperStruct paperStructTemp = paperStructService.checkNameUnique(ps.getName(), user.getRootOrgId().toString(), ps.getType());
        if (paperStructTemp != null) {
            throw new  StatusException("试卷结构名称重复，请重新命名！");
        } else {
            PaperStruct paperStruct = paperStructService.save(ps, user);
            return new ResponseEntity<>(paperStruct, HttpStatus.OK);
        }
    }

    /**
     * 删除试卷结构
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "删除试卷结构", notes = "删除试卷结构")
    @DeleteMapping(value = "/paperStruct/{ids}")
    public ResponseEntity<Object> removePaperStruct(@PathVariable String ids) {
        List<String> paperList = Stream.of(ids.split(",")).collect(Collectors.toList());
        paperStructService.removePaperStruct(paperList);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 根据题型获取来源大题
     *
     * @param
     * @return
     */
    @ApiOperation(value = "获取来源大题", notes = "获取来源大题")
    @GetMapping(value = "/paperStruct/quesNames")
    public ResponseEntity<Object> getPaperStructById(@RequestParam(required = false) String courseNo,
                                                     @RequestParam QuesStructType quesType) {
        List<QuesNameDto> quesNameDtos = new ArrayList<>();
        User user = getAccessUser();
        if (user != null) {
            quesNameDtos = paperStructService.getQuesNameList(user.getRootOrgId().toString(), courseNo, quesType);
        }
        return new ResponseEntity<>(quesNameDtos, HttpStatus.OK);
    }

}
