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

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
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 com.google.common.collect.Maps;

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.commons.util.PathUtil;
import cn.com.qmth.examcloud.core.questions.base.Constants;
import cn.com.qmth.examcloud.core.questions.base.excel.ExportUtils;
import cn.com.qmth.examcloud.core.questions.dao.entity.CourseProperty;
import cn.com.qmth.examcloud.core.questions.dao.entity.dto.CoursePropertyDto;
import cn.com.qmth.examcloud.core.questions.service.CoursePropertyService;
import cn.com.qmth.examcloud.core.questions.service.bean.CoursePropertyImportInfo;
import cn.com.qmth.examcloud.web.security.DataRule;
import cn.com.qmth.examcloud.web.support.ControllerSupport;
import io.swagger.annotations.ApiOperation;

/**
 * @author weiwenhai
 * @describle 课程属性
 * @date 2017.11.2
 */
@RestController
@RequestMapping("${api_cqb}/")
public class CoursePropertyController extends ControllerSupport {

    @Autowired
    private CoursePropertyService coursePropertyService;

    @DataRule(type = DataRuleType.COURSE)
    @ApiOperation(value = "根据orgId查询所有课程属性")
    @GetMapping(value = "/courseProperty/all")
    public ResponseEntity<Object> findAllByOrg() {
        User user = getAccessUser();
        UserDataRule ud = getUserDataRule(DataRuleType.COURSE);

        List<CourseProperty> courseProperties = coursePropertyService.findAllByOrgId(user.getRootOrgId(),ud);
        return new ResponseEntity<>(courseProperties, HttpStatus.OK);
    }

    @DataRule(type = DataRuleType.COURSE)
    @ApiOperation(value = "根据orgId查询所有课程属性(分页)")
    @GetMapping(value = "/courseProperty/all/{curPage}/{pageSize}")
    public ResponseEntity<Object> findAllByOrgId(@ModelAttribute CoursePropertyDto coursePropertyDto,
                                                 @PathVariable Integer curPage, @PathVariable Integer pageSize) {
        User user = getAccessUser();
        UserDataRule userDataRule = super.getUserDataRule(DataRuleType.COURSE);

        coursePropertyDto.setOrgId(user.getRootOrgId());

        PageRequest pageable = PageRequest.of(curPage - 1, pageSize);
        Page<CourseProperty> coursePropertiesPage = coursePropertyService.findList(coursePropertyDto, pageable, userDataRule);

        return new ResponseEntity<>(coursePropertiesPage, HttpStatus.OK);
    }

    @ApiOperation(value = "新增课程属性", notes = "新增课程属性")
    @PostMapping(value = "/courseProperty/save")
    public ResponseEntity<Object> saveCourseProperty(@RequestBody CoursePropertyDto coursePropertyDto) {
        User user = getAccessUser();
        if (user == null) {
            throw new StatusException(Constants.SYS_CODE_500, "请先登录！");
        }

        coursePropertyDto.setOrgId(user.getRootOrgId());
        coursePropertyService.saveCourseProperty(coursePropertyDto);

        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation(value = "启用")
    @PutMapping(value = "/courseProperty/open/{id}")
    public ResponseEntity<Object> openCourseProperty(@PathVariable String id) {
        User user = getAccessUser();
        if (user == null) {
            throw new StatusException(Constants.SYS_CODE_500, "请先登录！");
        }

        coursePropertyService.updateCoursePropertyStatus(id, true);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation(value = "批量启用")
    @PutMapping(value = "/courseProperty/opens/{ids}")
    public ResponseEntity<Object> opensCourseProperty(@PathVariable String ids) {
        User user = getAccessUser();
        if (user == null) {
            throw new StatusException(Constants.SYS_CODE_500, "请先登录！");
        }

        List<String> idList = Stream.of(ids.split(",")).collect(Collectors.toList());
        coursePropertyService.updateCoursePropertyStatus(idList, true);

        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation(value = "禁用")
    @PutMapping(value = "/courseProperty/close/{id}")
    public ResponseEntity<Object> closeCourseProperty(@PathVariable String id) {
        User user = getAccessUser();
        if (user == null) {
            throw new StatusException(Constants.SYS_CODE_500, "请先登录！");
        }

        coursePropertyService.updateCoursePropertyStatus(id, false);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation(value = "批量禁用")
    @PutMapping(value = "/courseProperty/closes/{ids}")
    public ResponseEntity<Object> closesCourseProperty(@PathVariable String ids) {
        User user = getAccessUser();
        if (user == null) {
            throw new StatusException(Constants.SYS_CODE_500, "请先登录！");
        }

        List<String> idList = Stream.of(ids.split(",")).collect(Collectors.toList());
        coursePropertyService.updateCoursePropertyStatus(idList, false);

        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation(value = "根据courseId查询所有课程属性")
    @GetMapping(value = "/courseProperty/all/{courseId}")
    public ResponseEntity<Object> findAllByCourseId(@PathVariable Long courseId) {
        User user = getAccessUser();
        if (user == null) {
            throw new StatusException(Constants.SYS_CODE_500, "请先登录！");
        }

        List<CourseProperty> courseProperties = coursePropertyService.findAllByCourseId(courseId);
        return new ResponseEntity<>(courseProperties, HttpStatus.OK);
    }

    @ApiOperation(value = "根据courseCode查询所有课程属性")
    @GetMapping(value = "/courseProperty/code/{courseCode}")
    public ResponseEntity<Object> findAllByCourseCode(@PathVariable String courseCode) {
        User user = getAccessUser();
        if (user == null) {
            throw new StatusException(Constants.SYS_CODE_500, "请先登录！");
        }

        List<CourseProperty> courseProperties = coursePropertyService.findAllByCourseCode(courseCode);
        return new ResponseEntity<>(courseProperties, HttpStatus.OK);
    }

    @DataRule(type = DataRuleType.COURSE)
    @ApiOperation(value = "根据courseCode查询所有开启的课程属性")
    @GetMapping(value = "/courseProperty/enable/{courseCode}")
    public ResponseEntity<Object> findAllEnable(@PathVariable String courseCode) {
        User user = getAccessUser();
        UserDataRule ud = getUserDataRule(DataRuleType.COURSE);
        if (user == null) {
            throw new StatusException(Constants.SYS_CODE_500, "请先登录！");
        }

        List<CourseProperty> courseProperties = coursePropertyService.findByEnable(courseCode, true,user,ud);
        return new ResponseEntity<>(courseProperties, HttpStatus.OK);
    }
    
    @ApiOperation(value = "下载导入模板", notes = "下载导入模板")
	@GetMapping("/courseProperty/importTemplate")
	public void getImportTemplate(HttpServletResponse response) {
		String resoucePath = PathUtil.getResoucePath("templates/coursePropertyImportTemplate.xlsx");
		exportFile("课程属性导入模板.xlsx", new File(resoucePath));
	}

	@DataRule(type = DataRuleType.COURSE)
	@ApiOperation(value = "导入课程属性", notes = "导入")
	@PostMapping("/courseProperty/import")
	public Map<String, Object> importCourseProperty(@RequestPart @NotNull(message = "上传文件不能为空！") MultipartFile file) {
		User user = getAccessUser();
		UserDataRule ud = getUserDataRule(DataRuleType.COURSE);
		List<Map<String, Object>> failRecords = coursePropertyService.importCourseProperty(ud, user, getRootOrgId(), file);
		Map<String, Object> map = Maps.newHashMap();
		map.put("hasError", CollectionUtils.isNotEmpty(failRecords));
		map.put("failRecords", failRecords);
		return map;
	}
	
	@DataRule(type = DataRuleType.COURSE)
    @ApiOperation(value = "导出课程属性")
    @RequestMapping(value = "/courseProperty/export", method = RequestMethod.GET)
    public void exportCourseProperty(@RequestParam(required = false) String name,@RequestParam(required = false) Long courseId, HttpServletResponse response) {
        User user = getAccessUser();
        UserDataRule ud = getUserDataRule(DataRuleType.COURSE);
        List<CoursePropertyImportInfo> dtos = coursePropertyService.exportCourseProperty(ud, user, name,courseId);
        ExportUtils.exportEXCEL("课程属性", CoursePropertyImportInfo.class, dtos, response);
    }

}