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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
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.datapermission.core.annotation.DataPermission;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.system.controller.admin.user.dto.UserPageDTO;
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.dept.PostDO;
import cn.iocoder.yudao.module.system.dal.dataobject.position.PositionDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
import cn.iocoder.yudao.module.system.service.dept.PostService;
import cn.iocoder.yudao.module.system.service.position.PositionService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import com.baomidou.mybatisplus.core.metadata.IPage;
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 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.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMap;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

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

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

    @Resource
    private PostService postService;

    @Resource
    private PositionService positionService;

    @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);
    }


    @PutMapping("/update-fieldwork")
    @Operation(summary = "修改用户外勤打卡状态")
    public CommonResult<Boolean> updateFieldwork(@Valid @RequestBody UserUpdateFieldworkReqVO reqVO) {
        userService.updateFieldwork(reqVO.getId(), reqVO.getFieldworkFlag());
        return success(true);
    }

    @GetMapping("/gpsPosition")
    @Operation(summary = "GPS用户全量更新")
    public CommonResult<Boolean> gpsFullUserUpdate() {
        userService.gpsFullUserUpdate();
        return success(true);
    }

    @GetMapping("/page")
    @Operation(summary = "获得用户分页列表")
    @PreAuthorize("@ss.hasPermission('system:user:list')")
    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));
        Map<Long, PostDO> postMap = postService.getDeptMap(convertList(pageResult.getList(), AdminUserDO::getPostIds));
        List<PositionDO> positionDOs = positionService.getPositionList(convertList(pageResult.getList(), AdminUserDO::getPositionId));
        Map<Long, PositionDO> positionMap = convertMap(positionDOs, PositionDO::getId);

        return success(new PageResult<>(UserConvert.INSTANCE.convertList(pageResult.getList(), deptMap, postMap, positionMap),
                pageResult.getTotal()));
    }

    @GetMapping("/page-permission")
    @Operation(summary = "获得用户分页列表 | 无数据权限接口")
    @PreAuthorize("@ss.hasPermission('system:user:list')")
    @DataPermission(enable = false)
    public CommonResult<PageResult<UserRespVO>> getUserPageNoPermission(@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));
        Map<Long, PostDO> postMap = postService.getDeptMap(convertList(pageResult.getList(), AdminUserDO::getPostIds));
        List<PositionDO> positionDOs = positionService.getPositionList(convertList(pageResult.getList(), AdminUserDO::getPositionId));
        Map<Long, PositionDO> positionMap = convertMap(positionDOs, PositionDO::getId);

        return success(new PageResult<>(UserConvert.INSTANCE.convertList(pageResult.getList(), deptMap, postMap, positionMap),
                pageResult.getTotal()));
    }

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

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


    @PostMapping({"/list-all"})
    @Operation(summary = "获取用户精简信息列表", description = "只包含被开启的用户，主要用于前端的下拉选项,无数据权限")
    @DataPermission(enable = false)
    public CommonResult<IPage<UserSimpleRespVO>> getAllUserListByGroupIds(@RequestBody UserPageDTO dto) {
        IPage<UserSimpleRespVO> pageResult = userService.getAllUserListByGroupIds(dto);
        return success(pageResult);
    }

    @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);
        user.setAvatar(StrUtil.isEmpty(user.getAvatar()) ? "" : user.getAvatar() + "?timestamp=" + System.currentTimeMillis());
        // 拼接数据
        DeptDO dept = deptService.getDept(user.getDeptId());

        // 获取职称信息
        PostDO post = new PostDO();
        Set<Long> postIds = user.getPostIds();
        if (postIds != null && !postIds.isEmpty()) {

            ArrayList<Long> list = new ArrayList<>(postIds);
            // 只获配置的首个岗位
            Long postId = list.get(0);

            post = postService.getPost(postId);
        }

        // 获取岗位信息
        PositionDO positionDO = positionService.getPosition(user.getPositionId());

        return success(UserConvert.INSTANCE.convert(user, dept, post, positionDO));
    }

    @GetMapping("/getUserByChildDeptIds")
    @Operation(summary = "获得当前登录用户所在部门及下级部门的用户下拉列表")
    @PreAuthorize("@ss.hasPermission('system:user:query')")
    public CommonResult<List<UserSimpleRespVO>> getUserByChildDeptIds() {

        // 获得当前登录用户信息
        AdminUserDO user = userService.getUser(getLoginUserId());
        List<DeptDO> deptDOS = deptService.getChildDept(user.getDeptId());

        List<AdminUserDO> userDOS = userService.getUserListByDeptIds(convertList(deptDOS, DeptDO::getId), CommonStatusEnum.ENABLE.getStatus());
        userDOS.removeIf(data -> data.getId().equals(getLoginUserId()));

        return success(BeanUtils.toBean(userDOS, UserSimpleRespVO.class));
    }

    @PostMapping("/getByDeptIds")
    @Operation(summary = "获得用户详情")
    @PreAuthorize("@ss.hasPermission('system:user:query')")
    public CommonResult<List<UserRespVO>> getUserByDeptIds(@RequestBody Collection<Long> deptIds) {

        List<UserRespVO> user = userService.getUserByDeptIds(deptIds);

        return success(user);
    }

    @PostMapping("/selectByUserIds")
    @Operation(summary = "通过用户ids获取用户信息列表")
    @PreAuthorize("@ss.hasPermission('system:user:query')")
    public CommonResult<List<UserRespVO>> selectByUserIds(@RequestBody Collection<Long> userIds) {
        List<AdminUserDO> user = userService.selectByUserIds(userIds);
        return success(BeanUtils.toBean(user, UserRespVO.class));
    }


    @PostMapping("/selectByDeptIdsFilterGroupUser")
    @Operation(summary = "通过部门ids获取用户信息列表(过滤掉已在考勤组的用户)")
    @PreAuthorize("@ss.hasPermission('system:user:query')")
    public CommonResult<List<UserRespVO>> selectByDeptIdsFilterGroupUser(@RequestParam(required = false) Long groupId, @RequestBody Collection<Long> deptIds) {

        List<UserRespVO> user = userService.selectByDeptIdsFilterGroupUser(deptIds, groupId);
        return success(user);
    }

    @PostMapping("/getByDeptId")
    @Operation(summary = "获得指定部门开启状态的用户数组（除去当前登录者用户）")
    @Parameter(name = "deptId", description = "部门编号", required = true, example = "117")
    @PreAuthorize("@ss.hasPermission('system:user:query')")
    public CommonResult<List<UserRespVO>> getListUserByDeptId(@RequestParam("deptId") Long deptId) {

        List<AdminUserDO> user = userService.getListUserByDeptId(deptId);

        return success(BeanUtils.toBean(user, UserRespVO.class));
    }

    @PostMapping("/getByDeptId-all")
    @Operation(summary = "获得指定部门开启状态的用户数组（除去当前登录者用户）")
    @Parameter(name = "deptId", description = "部门编号", required = true, example = "117")
    @PreAuthorize("@ss.hasPermission('system:user:query')")
    @DataPermission(enable = false)
    public CommonResult<List<UserRespVO>> getListUserByDeptIdAll(@RequestParam("deptId") Long deptId) {

        List<AdminUserDO> user = userService.getListUserByDeptId(deptId);

        return success(BeanUtils.toBean(user, UserRespVO.class));
    }

    @GetMapping("/getByDeptIdAll")
    @Operation(summary = "获得指定部门及下级部门开启状态的用户数组（除去当前登录者用户）")
    @Parameter(name = "deptId", description = "部门编号", required = true, example = "117")
    @PreAuthorize("@ss.hasPermission('system:user:query')")
    @DataPermission(enable = false)
    public CommonResult<List<UserRespVO>> getUserByDeptIdAll(@RequestParam("deptId") Long deptId) {

        List<DeptDO> deptDOS = deptService.getChildDept(deptId);

        List<AdminUserDO> user = userService.getUserListByDeptIds(convertList(deptDOS, DeptDO::getId), null);
        user = user.stream().filter(data -> !data.getId().equals(getLoginUserId())).collect(Collectors.toList());

        return success(BeanUtils.toBean(user, UserRespVO.class));
    }

    @PostMapping("/getUserListByBirthday")
    @Operation(summary = "获得当天以及当月即将过生日的用户信息")
    @PreAuthorize("@ss.hasPermission('system:user:query')")
    public CommonResult<PageResult<UserBirthdayRespVO>> getUserListByBirthday(@RequestBody UserBirthdayPageReqVO pageReqVO) {

        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("MM-dd"));

        PageResult<UserBirthdayRespVO> pageResult = userService.getUserListByBirthday(pageReqVO);
        pageResult.getList().forEach(data -> {
            if (data.getBirthday().format(DateTimeFormatter.ofPattern("MM-dd")).equals(time)) {
                data.setStatus(1);
            }else if (data.getBirthday().getMonthValue() == LocalDateTime.now().getMonthValue()){
                data.setStatus(2);
            }
        });

        return success(pageResult);
    }

    @GetMapping("/export")
    @Operation(summary = "导出用户")
    @PreAuthorize("@ss.hasPermission('system:user:export')")
    @OperateLog(type = EXPORT)
    public void exportUserList(@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));
        Map<Long, PostDO> postMap = postService.getDeptMap(convertList(list, AdminUserDO::getPostIds));
        List<PositionDO> positionDOs = positionService.getPositionList(convertList(list, AdminUserDO::getPositionId));
        Map<Long, PositionDO> positionMap = convertMap(positionDOs, PositionDO::getId);

        //获取部门名称
        List<DeptDO> deptDO = deptService.getDeptTree();

        //获取岗位名称
        List<PostDO> postDO = postService.getPostList(null, Collections.singleton(CommonStatusEnum.ENABLE.getStatus()));
        postDO.sort(Comparator.comparing(PostDO::getSort));

        // 输出 Excel
        ExcelUtils.write(response, "用户数据.xls", "数据", UserRespVO.class,
                UserConvert.INSTANCE.convertList(list, deptMap, postMap, positionMap),
                1, getDeptNameFun(deptDO),
                2, getPostNameFun(postDO));
    }

    @GetMapping("/get-import-template")
    @Operation(summary = "获得导入用户模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
//        // 手动创建导出 demo
//        List<UserImportExcelVO> list = Arrays.asList(
//                UserImportExcelVO.builder().nickname("XXXX").deptName(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()
//        );

        //获取部门名称
        List<DeptDO> deptDO = deptService.getDeptTree();

        //获取岗位名称
        List<PostDO> postDO = postService.getPostList(null, Collections.singleton(CommonStatusEnum.ENABLE.getStatus()));
        postDO.sort(Comparator.comparing(PostDO::getSort));

        // 输出
        ExcelUtils.write(response, "用户导入模板.xlsx", "用户列表",
                UserImportExcelVO.class, null,
                1, getDeptNameFun(deptDO),
                2, getPostNameFun(postDO));
    }

    @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));
    }

    private List<String> getDeptNameFun(List<DeptDO> deptDO) {

        List<String> deptName = new ArrayList<>();

        for (DeptDO var : deptDO) {

            deptName.add(var.getId() + ":" + var.getName());
        }

        return deptName;
    }

    private List<String> getPostNameFun(List<PostDO> postDO) {

        List<String> postName = new ArrayList<>();

        for (PostDO var : postDO) {

            postName.add(var.getId() + ":" + var.getName());
        }

        return postName;
    }
}
