package com.qmth.distributed.print.api;

import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.distributed.print.business.bean.result.EditResult;
import com.qmth.distributed.print.business.service.PrintCommonService;
import com.qmth.distributed.print.business.templete.execute.AsyncCourseDataImportService;
import com.qmth.teachcloud.common.annotation.OperationLogDetail;
import com.qmth.teachcloud.common.bean.params.BasicCourseParams;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.BasicCourse;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.entity.TBTask;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.enums.TaskTypeEnum;
import com.qmth.teachcloud.common.enums.log.LevelEnum;
import com.qmth.teachcloud.common.enums.log.OperationTypeEnum;
import com.qmth.teachcloud.common.service.BasicCourseService;
import com.qmth.teachcloud.common.util.Result;
import com.qmth.teachcloud.common.util.ResultUtil;
import com.qmth.teachcloud.common.util.ServletUtil;
import io.swagger.annotations.*;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程表 前端控制器
 * </p>
 *
 * @author xf
 * @since 2021-03-23
 */
@Api(tags = "课程Controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + "/${prefix.url.basic}/course")
@Validated
//@Aac(strict = BOOL.FALSE, auth = BOOL.FALSE)
public class BasicCourseController {

    @Resource
    private PrintCommonService printCommonService;
    @Resource
    private BasicCourseService basicCourseService;
    @Resource
    private AsyncCourseDataImportService asyncCourseDataImportService;

    @ApiOperation(value = "模糊查询")
    @RequestMapping(value = "/query", method = RequestMethod.POST)
    public Result query(@RequestParam(value = "param", required = false) String param,
                        @RequestParam(value = "printPlanId", required = false) List<String> printPlanId,
                        @RequestParam(value = "teachingRoomId", required = false) Long teachingRoomId) {
        if (Objects.isNull(printPlanId)) {
            printPlanId = new ArrayList<>();
        }
        List<Long> printPlanIdList = printPlanId.stream().map(SystemConstant::convertIdToLong).collect(Collectors.toList());
        List<BasicCourse> userDtos = printCommonService.list(param, printPlanIdList, teachingRoomId);
        return ResultUtil.ok(userDtos);
    }


    @ApiOperation(value = "删除")
    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    public Result remove(@RequestBody BasicCourse course) {
        boolean isSuccess = printCommonService.remove(course.getId());
        return ResultUtil.ok(isSuccess);
    }


    @ApiOperation(value = "课程管理-查询")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result findBasicCourseList(@ApiParam(value = "所属机构id") @RequestParam(required = false) String belongOrgId,
                                      @ApiParam(value = "课程名称（模糊查询）") @RequestParam(required = false) String courseName,
                                      @ApiParam(value = "创建时间（起始位置）") @RequestParam(required = false) String startCreateTime,
                                      @ApiParam(value = "创建时间（终止位置）") @RequestParam(required = false) String endCreateTime,
                                      @ApiParam(value = "状态") @RequestParam(required = false) Boolean enable,
                                      @ApiParam(value = "分页页码", required = true) @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) Integer pageNumber,
                                      @ApiParam(value = "分页数", required = true) @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) Integer pageSize) {
        return ResultUtil.ok(basicCourseService.basicCoursePage(SystemConstant.convertIdToLong(belongOrgId), courseName, SystemConstant.convertIdToLong(startCreateTime), SystemConstant.convertIdToLong(endCreateTime), enable, pageNumber, pageSize));
    }

    @ApiOperation(value = "课程管理-新增/编辑")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "更新成功", response = EditResult.class)})
    public Result saveBasicCourse(@Valid @RequestBody BasicCourseParams basicCourseParams, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        return ResultUtil.ok(basicCourseService.saveBasicCourse(basicCourseParams, sysUser));
    }

    @ApiOperation(value = "课程管理-批量启用/禁用")
    @RequestMapping(value = "/enable", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "删除成功", response = EditResult.class)})
    public Result enableBasicCourse(@ApiParam(value = "选择的要删除的课程id集合", required = true) @RequestParam List<Long> idList,
                                    @ApiParam(value = "启用/禁用（默认禁用）") @RequestParam(required = false) Boolean enable) {
        if (Objects.isNull(enable)) {
            enable = false;
        }
        return ResultUtil.ok(basicCourseService.removeBasicCourseBatch(idList, enable));
    }

    @ApiOperation(value = "课程管理-根据查询条件批量启用/禁用")
    @RequestMapping(value = "/enable_by_query", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "删除成功", response = EditResult.class)})
    @OperationLogDetail(detail = "根据查询条件【所属机构id[{{belongOrgId}}],课程名称（模糊查询）[{{courseName}}],创建时间（起始位置）[{{startCreateTime}}]," +
            "创建时间（终止位置）[{{endCreateTime}}],状态[{{enable}}],启用&禁用操作[{{enableOperate}}]】批量启用/禁用课程",level = LevelEnum.TERTIARY,operationType = OperationTypeEnum.EDIT)
    public Result enableBasicCourseByQuery(@ApiParam(value = "所属机构id") @RequestParam(required = false) String belongOrgId,
                                           @ApiParam(value = "课程名称（模糊查询）") @RequestParam(required = false) String courseName,
                                           @ApiParam(value = "创建时间（起始位置）") @RequestParam(required = false) String startCreateTime,
                                           @ApiParam(value = "创建时间（终止位置）") @RequestParam(required = false) String endCreateTime,
                                           @ApiParam(value = "状态") @RequestParam(required = false) Boolean enable,
                                           @ApiParam(value = "启用&禁用操作",required = true) @RequestParam Boolean enableOperate) {
        // 禁用条件
        if (!SystemConstant.strNotNull(belongOrgId) && !SystemConstant.strNotNull(courseName) && !SystemConstant.strNotNull(startCreateTime) && !SystemConstant.strNotNull(endCreateTime) && Objects.isNull(enable)){
            throw ExceptionResultEnum.ERROR.exception("请选择要禁用的条件");
        }
        return ResultUtil.ok(basicCourseService.removeBasicCourseBatchByQuery(SystemConstant.convertIdToLong(belongOrgId), courseName, SystemConstant.convertIdToLong(startCreateTime), SystemConstant.convertIdToLong(endCreateTime), enable,enableOperate));
    }

    @ApiOperation(value = "课程基本信息管理-批量导入（异步）")
    @RequestMapping(value = "/data_import", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = EditResult.class)})
    public Result basicCourseImportAsync(@ApiParam(value = "上传文件", required = true) @RequestParam MultipartFile file) throws Exception {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        Map<String, Object> map = printCommonService.saveTask(file, TaskTypeEnum.COURSE_IMPORT);
        map.put(SystemConstant.SYS_USER, sysUser);

        asyncCourseDataImportService.importTask(map);
        TBTask tbTask = Objects.nonNull(map.get(SystemConstant.TASK)) ? (TBTask) map.get(SystemConstant.TASK) : null;
        return Objects.nonNull(tbTask) ? ResultUtil.ok(tbTask.getId()) : ResultUtil.error("创建任务失败");
    }
}

