package cn.iocoder.yudao.module.system.controller.admin.user;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.*;
import cn.iocoder.yudao.module.system.convert.user.UserConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.enums.common.SexEnum;
import cn.iocoder.yudao.module.system.enums.common.UserImportEnums;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;

@Tag(name = "管理后台 - 用户")
@RestController
@RequestMapping("/system/user")
@Validated
public class UserController {

    @Resource
    private AdminUserService userService;
    @Resource
    private DeptService deptService;

    @PostMapping("/create")
    @Operation(summary = "新增用户")
    @PreAuthorize("@ss.hasPermission('system:user:create')")
    public CommonResult<Long> createUser(@Valid @RequestBody UserSaveReqVO reqVO) {
        Long id = userService.createUser(reqVO);
        return success(id);
    }

    @PutMapping("update")
    @Operation(summary = "修改用户")
    @PreAuthorize("@ss.hasPermission('system:user:update')")
    public CommonResult<Boolean> updateUser(@Valid @RequestBody UserSaveReqVO reqVO) {
        userService.updateUser(reqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除用户")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:user:delete')")
    public CommonResult<Boolean> deleteUser(@RequestParam("id") Long id) {
        userService.deleteUser(id);
        return success(true);
    }

    @PutMapping("/update-password")
    @Operation(summary = "重置用户密码")
    @PreAuthorize("@ss.hasPermission('system:user:update-password')")
    public CommonResult<Boolean> updateUserPassword(@Valid @RequestBody UserUpdatePasswordReqVO reqVO) {
        userService.updateUserPassword(reqVO.getId(), reqVO.getPassword());
        return success(true);
    }

    @PutMapping("/update-status")
    @Operation(summary = "修改用户状态")
    @PreAuthorize("@ss.hasPermission('system:user:update')")
    public CommonResult<Boolean> updateUserStatus(@Valid @RequestBody UserUpdateStatusReqVO reqVO) {
        userService.updateUserStatus(reqVO.getId(), reqVO.getStatus());
        return success(true);
    }

    @GetMapping("/page")
    @Operation(summary = "获得用户分页列表")
    @PreAuthorize("@ss.hasPermission('system:user:query')")
    public CommonResult<PageResult<UserRespVO>> getUserPage(@Valid UserPageReqVO pageReqVO) {
        // 获得用户分页列表
        PageResult<AdminUserDO> pageResult = userService.getUserPage(pageReqVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(new PageResult<>(pageResult.getTotal()));
        }
        // 拼接数据
        Map<Long, DeptDO> deptMap = deptService.getDeptMap(
                convertList(pageResult.getList(), AdminUserDO::getDeptId));
        return success(new PageResult<>(UserConvert.INSTANCE.convertList(pageResult.getList(), deptMap),
                pageResult.getTotal()));
    }

    @GetMapping({"/list-all-simple", "/simple-list"})
    @Operation(summary = "获取用户精简信息列表", description = "只包含被开启的用户，主要用于前端的下拉选项")
    public CommonResult<List<UserSimpleRespVO>> getSimpleUserList() {
        List<AdminUserDO> list = userService.getUserListByStatus(CommonStatusEnum.ENABLE.getStatus());
        // 拼接数据
        Map<Long, DeptDO> deptMap = deptService.getDeptMap(
                convertList(list, AdminUserDO::getDeptId));
        return success(UserConvert.INSTANCE.convertSimpleList(list, deptMap));
    }

    @GetMapping("/get")
    @Operation(summary = "获得用户详情")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:user:query')")
    public CommonResult<UserRespVO> getUser(@RequestParam("id") Long id) {
        AdminUserDO user = userService.getUser(id);
        if (user == null) {
            return success(null);
        }
        // 拼接数据
        DeptDO dept = deptService.getDept(user.getDeptId());
        return success(UserConvert.INSTANCE.convert(user, dept));
    }

    @GetMapping("/export")
    @Operation(summary = "导出用户")
    @PreAuthorize("@ss.hasPermission('system:user:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportUserList(@Validated UserPageReqVO exportReqVO,
                               HttpServletResponse response) throws IOException {
        exportReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<AdminUserDO> list = userService.getUserPage(exportReqVO).getList();
        // 输出 Excel
        Map<Long, DeptDO> deptMap = deptService.getDeptMap(
                convertList(list, AdminUserDO::getDeptId));
        ExcelUtils.write(response, "用户数据.xls", "数据", UserRespVO.class,
                UserConvert.INSTANCE.convertList(list, deptMap));
    }

    @GetMapping("/student/export")
    @Operation(summary = "导出学生")
    @PreAuthorize("@ss.hasPermission('system:user:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exporStudent(@Validated UserPageReqVO exportReqVO,
                               HttpServletResponse response) throws IOException {
        exportReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<AdminUserDO> list = userService.getUserPage(exportReqVO).getList();

        Map<Long, DeptDO> deptMap = deptService.getDeptMap(
                convertList(list, AdminUserDO::getDeptId));

        List<UserRespVO> userRespVOS = UserConvert.INSTANCE.convertList(list, deptMap);
        //将用户转换成学生的标头
        List<UserStudentExcelVO> studentUserList = new ArrayList<>();
        if (!userRespVOS.isEmpty()) {
            userRespVOS.stream().forEach(sysUser ->{
                UserStudentExcelVO student = new UserStudentExcelVO();
                BeanUtil.copyProperties(sysUser, student);
                if (sysUser.getUserType()==1){
                    student.setStatusType(sysUser.getStatusType()==1?"培训教师":"教师");
                }else if (sysUser.getUserType()==2){
                    student.setStatusType(sysUser.getStatusType()==1?"学员":"学生");
                }
                studentUserList.add(student);
            });
        }
        // 输出 Excel
        ExcelUtils.write(response, "学生数据.xls", "数据", UserStudentExcelVO.class,
                BeanUtils.toBean(studentUserList, UserStudentExcelVO.class));
//        ExcelUtils.write(response, "学生数据.xls", "数据", UserStudentExcelVO.class, studentUserList );
    }

    @GetMapping("/teacher/export")
    @Operation(summary = "导出教师")
    @PreAuthorize("@ss.hasPermission('system:user:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exporTeacher(@Validated UserPageReqVO exportReqVO,
                             HttpServletResponse response) throws IOException {
        exportReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<AdminUserDO> list = userService.getUserPage(exportReqVO).getList();
        Map<Long, DeptDO> deptMap = deptService.getDeptMap(
                convertList(list, AdminUserDO::getDeptId));
        List<UserRespVO> userRespVOS = UserConvert.INSTANCE.convertList(list, deptMap);
        //将用户转换成教师的标头
        List<UserTeacherExcelVO> studentUserList = new ArrayList<>();
        if (!userRespVOS.isEmpty()) {
            userRespVOS.stream().forEach(sysUser ->{
                UserTeacherExcelVO student = new UserTeacherExcelVO();
                BeanUtil.copyProperties(sysUser, student);
                if (sysUser.getUserType()==1){
                    student.setStatusType(sysUser.getStatusType()==1?"培训教师":"教师");
                }else if (sysUser.getUserType()==2){
                    student.setStatusType(sysUser.getStatusType()==1?"学员":"学生");
                }
                studentUserList.add(student);
            });
        }
        // 输出 Excel
        ExcelUtils.write(response, "教师数据.xls", "数据", UserTeacherExcelVO.class,
                studentUserList);
    }

    @GetMapping("/get-import-template")
    @Operation(summary = "获得导入用户模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 手动创建导出 demo
        List<UserImportExcelVO> list = Arrays.asList(
                UserImportExcelVO.builder().username("yunai").deptId(1L).email("yunai@iocoder.cn").mobile("15601691300")
                        .nickname("芋道").status(CommonStatusEnum.ENABLE.getStatus()).sex(SexEnum.MALE.getSex()).build(),
                UserImportExcelVO.builder().username("yuanma").deptId(2L).email("yuanma@iocoder.cn").mobile("15601701300")
                        .nickname("源码").status(CommonStatusEnum.DISABLE.getStatus()).sex(SexEnum.FEMALE.getSex()).build()
        );
        // 输出
        ExcelUtils.write(response, "用户导入模板.xls", "用户列表", UserImportExcelVO.class, list);
    }

    @PostMapping("/import")
    @Operation(summary = "导入用户")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true),
            @Parameter(name = "updateSupport", description = "是否支持更新，默认为 false", example = "true")
    })
    @PreAuthorize("@ss.hasPermission('system:user:import')")
    public CommonResult<UserImportRespVO> importExcel(@RequestParam("file") MultipartFile file,
                                                      @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {
        List<UserImportExcelVO> list = ExcelUtils.read(file, UserImportExcelVO.class);
        return success(userService.importUserList(list, updateSupport));
    }

    @PostMapping("/student/import")
    @Operation(summary = "导入学生")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true),
    })
    @PreAuthorize("@ss.hasPermission('system:user:import')")
    public CommonResult<String> importExcelStudent(@RequestParam("file") MultipartFile file) throws Exception {
        List<UserStudentExcelVO> list = ExcelUtils.read(file, UserStudentExcelVO.class);
        List<AdminUserDO> userList = new ArrayList<>();
        if (!list.isEmpty()) {
            list.stream().forEach(sysStudentUser ->{
                AdminUserDO user = new AdminUserDO();
                user.setUserType(2);
                user.setUsername(sysStudentUser.getUsername());
                user.setNickname(sysStudentUser.getNickname());
                user.setMobile(sysStudentUser.getMobile());
                user.setStatusType(UserImportEnums.getStatusByName(sysStudentUser.getStatusType()));
                user.setSex(Integer.valueOf(sysStudentUser.getSex()));
                user.setStatus(Integer.valueOf(sysStudentUser.getStatus()));
                user.setUserNo(sysStudentUser.getUserNo());
                userList.add(user);
            });
        }
        return success(userService.importUserStudentTeacher(userList));
    }

    @PostMapping("/teacher/import")
    @Operation(summary = "导入教师")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true)
    })
    @PreAuthorize("@ss.hasPermission('system:user:import')")
    public CommonResult<String> importExcelTeacher(@RequestParam("file") MultipartFile file) throws Exception {
        List<UserTeacherExcelVO> list = ExcelUtils.read(file, UserTeacherExcelVO.class);
        List<AdminUserDO> userList = new ArrayList<>();
        if (!list.isEmpty()) {
            list.stream().forEach(sysStudentUser ->{
                AdminUserDO user = new AdminUserDO();
                user.setUsername(sysStudentUser.getUsername());
                user.setUserNo(sysStudentUser.getUserNo());
                user.setNickname(sysStudentUser.getNickname());
                user.setEmail(sysStudentUser.getEmail());
                user.setMobile(sysStudentUser.getMobile());
                user.setSex(Integer.valueOf(sysStudentUser.getSex()));
                user.setStatus(Integer.valueOf(sysStudentUser.getStatus()));
                user.setBirthDate(LocalDateTime.parse(sysStudentUser.getBirthDate()));
                user.setStatusType(UserImportEnums.getStatusByName(sysStudentUser.getStatusType()));
                user.setUserType(1);
                userList.add(user);
            });
        }
        return success(userService.importUserStudentTeacher(userList));
    }

    @GetMapping("/student/importTemplate")
    @Operation(summary = "导出学生")
    @PreAuthorize("@ss.hasPermission('system:user:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void importStudentTemplate(HttpServletResponse response) throws IOException {
        List<UserStudentExcelVO> list = new ArrayList<>();
        list.add(UserStudentExcelVO.builder().username("yunai").nickname("导入前请删除").mobile("18999999999")
                .sex("1").status("0").userNo("10001").statusType("学生").build());
        list.add(UserStudentExcelVO.builder().username("yuanma").nickname("请删除本行数据").mobile("18999999999")
                .sex("2").status("1").userNo("10002").statusType("学员").build());
        // 输出 Excel
        ExcelUtils.write(response, "学生模板.xls", "数据", UserStudentExcelVO.class,list);
    }


    @GetMapping("/teacher/importTemplate")
    @Operation(summary = "导出教师模板")
    @PreAuthorize("@ss.hasPermission('system:user:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void importTeacherTemplate(HttpServletResponse response) throws IOException {
        List<UserTeacherExcelVO> list = new ArrayList<>();
        list.add(UserTeacherExcelVO.builder().username("yunai").userNo("10001").nickname("导入前请删除").email("18999999999@qq.com").mobile("18999999999")
                .sex("1").status("0").birthDate("2020-01-01 00:00:00").statusType("教师").build());
        list.add(UserTeacherExcelVO.builder().username("yuanma").userNo("10002").nickname("请删除本行数据").email("18999999999@qq.com").mobile("18999999999")
                .sex("2").status("1").birthDate("2020-01-01 00:00:00").statusType("培训教师").build());
        // 输出 Excel
        ExcelUtils.write(response, "教师模板.xls", "数据", UserTeacherExcelVO.class,list);
    }

}
