package com.yida.data.user.controller;

import cc.mrbird.febs.common.redis.service.RedisService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yida.data.common.core.common.ResultBean;
import com.yida.data.common.core.entity.CurrentUser;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.user.EduFaceGroup;
import com.yida.data.common.core.entity.user.EduFaceGroupDevice;
import com.yida.data.common.core.entity.user.EduStaff;
import com.yida.data.common.core.entity.user.EduStudent;
import com.yida.data.common.core.utils.Asserts;
import com.yida.data.common.core.utils.ExcelUtil;
import com.yida.data.common.core.utils.FebsUtil;
import com.yida.data.common.core.utils.FileUtil;
import com.yida.data.user.dto.*;
import com.yida.data.user.service.EduFaceGroupDeviceService;
import com.yida.data.user.service.EduFaceGroupService;
import com.yida.data.user.service.EduFaceGroupUserService;
import com.yida.data.user.service.EduUserFaceService;
import com.yida.data.user.vo.ImportFaceVO;
import com.yida.data.user.vo.IssueFacePercentVO;
import com.yida.data.user.vo.UserFacePageVO;
import com.yida.data.user.vo.UserInfoVO;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 用户人脸图像 Controller
 *
 * @author zhanghaijun
 * @date 2021-06-16 14:14:52
 */
@Slf4j
@Validated
@RestController
@RequestMapping("face")
@RequiredArgsConstructor
public class EduUserFaceController {

    private final EduUserFaceService eduUserFaceService;
    private final EduFaceGroupService eduFaceGroupService;
    private final EduFaceGroupDeviceService eduFaceGroupDeviceService;
    private final EduFaceGroupUserService eduFaceGroupUserService;
    private final RedisService redisService;

    @ApiOperation("分页查询人脸组列表")
    @GetMapping("/listFaceGroupPage")
    public ResultBean<IPage<EduFaceGroup>> listFaceGroupPage(
            @ApiParam("组名") @RequestParam(required = false) String groupName,
            @ApiParam("组id") @RequestParam(required = false) Long groupId,
            @ApiParam("当前页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @ApiParam("页面大小") @RequestParam(defaultValue = "10") Integer pageSize) {
        Long schoolId = null;
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        if (currentUser.getDeptType() == 0) {
            schoolId = currentUser.getDeptId();
        }
        return ResultBean.buildSuccess(eduFaceGroupService.listFaceGroupPage(new Page(pageNum, pageSize), groupName, schoolId, groupId));
    }

    @ApiOperation("保存、修改人脸组")
    @PostMapping("/saveFaceGroup")
    public ResultBean saveFaceGroup(@RequestBody EduFaceGroup eduFaceGroup) {
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        eduFaceGroup.setSchoolId(currentUser.getDeptId());
        eduFaceGroup.setSchoolName(currentUser.getDeptName());
        eduFaceGroupService.saveOrUpdate(eduFaceGroup);
        return ResultBean.buildSuccess();
    }


    @ApiOperation("删除人脸组")
    @GetMapping("/delFaceGroup")
    public ResultBean delFaceGroup(Long groupId) {
        eduFaceGroupService.removeFaceGroup(groupId);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("绑定人脸组与设备")
    @PostMapping("/bindFaceGroupAndDevice")
    public ResultBean bindFaceGroupAndDevice(@RequestBody BindFaceGroupDeviceDTO dto) {
        eduFaceGroupDeviceService.bindFaceGroupAndDevice(dto);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("查询人脸组设备信息")
    @GetMapping("/listFaceGroupDevice")
    public ResultBean<List<EduFaceGroupDevice>> listFaceGroupDevice(Long faceGroupId) {
        return ResultBean.buildSuccess(eduFaceGroupDeviceService.listFaceGroupDevice(faceGroupId));
    }

    @ApiOperation("查询未导入的学生")
    @GetMapping("/listStudentNotImport")
    public ResultBean<IPage<EduStudent>> listStudentNotImport(
            @RequestParam(required = false) Long depId,
            @ApiParam("0-走读，1-寄宿") @RequestParam(required = false) Integer type,
            @ApiParam("0-男，1-女") @RequestParam(required = false) Integer sex,
            @RequestParam(required = false) String keyword,
            Long schoolId, Long groupId,
            @ApiParam("当前页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @ApiParam("页面大小") @RequestParam(defaultValue = "10") Integer pageSize,
            Long dormId, Long dormRoomId,
            Long campusId, Long sectionId, Long gradeId, Long classId) {
        return ResultBean.buildSuccess(eduFaceGroupUserService.listStudentNotImport(new Page(pageNum,
                pageSize), depId, type, sex, keyword, schoolId, groupId, dormId, dormRoomId, campusId, sectionId, gradeId, classId));
    }


    @ApiOperation("查询未导入的教职工")
    @GetMapping("/listStaffNotImport")
    public ResultBean<IPage<EduStaff>> listStaffNotImport(
            @ApiParam("0-男，1-女") @RequestParam(required = false) Integer sex,
            @RequestParam(required = false) String keyword,
            Long schoolId, Long groupId,
            @ApiParam("当前页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @ApiParam("页面大小") @RequestParam(defaultValue = "10") Integer pageSize) {
        return ResultBean.buildSuccess(eduFaceGroupUserService.listStaffNotImport(new Page(pageNum, pageSize), sex, keyword, schoolId, groupId));
    }


    @ApiOperation("学生全部导入")
    @GetMapping("/saveAllStudent")
    public ResultBean saveAllStudent(
            @ApiParam("0-走读，1-寄宿") @RequestParam(required = false) Integer type,
            @ApiParam("0-男，1-女") @RequestParam(required = false) Integer sex,
            @RequestParam(required = false) String keyword,
            Long schoolId, Long groupId,
            Long dormId, Long dormRoomId,
            Long campusId, Long sectionId, Long gradeId, Long classId) {
        eduFaceGroupUserService.saveAllStudent(type, sex, keyword, schoolId, groupId, dormId, dormRoomId,
                campusId, sectionId, gradeId, classId);
        return ResultBean.buildSuccess();
    }


    @ApiOperation("教职工全部导入")
    @GetMapping("/saveAllStaff")
    public ResultBean saveAllStaff(@ApiParam("0-男，1-女") @RequestParam(required =
            false) Integer sex,
                                   @RequestParam(required = false) String keyword,
                                   Long schoolId,
                                   Long groupId) {
        eduFaceGroupUserService.saveAllStaff(sex, keyword, schoolId,
                groupId);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("添加人脸组成员")
    @PostMapping("/saveUser")
    public ResultBean saveUser(@RequestBody SaveFaceGroupUserDTO dto) {
        eduFaceGroupUserService.saveFaceGroupUser(dto, FebsUtil.getCurrentUser());
        return ResultBean.buildSuccess();
    }


    @ApiOperation("分页查询人脸组成员信息")
    @GetMapping("/listUserPage")
    public ResultBean<IPage<UserFacePageVO>> listUserPage(FaceGroupUserPageDTO dto) {
        return ResultBean.buildSuccess(eduFaceGroupUserService.listUserFacePage(dto));
    }

    @ApiOperation("删除人脸组成员")
    @PostMapping("/delUserBatch")
    public ResultBean delUserBatch(@RequestBody DelFaceGroupUserDTO dto) {
        eduFaceGroupUserService.delUserBatch(dto);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("人脸下发")
    @PostMapping("/issueBatch")
    public ResultBean issueBatch(@RequestBody BatchIssueDTO dto) {
        eduFaceGroupUserService.issueBatch(dto, FebsUtil.getCurrentUser());
        return ResultBean.buildSuccess();
    }

    @ApiOperation("上传人脸信息")
    @PostMapping("/uploadFace")
    public ResultBean uploadFace(@RequestParam("file") MultipartFile file,
                                 @ApiParam("用户id") @RequestParam Long id,
                                 @ApiParam("用户名称") @RequestParam String name,
                                 @ApiParam("学校id") @RequestParam Long schoolId,
                                 @ApiParam("0-学生，1-职工") @RequestParam Integer type) {
        return ResultBean.buildSuccess(eduUserFaceService.uploadUserFace(file, id, name, schoolId, type));
    }

    @ApiOperation("批量上传人脸信息")
    @PostMapping("/uploadFaceBatch")
    public ResultBean uploadFaceBatch(@RequestParam("file") MultipartFile file,
                                      @ApiParam("学校id") @RequestParam Long schoolId,
                                      @ApiParam("0-学生，1-职工") @RequestParam Integer type,
                                      @ApiParam("导入方式，0-按学号/手机号导入，1-按名称导入。默认学号手机号") @RequestParam(defaultValue = "0") Integer importType) {
        Long userId = FebsUtil.getCurrentUser().getUserId();
        Object o = redisService.get(CachePrefixConstant.IMPORT_FACE_KEY + userId.toString());
        Asserts.isTrue(o == null || ((ImportFaceVO) o).getFinish() == 1, "有文件正在上传中");
        eduUserFaceService.uploadUserFaceBatch(FileUtil.uploadMultipartFile(file), schoolId, type, userId, importType);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("查询导入进度")
    @GetMapping("/getImportPercent")
    public ResultBean<Object> getImportPercent() {
        return ResultBean.buildSuccess(redisService.get(CachePrefixConstant.IMPORT_FACE_KEY + FebsUtil.getCurrentUser().getUserId().toString()));
    }

    @ApiOperation("下载上传失败文件")
    @PostMapping("/downloadImportFail")
    public void downloadImportFail(HttpServletResponse response) {
        eduUserFaceService.downloadImportFail(FebsUtil.getCurrentUser().getUserId(), response);
    }

    @ApiOperation("查询人脸下发进度")
    @GetMapping("/getIssuePercent")
    public ResultBean<IssueFacePercentVO> getIssuePercent(@ApiParam("人脸组id") Long faceGroupId) {
        return ResultBean.buildSuccess(eduUserFaceService.getIssuePercent(faceGroupId));
    }

    @ApiOperation("下载下发失败文件")
    @PostMapping("/downloadIssueFail")
    public void downloadIssueFail(@RequestBody List<UserInfoVO> data,
                                  HttpServletResponse response) {
        ExcelUtil.export("下发失败.xlsx", UserInfoVO.class, data, response);
    }
}
