package com.vctgo.system.controller;

import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.vctgo.common.core.constant.CacheConstants;
import com.vctgo.common.core.domain.R;
import com.vctgo.common.core.utils.StrUtils;
import com.vctgo.common.core.utils.poi.ExcelUtil;
import com.vctgo.common.core.web.controller.BaseController;
import com.vctgo.common.core.web.domain.AjaxResult;
import com.vctgo.common.mybatisplus.aop.TemporaryIgnoreTables;
import com.vctgo.common.redis.service.RedisService;
import com.vctgo.common.security.annotation.InnerAuth;
import com.vctgo.common.security.annotation.RequiresPermissions;
import com.vctgo.common.security.utils.SecurityUtils;
import com.vctgo.system.api.domain.SysPlatformDept;
import com.vctgo.system.api.domain.SysPlatformRole;
import com.vctgo.system.api.domain.SysPlatformUser;
import com.vctgo.system.api.domain.SysTenant;
import com.vctgo.system.api.model.LoginUser;
import com.vctgo.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
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.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author vctgo
 */
@Api(tags = "用户信息")
@RestController
@RequestMapping("/plat/user")
public class SysPlatformUserController extends BaseController {

    @Autowired
    private ISysPlatformUserService userService;

    @Autowired
    private ISysPlatformRoleService roleService;

    @Autowired
    private ISysPlatformDeptService deptService;

    @Autowired
    private ISysPlatformPostService postService;

    @Autowired
    private ISysPlatformPermissionService permissionService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysTenantService sysTenantService;

    @Autowired
    private RedisService redisService;

    /**
     * 获取用户列表
     */
    @RequiresPermissions("system:user:page")
    @GetMapping("/page")
    public AjaxResult list(SysPlatformUser user) {
        IPage<SysPlatformUser> list = userService.selectUserPage(user);
        return AjaxResult.success(list);
    }

    /**
     * 流程管理获取用户列表
     */
    @ApiOperation(value = "获取流程管理用户列表")
    @TemporaryIgnoreTables
    @GetMapping("/process/user/list")
    public AjaxResult processUserList() {
        List<SysPlatformDept> sysPlatformDeptList = userService.processUserList();
        return AjaxResult.success(sysPlatformDeptList);
    }

    /**
     * 内部资料管理获取用户列表
     */
    @ApiOperation(value = "内部资料管理获取用户列表")
    @TemporaryIgnoreTables
    @GetMapping("/profile/user/list")
    public AjaxResult profileUserList() {
        List<SysPlatformDept> sysPlatformDeptList = userService.processUserList();
        return AjaxResult.success(sysPlatformDeptList);
    }

    /**
     * 平台获取流程管理专家列表
     */
    @ApiOperation(value = "平台获取流程管理专家列表")
    @TemporaryIgnoreTables
    @GetMapping("/process/expert/list")
    public AjaxResult processExpertList() {
        return AjaxResult.success(userService.processExpertList());
    }

    /**
     * 全量获取用户列表
     */
//    @RequiresPermissions("system:user:all:list")
    @GetMapping("/allList")
    public AjaxResult userList() {
        SysPlatformUser sysUser = new SysPlatformUser();
        if (SecurityUtils.getTenantId() != 9999L) {
            sysUser.setTenantId(SecurityUtils.getTenantId());
        }
        List<SysPlatformUser> list = userService.selectUserList(new SysPlatformUser());
        return AjaxResult.success(list);
    }

    /**
     * 通过租户id获取特定的用户列表
     */
    @TemporaryIgnoreTables(temporaryIgnoreTables = {"sys_platform_user", "sys_platform_dept"})
//    @RequiresPermissions("system:user:list")
    @GetMapping("/allList/tenantIds")
    public AjaxResult userListByTenantIds(@RequestParam("tenantIds") String tenantIds) {
        return AjaxResult.success(userService.userListByTenantIds(tenantIds));
    }

    @RequiresPermissions("system:user:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysPlatformUser user) {
        List<SysPlatformUser> list = userService.selectUserList(user);
        ExcelUtil<SysPlatformUser> util = new ExcelUtil<SysPlatformUser>(SysPlatformUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @RequiresPermissions("system:user:import")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysPlatformUser> util = new ExcelUtil<SysPlatformUser>(SysPlatformUser.class);
        List<SysPlatformUser> userList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        ExcelUtil<SysPlatformUser> util = new ExcelUtil<>(SysPlatformUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 获取当前用户信息
     */
    @TemporaryIgnoreTables(temporaryIgnoreTables = {"sys_platform_role_menu"})
    @Transactional
    @InnerAuth
    @GetMapping("/info/{username}")
    public R<LoginUser> info(@PathVariable("username") String username) {
        SysPlatformUser sysUser = userService.selectUserByUserName(username);
        if (StrUtils.isNull(sysUser)) {
            return R.fail("用户名或密码错误");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        // 查询租户信息
        SysTenant tenant = sysTenantService.selectSysTenantById(sysUser.getTenantId());
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUserTempalte(sysUser);
        sysUserVo.setSysPlatformUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        if (tenant != null) {
            sysUserVo.setTenantStatus(tenant.getStatus());
        }
        return R.ok(sysUserVo);
    }

    /**
     * 注册用户信息
     */
    @InnerAuth
    @PostMapping("/register")
    public R<Boolean> register(@RequestBody SysPlatformUser 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 用户信息
     */
    @TemporaryIgnoreTables(temporaryIgnoreTables = {"sys_platform_user", "sys_platform_dept"})
    @GetMapping("/name/info/{userId}")
    public R<SysPlatformUser> getUserInfoByUserId(@PathVariable Long userId) {
        return R.ok(userService.selectUserById(userId));
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @TemporaryIgnoreTables(temporaryIgnoreTables = {"sys_platform_user", "sys_platform_dept"})
    @GetMapping("/name/info/permissions")
    public R<String> getPermissions() {
        //调整下查询顺序 将租户id塞入当前查询线程 --或者直接让权限过滤忽略租户查询 毕竟账号id唯一 目前选择直接忽略查询 后续此处修改
        SysPlatformUser user = userService.selectUserById(SecurityUtils.getUserId());
        // 角色集合
        return R.ok(JSONArray.toJSONString(new ArrayList<>(permissionService.getMenuPermission(user))));
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo() {
        //调整下查询顺序 将租户id塞入当前查询线程 --或者直接让权限过滤忽略租户查询 毕竟账号id唯一 目前选择直接忽略查询 后续此处修改
        SysPlatformUser user = userService.selectUserById(SecurityUtils.getUserId());
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        // 查询租户信息
        SysTenant tenant = sysTenantService.selectSysTenantById(user.getTenantId());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        ajax.put("tenantName", tenant == null ? "" : tenant.getTenantName());//系统名称同步租户名称
        return ajax;
    }

    /**
     * 根据用户编号获取详细信息
     */
    @RequiresPermissions("system:user:query")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysPlatformRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysPlatformUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StrUtils.isNotNull(userId)) {
            SysPlatformUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysPlatformRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @RequiresPermissions("system:user:add")
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysPlatformUser user) {
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StrUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StrUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        //默认密码采用随机生成
        String randomPassword = SecurityUtils.randomPassword(6);//随机密码6位
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(randomPassword));
        return userService.insertUser(user) > 0 ? AjaxResult.success(randomPassword) : AjaxResult.error();
    }

    /**
     * 修改用户
     */
    @Transactional
    @RequiresPermissions("system:user:edit")
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysPlatformUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StrUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StrUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        int result = userService.updateUser(user);

        if (result > 0) {
            // 强制该用户退出登录
            Collection<String> keys = redisService.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
            for (String key : keys) {
                LoginUser onlineUser = redisService.getCacheObject(key);
                if (Objects.nonNull(onlineUser)
                        && Objects.nonNull(onlineUser.getUserid())
                        && onlineUser.getUserid().longValue() == user.getUserId().longValue()) {
                    redisService.deleteObject(key);
                }
            }
        }
        return toAjax(result);
    }

    /**
     * 删除用户
     */
    @RequiresPermissions("system:user:remove")
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, SecurityUtils.getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @Transactional
    @RequiresPermissions("system:user:resetPwd")
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysPlatformUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());

        String randomPassword = SecurityUtils.randomPassword(6);//随机密码6位
        user.setPassword(SecurityUtils.encryptPassword(randomPassword));
        user.setUpdateBy(SecurityUtils.getUsername());
        userService.resetPwd(user);

        // 强制该用户退出登录
        Collection<String> keys = redisService.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        for (String key : keys) {
            LoginUser onlineUser = redisService.getCacheObject(key);
            if (Objects.nonNull(onlineUser)
                    && Objects.nonNull(onlineUser.getUserid())
                    && onlineUser.getUserid().longValue() == user.getUserId().longValue()) {
                redisService.deleteObject(key);
            }
        }
        return AjaxResult.success(randomPassword);
    }

    /**
     * 状态修改
     */
    @RequiresPermissions("system:user:changeStatus")
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysPlatformUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(SecurityUtils.getUsername());
        int result = userService.updateUserStatus(user);
        if (result > 0 && "1".equals(user.getStatus())) {
            // 强制该用户退出登录
            Collection<String> keys = redisService.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
            for (String key : keys) {
                LoginUser onlineUser = redisService.getCacheObject(key);
                if (Objects.nonNull(onlineUser)
                        && Objects.nonNull(onlineUser.getUserid())
                        && onlineUser.getUserid().longValue() == user.getUserId().longValue()) {
                    redisService.deleteObject(key);
                }
            }
        }
        return toAjax(result);
    }

    /**
     * 根据用户编号获取授权角色
     */
    @RequiresPermissions("system:user:auth:role")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysPlatformUser user = userService.selectUserById(userId);
        List<SysPlatformRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysPlatformUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @RequiresPermissions("system:user:auth:role")
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        // 强制该用户退出登录
        Collection<String> keys = redisService.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        for (String key : keys) {
            LoginUser onlineUser = redisService.getCacheObject(key);
            if (Objects.nonNull(onlineUser)
                    && Objects.nonNull(onlineUser.getUserid())
                    && onlineUser.getUserid().longValue() == userId.longValue()) {
                redisService.deleteObject(key);
            }
        }
        return success();
    }

    /**
     * 获取部门树列表
     */
    @RequiresPermissions("system:user:deptTree")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysPlatformDept dept) {
        return success(deptService.selectDeptTreeList(dept));
    }

    /**
     * 通过昵称获取所有用户
     */
    @GetMapping("/getUserList/{nickName}")
    public AjaxResult getUserList(@PathVariable("nickName") String nickName) {
        List<SysPlatformUser> list = userService.getUserList(nickName);
        return AjaxResult.success(list);
    }
}
