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.AsyncBasicClazzImportService;
import com.qmth.teachcloud.common.bean.params.BasicClazzParams;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.entity.TBTask;
import com.qmth.teachcloud.common.enums.TaskTypeEnum;
import com.qmth.teachcloud.common.service.BasicClazzService;
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.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: 基础班级管理前端控制器
 * @Author: CaoZixuan
 * @Date: 2021-08-28
 */
@Api(tags = "班级管理controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + "/${prefix.url.basic}/clazz")
@Validated
//@Aac(strict = BOOL.FALSE, auth = BOOL.FALSE)
public class BasicClazzController {
    @Resource
    private BasicClazzService basicClazzService;
    @Resource
    private PrintCommonService printCommonService;
    @Resource
    private AsyncBasicClazzImportService asyncBasicClazzImportService;

    @ApiOperation(value = "班级基本信息管理-查询")
    @RequestMapping(value = "/query", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result findBasicClazzList(@ApiParam(value = "查询参数（班级号或班级名）") @RequestParam(required = false) String queryParams,
                                     @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(basicClazzService.basicClazzPage(queryParams, pageNumber, pageSize));
    }

    @ApiOperation(value = "班级基本信息管理-新增/编辑")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "更新成功", response = EditResult.class)})
    public Result saveBasicClazz(@Valid @RequestBody BasicClazzParams basicClazzParams, BindingResult bindingResult) throws IllegalAccessException {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        return ResultUtil.ok(basicClazzService.saveBasicClazz(basicClazzParams, sysUser));
    }

    @ApiOperation(value = "班级基本信息管理-批量删除（逻辑）")
    @RequestMapping(value = "/delete_batch", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "删除成功", response = EditResult.class)})
    public Result deleteBasicClazz(@ApiParam(value = "选择的要删除的班级id集合", required = true) @RequestParam List<String> idList) {
        return ResultUtil.ok(basicClazzService.removeBasicClazzBatch(idList.stream().map(SystemConstant::convertIdToLong).collect(Collectors.toList())));
    }

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

        asyncBasicClazzImportService.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("创建任务失败");
    }

    @ApiOperation(value = "班级数据源查询")
    @RequestMapping(value = "/datasource", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result findBasicClazzList(@ApiParam(value = "校区主键") @RequestParam(required = false) String campusId) {
        return ResultUtil.ok(basicClazzService.findClazzDatasource(SystemConstant.convertIdToLong(campusId)));
    }
}
