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

import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.constraints.NotNull;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import cn.com.qmth.examcloud.api.commons.enums.AdminOperateType;
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.Model;
import cn.com.qmth.examcloud.core.questions.base.exception.PaperException;
import cn.com.qmth.examcloud.core.questions.dao.PaperRepo;
import cn.com.qmth.examcloud.core.questions.dao.entity.Course;
import cn.com.qmth.examcloud.core.questions.dao.entity.Paper;
import cn.com.qmth.examcloud.core.questions.service.ClonePaperService;
import cn.com.qmth.examcloud.core.questions.service.ImportDdCollegePaperService;
import cn.com.qmth.examcloud.core.questions.service.ImportPaperService;
import cn.com.qmth.examcloud.core.questions.service.impl.CourseService;
import cn.com.qmth.examcloud.core.questions.service.temp.CqdxService;
import cn.com.qmth.examcloud.core.questions.service.yunkai.YunkaiImportPaperParam;
import cn.com.qmth.examcloud.core.questions.service.yunkai.YunkaiService;
import cn.com.qmth.examcloud.reports.commons.bean.AdminOperateReport;
import cn.com.qmth.examcloud.reports.commons.util.ReportsUtil;
import cn.com.qmth.examcloud.web.security.DataRule;
import cn.com.qmth.examcloud.web.support.ControllerSupport;
import io.swagger.annotations.ApiOperation;

/**
 * @author weiwenhai
 * @date 2017年4月14日 下午6:05:37
 * @company QMTH
 * @description 导入试卷控制器
 * @code 090
 */
@RestController
@RequestMapping("${api_cqb}/")
public class ImportPaperController extends ControllerSupport {
	private static final Logger LOG = LoggerFactory.getLogger(ImportPaperController.class);

	@Autowired
	private ClonePaperService clonePaperService;
	@Autowired
	private ImportPaperService importPaperService;
	@Autowired
	private ImportDdCollegePaperService importDdCollegePaperService;
	@Autowired
	private CqdxService cqdxService;
	@Autowired
	private YunkaiService yunkaiService;
	@Autowired
	private CourseService courseService;
	@Autowired
	private PaperRepo paperRepo;

	/**
	 * 导入试卷
	 *
	 * @param file
	 * @return
	 */
	@DataRule(type = DataRuleType.COURSE)
	@ApiOperation(value = "导入试卷", notes = "导入试卷")
	@PostMapping(value = "/importPaper")
	public ResponseEntity<Object> importPaper(@ModelAttribute Paper paper,
			@RequestParam("file") CommonsMultipartFile file) {
		User user = getAccessUser();
		UserDataRule ud = getUserDataRule(DataRuleType.COURSE);
		LOG.info("导入开始");
		File tempFile = null;
		try {
			tempFile = importPaperService.getUploadFile(file);
			Paper newPaper = importPaperService.importPaper(paper, user, tempFile, ud);
			StringBuilder sb = new StringBuilder();
			sb.append("课程:" + paper.getCourse().getName() + "(" + paper.getCourse().getCode() + ")");
			sb.append(" 试卷名称:" + paper.getName());
			ReportsUtil.report(new AdminOperateReport(user.getRootOrgId(), user.getUserId(),
					AdminOperateType.TYPE29.getDesc(), sb.toString()));
			return new ResponseEntity<>(newPaper, HttpStatus.OK);
		} catch (StatusException e) {
			throw e;
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			throw new StatusException("500", e.getMessage(), e);
		}
	}

	/**
	 * 新增试卷
	 *
	 * @param courseNo
	 * @param paperName
	 * @return
	 */
	@ApiOperation(value = "保存导入类型空白试卷", notes = "保存导入类型空白试卷")
	@PostMapping(value = "/importPaper/saveBlankPaper/{courseNo}/{paperName}")
	public ResponseEntity<Object> saveBlankPaper(@PathVariable String courseNo, @PathVariable String paperName) {
		User user = getAccessUser();
		Map<String, Object> returnMap = importPaperService.saveBlankPaper(courseNo, paperName, user);
		if (returnMap.get("msg").equals("success")) {
			return new ResponseEntity<>(returnMap, HttpStatus.OK);
		} else {
			return new ResponseEntity<>(returnMap, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	/**
	 * 克隆试卷
	 *
	 * @return
	 */
	@ApiOperation(value = "克隆试卷", notes = "克隆试卷")
	@PostMapping(value = "/clonePaper/{paperId}/{paperName}/{courseNo}")
	public ResponseEntity<Object> clonePaper(@PathVariable String paperId, @PathVariable String paperName,
			@PathVariable String courseNo) {
		User user = getAccessUser();
		Map<String, Object> map = new HashMap<>();
		try {
			clonePaperService.clonePaper(paperId, paperName, courseNo, user);
			Paper paper = Model.of(paperRepo.findById(paperId));

			Course course = courseService.getCourse(user.getRootOrgId(), courseNo);
			StringBuilder sb = new StringBuilder();
			sb.append("来源课程:" + paper.getCourse().getName() + "(" + paper.getCourse().getCode() + ")");
			sb.append(" 来源试卷名称:" + paper.getName());
			sb.append(" 复制到课程:" + course.getName() + "(" + course.getCode() + ")");
			sb.append(" 复制到试卷名称:" + paperName);
			ReportsUtil.report(new AdminOperateReport(user.getRootOrgId(), user.getUserId(),
					AdminOperateType.TYPE30.getDesc(), sb.toString()));
			map.put("msg", "success");
			return new ResponseEntity<>(map, HttpStatus.OK);
		} catch (PaperException e) {
			map.put("msg", e.getMessage());
			return new ResponseEntity<>(map, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	@ApiOperation(value = "导入地大试卷", notes = "导入地大试卷")
	@PostMapping(value = "/importDdCollegePaper")
	public ResponseEntity<Object> importDdCollegePaper(
			@RequestPart @NotNull(message = "上传文件不能为空！") MultipartFile dataFile, @RequestParam Long rootOrgId,
			@RequestParam String courseCode, @RequestParam(required = false) String suff) {
		User user = getAccessUser();
		importDdCollegePaperService.importDdCollegePaper(dataFile, user, rootOrgId, courseCode, suff);
		return new ResponseEntity<>(HttpStatus.OK);
	}

	@ApiOperation(value = "导入重庆试卷", notes = "导入重庆试卷")
	@PostMapping(value = "/importCqCollegePaper")
	public ResponseEntity<Object> importCqCollegePaper(
			@RequestPart @NotNull(message = "上传文件不能为空！") MultipartFile dataFile, @RequestParam Long rootOrgId,
			@RequestParam String paperNameSuffix, @RequestParam String impType) {
		User user = getAccessUser();
		cqdxService.bulidPaper(dataFile, user, rootOrgId, paperNameSuffix, impType);
		return new ResponseEntity<>(HttpStatus.OK);
	}

//	@ApiOperation(value = "云开导入前清理课程属性、试题属性")
//	@PostMapping(value = "/importYunkaiProp/clear")
//	public void importYunkaiPropClear(Long rootOrgId, @RequestParam String batch) {
//		yunkaiService.propClear(rootOrgId, batch);
//	}

	@ApiOperation(value = "云开导入课程属性、试题属性")
	@PostMapping(value = "/importYunkaiProp")
	public void importYunkaiProp(@RequestPart @NotNull(message = "上传文件不能为空！") MultipartFile dataFile,
			@RequestParam Long rootOrgId, @RequestParam String courseCodes, @RequestParam String batch) {
		User user = getAccessUser();
		List<String> cs = Arrays.asList(courseCodes.split(","));
		yunkaiService.saveProp(user, dataFile, rootOrgId, cs, batch);

	}

	@ApiOperation(value = "云开导入试卷")
	@PostMapping(value = "/importYunkaiPaper")
	public void importYunkaiPaper(@RequestPart @NotNull(message = "上传文件不能为空！") MultipartFile dataFile,
			@RequestParam Long rootOrgId, @RequestParam String courseCodes,@RequestParam String batch) {
		User user = getAccessUser();
		List<String> cs = Arrays.asList(courseCodes.split(","));
		YunkaiImportPaperParam p = new YunkaiImportPaperParam(user, dataFile, rootOrgId, cs);
		p.setBatch(batch);
		yunkaiService.importYunkaiPaper(p);
	}
}