package com.bonus.system.controller;

import com.bonus.common.core.constant.CacheConstants;
import com.bonus.common.core.domain.R;
import com.bonus.common.core.enums.UserPermanentEnum;
import com.bonus.common.core.enums.UserStatus;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.utils.poi.ExcelUtil;
import com.bonus.common.core.web.controller.BaseController;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.core.web.page.TableDataInfo;
import com.bonus.common.log.annotation.SysLog;
import com.bonus.common.log.enums.OperaType;
import com.bonus.common.redis.service.RedisService;
import com.bonus.common.security.annotation.InnerAuth;
import com.bonus.common.security.annotation.PreventRepeatSubmit;
import com.bonus.common.security.annotation.RequiresPermissions;
import com.bonus.common.security.annotation.RequiresPermissionsOrInnerAuth;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.system.api.RemoteFileService;
import com.bonus.system.api.domain.SysDept;
import com.bonus.system.api.domain.SysRole;
import com.bonus.system.api.domain.SysUser;
import com.bonus.system.api.model.LoginUser;
import com.bonus.system.domain.UserPasswordHistory;
import com.bonus.system.service.*;
import com.bonus.system.warning.WebSocketHandler;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
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 java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author bonus
 */
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysPermissionService permissionService;

    @Autowired
    private ISysConfigService configService;

    @Resource
    private PasswordValidatorService passwordValidatorService;

    @Resource
    private RedisService redisService;

    @Resource
    private WebSocketHandler webSocketHandler;


    @Autowired
    private ISysLogService sysLogService;

    @Autowired
    RemoteFileService remoteFileService;

    /**
     * 获取用户列表
     */
    //@RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth(isUser = false), requiresPermissions = @RequiresPermissions("system:user:list"))
    @GetMapping("/list")
    @SysLog(title = "用户管理", businessType = OperaType.QUERY, logType = 0, module = "系统管理->用户管理", details = "查询用户列表")
    public TableDataInfo list(SysUser user) {
        try {
            startPage();
            List<SysUser> list = userService.selectUserList(user);
            return getDataTable(list);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return getDataTableError(new ArrayList<>());
    }
    @RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @RequiresPermissions("system:user:list"))
    @GetMapping("/list_all")
    @SysLog(title = "用户管理", businessType = OperaType.QUERY, logType = 0, module = "系统管理->用户管理", details = "查询用户列表")
    public TableDataInfo listAll(SysUser user) {
        try {
            user .setQueryTyoe(2);
            List<SysUser> list = userService.selectUserList(user);
            return getDataTable(list);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return getDataTableError(new ArrayList<>());
    }


    @RequiresPermissions("system:user:export")
    @PostMapping("/export")
    @SysLog(title = "用户管理", businessType = OperaType.EXPORT, logType = 0, module = "系统管理->用户管理", details = "导出用户信息")
    public void export(HttpServletResponse response, SysUser user) {
        try {
            List<SysUser> list = userService.selectUserList(user);
            ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
            util.exportExcel(response, list, "用户数据");
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
    }

    @PostMapping("/importData")
    @SysLog(title = "用户管理", businessType = OperaType.IMPORT, logType = 0, module = "系统管理->用户管理", details = "导入用户信息")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        try {
            ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
            List<SysUser> userList = util.importExcel(file.getInputStream());
            String operName = SecurityUtils.getUsername();
            String message = userService.importUser(userList, updateSupport, operName);

            return success(message);
        } catch (Exception e) {
            logger.error(e.toString(), e);
            return error(e.getMessage());
        }

    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        try {
            ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
            util.importTemplateExcel(response, "用户数据");
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
    }

    /**
     * 获取当前用户信息
     */
    @InnerAuth
    @GetMapping("/info/{username}")
    public R<LoginUser> info(@PathVariable("username") String username) {
        SysUser sysUser = userService.selectUserByUserName(username);
        if (StringUtils.isNull(sysUser)) {
            return R.fail("用户名或密码错误");
        }
        SysDept sysDept = deptService.selectActiveDeptById(sysUser.getCompanyId());
        if (StringUtils.isNull(sysDept)) {
            return R.fail("用户所在公司停用或注销");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);

    }

    /**
     * 获取当前用户信息
     */
    @InnerAuth
    @GetMapping("/infoPhoto/{photoNumber}")
    public R<LoginUser> infoPhotoNumber(@PathVariable("photoNumber") String photoNumber) {
        SysUser sysUser = userService.selectUserByPhotoNumber(photoNumber);
        if (StringUtils.isNull(sysUser)) {
            return R.fail("用户名或密码错误");
        }
        SysDept sysDept = deptService.selectActiveDeptById(sysUser.getCompanyId());
        if (StringUtils.isNull(sysDept)) {
            return R.fail("用户所在公司停用或注销");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);
    }

    @InnerAuth
    @GetMapping("/kitchenStaff/{photoNumber}")
    public R<LoginUser> getKitchenStaffInfoByPhone(@PathVariable("photoNumber") String photoNumber) {
        SysUser sysUser = userService.selectKitchenStaffByPhotoNumber(photoNumber);
        if (StringUtils.isNull(sysUser)) {
            return R.fail("用户名或密码错误");
        }
        // 权限集合
        Set<String> permissions = permissionService.getDevicePermission(sysUser);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);
    }

    /**
     * 获取当前用户信息
     */
    @InnerAuth
    @GetMapping("/infoEmail/{email}")
    public R<LoginUser> infoEmail(@PathVariable("email") String email) {
        SysUser sysUser = userService.selectUserByEmail(email);
        if (StringUtils.isNull(sysUser)) {
            return R.fail("用户名或密码错误");
        }
        SysDept sysDept = deptService.selectActiveDeptById(sysUser.getCompanyId());
        if (StringUtils.isNull(sysDept)) {
            return R.fail("用户所在公司停用或注销");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);
    }

    /**
     * 注册用户信息
     */
    @InnerAuth
    @PostMapping("/register")
    public R<Boolean> register(@RequestBody SysUser sysUser) {
        String username = sysUser.getUserName();
        final String stringTrue = "true";
        final String configKeyRegisterUser = "sys.account.registerUser";
        if (!(stringTrue.equals(configService.selectConfigByKey(configKeyRegisterUser)))) {
            return R.fail("当前系统没有开启注册功能！");
        }
        if (!userService.checkUserNameUnique(sysUser)) {
            return R.fail("保存用户'" + username + "'失败，注册账号已存在");
        }

        return R.ok(userService.registerUser(sysUser));
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        try {
            SysUser user = userService.selectUserById(SecurityUtils.getUserId());
            user.setAvatar(remoteFileService.getFullFileUrl(user.getAvatar()));
            user.setPhotoUrl(remoteFileService.getFullFileUrl(user.getPhotoUrl()));
            user.setPassword(null);
            // 角色集合
            Set<String> roles = permissionService.getRolePermission(user);
            // 权限集合
            Set<String> permissions = permissionService.getMenuPermission(user);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("user", user);
            ajax.put("roles", roles);
            ajax.put("permissions", permissions);
            return ajax;
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return error("系统异常,请联系管理员");
    }

    /**
     * 根据用户编号获取详细信息
     */
    //@RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @RequiresPermissions("system:user:query"))
    @GetMapping(value = {"/", "/{userId}"})
//    @GetMapping("/{userId:\\d+}")
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        try {
            userService.checkUserDataScope(userId);
            AjaxResult ajax = AjaxResult.success();
            List<SysRole> roles = roleService.selectRoleAll();
            ajax.put("roles", roles);
            ajax.put("posts", postService.selectPostAll());
            if (StringUtils.isNotNull(userId)) {
                SysUser sysUser = userService.selectUserById(userId);
                sysUser.setPassword(null);
                sysUser.setPhotoUrl(remoteFileService.getFullFileUrl(sysUser.getPhotoUrl()));
                ajax.put(AjaxResult.DATA_TAG, sysUser);
                ajax.put("postIds", postService.selectPostListByUserId(userId));
                ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
            }
            return ajax;
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return error("系统异常,请联系管理员");
    }

    /**
     * 根据用户编号列表获取用户列表
     */
    @RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @RequiresPermissions("system:user:query"))
    @GetMapping("/ids/{userIds}")
    @SysLog(title = "用户管理", businessType = OperaType.QUERY, logType = 0, module = "系统管理->用户管理", details = "根据ids获取用户列表")
    public AjaxResult getUsers(@PathVariable("userIds") Long[] userIds) {
        try {
            AjaxResult ajax = AjaxResult.success();
            List<SysUser> sysUsers = userService.selectUsersByIds(userIds);
            ajax.put(AjaxResult.DATA_TAG, sysUsers);
            return ajax;
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return error("系统异常,请联系管理员");
    }

    /**
     * 新增用户
     */
    @RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @RequiresPermissions("system:user:add"))
    @PostMapping
    @SysLog(title = "用户管理", businessType = OperaType.INSERT, logType = 0, module = "系统管理->用户管理", details = "新增用户信息")
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        try {
            deptService.checkDeptDataScope(user.getDeptId());
            roleService.checkRoleDataScope(user.getRoleIds());
            if (!userService.checkUserNameUnique(user)) {
                return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
            } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
                return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
            } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
                return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
            } else if (Objects.equals(user.getIsBuiltIn(), "0")){
                return error("内置用户不允许添加");
            }
            /*String pwd = ValidateUtils.isPwd(user.getPassword());
            if (StringUtils.isNotEmpty(pwd)) {
                return error("新增用户'" + user.getUserName() + "'失败，" + pwd);
            }*/
            AjaxResult ajaxResult = passwordValidatorService.validatePassword(-100L, user.getUserName(), "", user.getPassword());
            if (ajaxResult.isError()) {
                return ajaxResult;
            }
            user.setCreateBy(SecurityUtils.getUsername());
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
            userService.setUserStatus(user);
            return toAjax(userService.insertUser(user));
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return error("系统异常,请联系管理员");
    }

    /**
     * 修改用户
     */
    //@RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @RequiresPermissions("system:user:edit"))
    @PostMapping("/edit")
    @SysLog(title = "用户管理", businessType = OperaType.UPDATE, logType = 0, module = "系统管理->用户管理", details = "修改用户信息")
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        try {
            userService.checkUserAllowed(user);
            userService.checkUserDataScope(user.getUserId());
            deptService.checkDeptDataScope(user.getDeptId());
            roleService.checkRoleDataScope(user.getRoleIds());
            if (!userService.checkUserNameUnique(user)) {
                return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
            } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
                return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
            } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
                return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
            }else if (Objects.equals(user.getIsBuiltIn(), "0")){
                return error("内置用户不允许修改");
            }
            user.setUpdateBy(SecurityUtils.getUsername());
            userService.setUserStatus(user);
            return toAjax(userService.updateUser(user));
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return error("系统异常,请联系管理员");
    }

    /**
     * 删除用户
     */
    @RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @RequiresPermissions("system:user:remove"))
    @PostMapping("/delete/{userIds}")
    @SysLog(title = "用户管理", businessType = OperaType.DELETE, logType = 0, module = "系统管理->用户管理", details = "删除用户信息")
    public AjaxResult remove(@PathVariable("userIds") Long[] userIds) {
        try {
            if (ArrayUtils.contains(userIds, SecurityUtils.getUserId())) {
                return error("当前用户不能删除");
            }
            return toAjax(userService.deleteUserByIds(userIds));
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return error("系统异常,请联系管理员");
    }

    /**
     * 重置密码
     */
    @RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @RequiresPermissions("system:user:edit"))
    @PostMapping("/resetPwd")
    @SysLog(title = "用户管理", businessType = OperaType.UPDATE, logType = 0, module = "系统管理->用户管理", details = "重置用户密码")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        try {
            SysUser sysUser = userService.selectUserById(user.getUserId());
            AjaxResult ajaxResult = passwordValidatorService.validatePassword(sysUser.getUserId(), sysUser.getUserName(), sysUser.getPassword(), user.getPassword());
            if (ajaxResult.isError()) {
                return ajaxResult;
            }
            userService.checkUserAllowed(user);
            userService.checkUserDataScope(user.getUserId());
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
            user.setUpdateBy(SecurityUtils.getUsername());
            UserPasswordHistory userPasswordHistory = new UserPasswordHistory();
            userPasswordHistory.setUserId(user.getUserId());
            userPasswordHistory.setChangeUser(SecurityUtils.getUserId());
            userPasswordHistory.setNewPassword(user.getPassword());
            userPasswordHistory.setOldPassword(sysUser.getPassword());
            passwordValidatorService.addPasswordExpiry(userPasswordHistory);
            return toAjax(userService.resetPwd(user));
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return error("系统异常,请联系管理员");
    }

    /**
     * 状态修改
     */
    @RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @RequiresPermissions("system:user:edit"))
   @PostMapping("/changeStatus")
    @SysLog(title = "用户管理", businessType = OperaType.UPDATE, logType = 0, module = "系统管理->用户管理", details = "修改用户状态")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        try {
            userService.checkUserAllowed(user);
            userService.checkUserDataScope(user.getUserId());
            user.setUpdateBy(SecurityUtils.getUsername());
            return toAjax(userService.updateUserStatus(user));
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return error("系统异常,请联系管理员");
    }

    /**
     * 根据用户编号获取授权角色
     */
    @RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @RequiresPermissions("system:user:query"))
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        try {
            AjaxResult ajax = AjaxResult.success();
            SysUser user = userService.selectUserById(userId);
            List<SysRole> roles = roleService.selectRolesByUserId(userId);
            ajax.put("user", user);
            ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
            return ajax;
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return error("系统异常,请联系管理员");
    }

    /**
     * 用户授权角色
     */
    @RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @RequiresPermissions("system:user:edit"))
   @PostMapping("/authRole/edit")
    @SysLog(title = "用户管理", businessType = OperaType.GRANT, logType = 0, module = "系统管理->用户管理", details = "用户授权角色")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        try {
            userService.checkUserDataScope(userId);
            roleService.checkRoleDataScope(roleIds);
            userService.insertUserAuth(userId, roleIds);
            return success();
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return error("系统异常,请联系管理员");
    }

    /**
     * 获取部门树列表
     */
    @RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @RequiresPermissions("system:user:list"))
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept) {
        try {
            return success(deptService.selectDeptTreeList(dept));
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return error("系统异常,请联系管理员");
    }

    /**
     * 查询部门人员树列表
     */
    //@RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @RequiresPermissions("system:user:list"))
    @PostMapping("/deptUserTree")
    public AjaxResult deptUserTree(@RequestBody SysUser sysUser) {
        try {
            return success(deptService.selectDeptUserTree(sysUser));
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return error("系统异常,请联系管理员");
    }

    /**
     * 修改用户审批状态
     */
    @RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @RequiresPermissions("system:user:approval"))
    @PostMapping("/approvalStatus")
    public AjaxResult approvalStatus(@RequestBody SysUser user) {
        try {
            return success(userService.approvalStatus(user.getUserId()));
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return error("系统异常,请联系管理员");
    }


    /**
     * 修改用户审批状态
     */
    @RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @RequiresPermissions("system:user:systemUpdateUser"))
    @PostMapping("/systemUpdateUser")
    public AjaxResult systemUpdateUser(@RequestBody SysUser user) {
        try {
            return success(userService.systemUpdateUser(user));
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return error("系统异常,请联系管理员");
    }

    @GetMapping("/checkPasswordStatus")
    public AjaxResult checkPasswordStatus() {
        // 1. 先检查是否是首次登录
        boolean firstLoginResult = passwordValidatorService.checkFirstLogin();
        if (firstLoginResult) {
            return AjaxResult.success("首次登录需要修改密码", true);
        }
        // 2. 再检查密码是否已过期
        boolean passwordExpiryResult = passwordValidatorService.checkPasswordExpiry();
        // 如果密码已过期，返回密码过期的提示
        if (passwordExpiryResult) {
            return AjaxResult.success("密码已过期，需要修改密码", true);
        }
        // 3. 如果都不需要操作，返回成功
        return AjaxResult.success(false);
    }

    /**
     * 查询被锁定的用户
     * @return
     */

    @GetMapping("/getLockUser")
    public AjaxResult getLockUser() {
        Set<String> pwdErrCnt = redisService.getKeysByPrefix(CacheConstants.REDIS_KEY);
        List<Map<String,Object>> list = new ArrayList<>();
        for (String key : pwdErrCnt) {
            Map<String,Object> map = new HashMap<>();
            map.put("userName", key.split(":")[1]);
            long time = redisService.getExpire(key);
            map.put("time", time/60+1);
            list.add(map);
        }
        // 3. 如果都不需要操作，返回成功
        return AjaxResult.success(list);
    }

    @PostMapping("/delLockUser")
    public AjaxResult delLockUser(@RequestBody String[] userName) {
        for (String name : userName) {
            String key = CacheConstants.REDIS_KEY + name;
            if (redisService.hasKey(key)) {
                redisService.deleteObject(key);
            }
        }
        return AjaxResult.success();
    }

    @PostMapping("/confirmPassword")
    public AjaxResult confirmPassword(@RequestBody SysUser user) {
        Long userId = SecurityUtils.getUserId();
        user.setUserId(userId);
        SysUser sysUser = userService.selectUserById(user.getUserId());
        boolean b = SecurityUtils.matchesPassword(user.getPassword(), sysUser.getPassword());
        return b? success():error("密码错误");
    }
}
