package com.bonus.system.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.bonus.common.core.constant.ValidateUtils;
import com.bonus.common.log.annotation.SysLog;
import com.bonus.common.log.enums.OperaType;
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.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.bonus.common.core.domain.R;
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.security.annotation.InnerAuth;
import com.bonus.common.security.annotation.RequiresPermissions;
import com.bonus.common.security.utils.SecurityUtils;
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.service.ISysConfigService;
import com.bonus.system.service.ISysDeptService;
import com.bonus.system.service.ISysPermissionService;
import com.bonus.system.service.ISysPostService;
import com.bonus.system.service.ISysRoleService;
import com.bonus.system.service.ISysUserService;

/**
 * 用户信息
 *
 * @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;

    /**
     * 获取用户列表
     */
    @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<>());
    }

    @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("系统异常,请联系管理员");
    }

    @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("用户名或密码错误");
        }
        // 角色集合
        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();
        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser")))) {
            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());
            // 角色集合
            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("系统异常,请联系管理员");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @RequiresPermissions("system:user:query")
    @GetMapping(value = {"/", "/{userId}"})
    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("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
            ajax.put("posts", postService.selectPostAll());
            if (StringUtils.isNotNull(userId)) {
                SysUser sysUser = userService.selectUserById(userId);
                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("系统异常,请联系管理员");
    }

    /**
     * 新增用户
     */
    @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() + "'失败，邮箱账号已存在");
            }
            String pwd = ValidateUtils.isPwd(user.getPassword());
            if (StringUtils.isNotEmpty(pwd)) {
                return error("新增用户'" + user.getUserName() + "'失败，" + pwd);
            }
            user.setCreateBy(SecurityUtils.getUsername());
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
            return toAjax(userService.insertUser(user));
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return error("系统异常,请联系管理员");
    }

    /**
     * 修改用户
     */
    @RequiresPermissions("system:user:edit")
    @PutMapping
    @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() + "'失败，邮箱账号已存在");
            }
            user.setUpdateBy(SecurityUtils.getUsername());
            return toAjax(userService.updateUser(user));
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return error("系统异常,请联系管理员");
    }

    /**
     * 删除用户
     */
    @RequiresPermissions("system:user:remove")
    @DeleteMapping("/{userIds}")
    @SysLog(title = "用户管理", businessType = OperaType.DELETE, logType = 0, module = "系统管理->用户管理", details = "删除用户信息")
    public AjaxResult remove(@PathVariable 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("系统异常,请联系管理员");
    }

    /**
     * 重置密码
     */
    @RequiresPermissions("system:user:edit")
    @PutMapping("/resetPwd")
    @SysLog(title = "用户管理", businessType = OperaType.UPDATE, logType = 0, module = "系统管理->用户管理", details = "重置用户密码")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        try {
            userService.checkUserAllowed(user);
            userService.checkUserDataScope(user.getUserId());
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
            user.setUpdateBy(SecurityUtils.getUsername());
            return toAjax(userService.resetPwd(user));
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return error("系统异常,请联系管理员");
    }

    /**
     * 状态修改
     */
    @RequiresPermissions("system:user:edit")
    @PutMapping("/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("系统异常,请联系管理员");
    }

    /**
     * 根据用户编号获取授权角色
     */
    @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("系统异常,请联系管理员");
    }

    /**
     * 用户授权角色
     */
    @RequiresPermissions("system:user:edit")
    @PutMapping("/authRole")
    @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("系统异常,请联系管理员");
    }

    /**
     * 获取部门树列表
     */
    @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("系统异常,请联系管理员");
    }

    /**
     * 用户关联班组
     * @return AjaxResult
     * @author cwchen
     * @date 2024/7/15 14:54
     */
    @RequiresPermissions("system:user:associationTeam")
    @PostMapping("/associationTeam")
    @SysLog(title = "用户管理", businessType = OperaType.GRANT, logType = 0, module = "系统管理->用户管理", details = "关联班组")
    public AjaxResult userAssociationTeam(@RequestBody SysUser user) {
       return userService.userAssociationTeam(user);
    }

    /**
     * 获取项目部树
     */
    @RequiresPermissions("system:user:list")
    @GetMapping("/departTree")
    public AjaxResult departTree(SysDept dept) {
        try {
            return success(deptService.selectDepartTreeList(dept));
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return error("系统异常,请联系管理员");
    }
}
