package com.taais.system.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.ObjectUtil;
import com.taais.common.core.constant.UserConstants;
import com.taais.common.core.core.domain.CommonResult;
import com.taais.common.core.core.domain.model.LoginUser;
import com.taais.common.core.core.page.PageResult;
import com.taais.common.core.utils.MapstructUtils;
import com.taais.common.core.utils.StreamUtils;
import com.taais.common.core.utils.StringUtils;
import com.taais.common.encrypt.annotation.ApiEncrypt;
import com.taais.common.excel.core.ExcelResult;
import com.taais.common.excel.utils.ExcelUtil;
import com.taais.common.log.annotation.Log;
import com.taais.common.log.enums.BusinessType;
import com.taais.common.security.utils.LoginHelper;
import com.taais.common.tenant.helper.TenantHelper;
import com.taais.common.web.core.BaseController;
import com.taais.system.domain.bo.SysDeptBo;
import com.taais.system.domain.bo.SysPostBo;
import com.taais.system.domain.bo.SysRoleBo;
import com.taais.system.domain.bo.SysUserBo;
import com.taais.system.domain.vo.SysRoleVo;
import com.taais.system.domain.vo.SysUserExportVo;
import com.taais.system.domain.vo.SysUserImportVo;
import com.taais.system.domain.vo.SysUserInfoVo;
import com.taais.system.domain.vo.SysUserVo;
import com.taais.system.domain.vo.UserInfoVo;
import com.taais.system.listener.SysUserImportListener;
import com.taais.system.service.ISysDeptService;
import com.taais.system.service.ISysPostService;
import com.taais.system.service.ISysRoleService;
import com.taais.system.service.ISysTenantService;
import com.taais.system.service.ISysUserService;
import com.mybatisflex.core.mask.MaskManager;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ArrayUtils;
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 java.util.ArrayList;
import java.util.List;

/**
 * 用户信息
 *
 * @author wgk
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    @Resource
    private ISysUserService userService;
    @Resource
    private ISysRoleService roleService;
    @Resource
    private ISysDeptService deptService;
    @Resource
    private ISysPostService postService;
    @Resource
    private ISysTenantService tenantService;

    /**
     * 获取用户列表
     */
    @SaCheckPermission("system:user:list")
    @GetMapping("/list")
    public CommonResult<PageResult<SysUserVo>> list(SysUserBo userBo) {
        return CommonResult.success(userService.selectPage(userBo));
    }

    /**
     * 导出用户列表
     */
    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @SaCheckPermission("system:user:export")
    @PostMapping("/export")
    public CommonResult<Void> export(HttpServletResponse response, SysUserBo userBo) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        List<SysUserVo> list = userService.selectUserList(userBo);
        List<SysUserExportVo> listVo = MapstructUtils.convert(list, SysUserExportVo.class);
        userService.asyncExport(listVo, "用户数据", loginUser);
        return CommonResult.success();
    }

    /**
     * 导入数据
     *
     * @param file          导入文件
     * @param updateSupport 是否更新已存在数据
     */
    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @SaCheckPermission("system:user:import")
    @PostMapping("/importData")
    public CommonResult<Void> importData(MultipartFile file, boolean updateSupport) throws Exception {
        LoginUser loginUser = LoginHelper.getLoginUser();
        userService.asyncImportData(file, updateSupport, loginUser);
        return CommonResult.success();
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil.exportExcel(new ArrayList<>(), "用户数据", SysUserImportVo.class, response);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public CommonResult<UserInfoVo> getInfo() {
        UserInfoVo userInfoVo = new UserInfoVo();
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (LoginHelper.isSuperAdmin()) {
            // 超级管理员 如果重新加载用户信息需清除动态租户
            TenantHelper.clearDynamic();
        }
        SysUserVo user = userService.selectUserById(loginUser.getUserId());
        if (ObjectUtil.isNull(user)) {
            return CommonResult.fail("没有权限访问用户数据!");
        }
        userInfoVo.setUser(user);
        userInfoVo.setPermissions(loginUser.getMenuPermission());
        userInfoVo.setRoles(loginUser.getRolePermission());
        return CommonResult.success(userInfoVo);
    }


    /**
     * 根据用户编号获取详细信息
     */
    @SaCheckPermission("system:user:query")
    @GetMapping(value = {"/", "/{userId}"})
    public CommonResult<SysUserInfoVo> getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        SysUserInfoVo userInfoVo = new SysUserInfoVo();

        SysRoleBo sysRole = new SysRoleBo();
        sysRole.setStatus(UserConstants.ROLE_NORMAL);
        List<SysRoleVo> roles = roleService.selectRoleList(sysRole);
        SysPostBo sysPost = new SysPostBo();
        sysPost.setStatus(UserConstants.POST_NORMAL);
        userInfoVo.setRoles(LoginHelper.isSuperAdmin(userId) ? roles : StreamUtils.filter(roles, r -> !r.isSuperAdmin()));
        userInfoVo.setPosts(postService.selectPostList(sysPost));
        if (ObjectUtil.isNotNull(userId)) {
            //暂时取消脱敏处理
            SysUserVo sysUser;
            try {
                MaskManager.skipMask();
                sysUser = userService.selectUserById(userId);
            } finally {
                MaskManager.restoreMask();
            }
            userInfoVo.setUser(sysUser);

            List<SysRoleVo> userRoles = roleService.selectUserRolesByUserId(userId);
            userInfoVo.setRoleIds(StreamUtils.toList(userRoles, SysRoleVo::getRoleId));
            //userInfoVo.setRoleIds(StreamUtils.toList(sysUser.getRoles(), SysRoleVo::getRoleId));
            userInfoVo.setPostIds(postService.selectPostListByUserId(userId));
        }
        return CommonResult.success(userInfoVo);
    }


    /**
     * 新增用户
     */
    @SaCheckPermission("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public CommonResult<Void> add(@Validated @RequestBody SysUserBo userBo) {
        deptService.checkDeptDataScope(userBo.getDeptId());
        if (!userService.checkUserNameUnique(userBo)) {
            return CommonResult.fail("新增用户'" + userBo.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(userBo.getPhonenumber()) && !userService.checkPhoneUnique(userBo)) {
            return CommonResult.fail("新增用户'" + userBo.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(userBo.getEmail()) && !userService.checkEmailUnique(userBo)) {
            return CommonResult.fail("新增用户'" + userBo.getUserName() + "'失败，邮箱账号已存在");
        }
        if (!tenantService.checkAccountBalance(TenantHelper.getTenantId())) {
            return CommonResult.fail("当前租户下用户名额不足，请您联系管理员增加租户用户数量！");
        }
        userBo.setPassword(BCrypt.hashpw(userBo.getPassword()));
        boolean inserted = userService.insertUser(userBo);
        if (!inserted) {
            return CommonResult.fail("新增用户记录失败！");
        }
        return CommonResult.success();
    }

    /**
     * 修改用户
     */
    @SaCheckPermission("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public CommonResult<Void> edit(@Validated @RequestBody SysUserBo userBo) {
        userService.checkUserAllowed(userBo.getUserId());
        userService.checkUserDataScope(userBo.getUserId());
        deptService.checkDeptDataScope(userBo.getDeptId());
        if (!userService.checkUserNameUnique(userBo)) {
            return CommonResult.fail("修改用户'" + userBo.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(userBo.getPhonenumber()) && !userService.checkPhoneUnique(userBo)) {
            return CommonResult.fail("修改用户'" + userBo.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(userBo.getEmail()) && !userService.checkEmailUnique(userBo)) {
            return CommonResult.fail("修改用户'" + userBo.getUserName() + "'失败，邮箱账号已存在");
        }
        boolean updated = userService.updateUser(userBo);
        if (!updated) {
            return CommonResult.fail("修改用户记录失败！");
        }
        return CommonResult.success();
    }

    /**
     * 删除用户
     */
    @SaCheckPermission("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public CommonResult<Void> remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, LoginHelper.getUserId())) {
            return CommonResult.fail("当前用户不能删除");
        }
        boolean deleted = userService.deleteUserByIds(userIds);
        if (!deleted) {
            return CommonResult.fail("删除用户记录失败！");
        }
        return CommonResult.success();
    }

    /**
     * 重置密码
     */
    @ApiEncrypt
    @SaCheckPermission("system:user:resetPwd")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public CommonResult<Void> resetPwd(@RequestBody SysUserBo user) {
        userService.checkUserAllowed(user.getUserId());
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(BCrypt.hashpw(user.getPassword()));
        boolean reseted = userService.resetPwd(user);
        if (!reseted) {
            return CommonResult.fail("重置密码失败！");
        }
        return CommonResult.success();
    }

    /**
     * 状态修改
     */
    @SaCheckPermission("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public CommonResult<Void> changeStatus(@RequestBody SysUserBo user) {
        userService.checkUserAllowed(user.getUserId());
        userService.checkUserDataScope(user.getUserId());
        boolean updated = userService.updateUserStatus(user);
        if (!updated) {
            return CommonResult.fail("状态修改失败！");
        }
        return CommonResult.success();
    }

    /**
     * 根据用户编号获取授权角色
     */
    @SaCheckPermission("system:user:query")
    @GetMapping("/authRole/{userId}")
    public CommonResult<SysUserInfoVo> authRole(@PathVariable("userId") Long userId) {
        SysUserVo user = userService.selectUserById(userId);
        List<SysRoleVo> roles = roleService.selectRolesByUserId(userId);
        SysUserInfoVo userInfoVo = new SysUserInfoVo();
        userInfoVo.setUser(user);
        userInfoVo.setRoles(LoginHelper.isSuperAdmin(userId) ? roles : StreamUtils.filter(roles, r -> !r.isSuperAdmin()));//超级管理员角色只能id=1的admin用户才能拥有
        return CommonResult.success(userInfoVo);
    }

    /**
     * 用户授权角色
     */
    @SaCheckPermission("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public CommonResult<Void> insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return CommonResult.success();
    }

    /**
     * 获取部门树列表
     */
    @SaCheckPermission("system:user:list")
    @GetMapping("/deptTree")
    public CommonResult<List<Tree<Long>>> deptTree(SysDeptBo dept) {
        return CommonResult.success(deptService.selectDeptTreeList(dept));
    }

    /**
     * 获取部门下的所有用户信息
     */
    @SaCheckPermission("system:user:list")
    @GetMapping("/list/dept/{deptId}")
    public CommonResult<List<SysUserVo>> listByDept(@PathVariable @NotNull Long deptId) {
        return CommonResult.success(userService.selectUserListByDept(deptId));
    }


}
