package com.qmth.distributed.print.api;


import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.teachcloud.common.bean.params.BasicStudentParams;
import com.qmth.distributed.print.business.bean.result.EditResult;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.service.BasicStudentService;
import com.qmth.distributed.print.business.service.PrintCommonService;
import com.qmth.distributed.print.business.templete.execute.AsyncStudentDataImportService;
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.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.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 学校id 前端控制器
 * </p>
 *
 * @author wangliang
 * @since 2021-08-02
 */
@Api(tags = "学生管理controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + "/${prefix.url.basic}/student")
@Validated
//@Aac(strict = BOOL.FALSE, auth = BOOL.FALSE)
public class BasicStudentController {
    @Resource
    private BasicStudentService basicStudentService;
    @Resource
    private PrintCommonService printCommonService;
    @Resource
    private AsyncStudentDataImportService asyncStudentDataImportService;

    @ApiOperation(value = "学生基本信息管理-查询")
    @RequestMapping(value = "/query", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result findBasicStudentList(@ApiParam(value = "查询参数（学生学号或姓名）") @RequestParam(required = false) String queryParams,
                                       @ApiParam(value = "校区主键") @RequestParam(required = false) String campusId,
                                       @ApiParam(value = "学院主键") @RequestParam(required = false) String collegeId,
                                       @ApiParam(value = "专业主键") @RequestParam(required = false) String majorId,
                                       @ApiParam(value = "班级主键") @RequestParam(required = false) String clazzId,
                                       @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) {
        Set<Long> clazzIdSet = new HashSet<>();
        if (SystemConstant.strNotNull(clazzId)) {
            clazzIdSet.add(SystemConstant.convertIdToLong(clazzId));
        } else {
            clazzIdSet = null;
        }
        return ResultUtil.ok(basicStudentService.basicStudentPage(queryParams, SystemConstant.convertIdToLong(campusId), SystemConstant.convertIdToLong(collegeId), SystemConstant.convertIdToLong(majorId), clazzIdSet, pageNumber, pageSize));
    }

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

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

    @ApiOperation(value = "学生基本信息管理-根据条件删除（物理）")
    @RequestMapping(value = "/delete_by_condition", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result deleteBasicStudentByCondition(@ApiParam(value = "查询参数（学生学号或姓名）") @RequestParam(required = false) String queryParams,
                                                @ApiParam(value = "校区主键") @RequestParam(required = false) String campusId,
                                                @ApiParam(value = "学院主键") @RequestParam(required = false) String collegeId,
                                                @ApiParam(value = "专业主键") @RequestParam(required = false) String majorId,
                                                @ApiParam(value = "班级主键") @RequestParam(required = false) String clazzId) {
        Set<Long> clazzIdSet = new HashSet<>();
        if (SystemConstant.strNotNull(clazzId)) {
            clazzIdSet.add(SystemConstant.convertIdToLong(clazzId));
        } else {
            clazzIdSet = null;
        }
        if (!SystemConstant.strNotNull(queryParams) && !SystemConstant.strNotNull(campusId) && !SystemConstant.strNotNull(collegeId) && !SystemConstant.strNotNull(majorId) && clazzIdSet == null) {
            throw ExceptionResultEnum.ERROR.exception("请选择要删除的条件");
        }
        return ResultUtil.ok(basicStudentService.removeBasicStudentByCondition(queryParams, SystemConstant.convertIdToLong(campusId),
                SystemConstant.convertIdToLong(collegeId), SystemConstant.convertIdToLong(majorId), clazzIdSet));
    }

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

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