package com.user.service.web.controller;

import com.base.orbit.constant.UserConstants;
import com.base.orbit.domain.AjaxResult;
import com.base.orbit.domain.enity.SysMenu;
import com.base.orbit.domain.enity.SysRole;
import com.base.orbit.domain.enity.SysUser;
import com.base.orbit.domain.request.UserDTO;
import com.base.orbit.page.TableDataInfo;
import com.base.orbit.utils.DateUtils;
import com.user.service.util.SecurityUtils;
import com.base.orbit.utils.StringUtils;
import com.user.service.service.ISysMenuService;
import com.user.service.service.ISysRoleService;
import com.user.service.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/user")
@Api(tags = "用戶管理")
public class SysUserController extends BaseController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysMenuService menuService;

    /**
     * 添加用户列表
     */
    @PostMapping("/add")
    @ApiOperation(value = "添加用户", httpMethod = "POST", notes = "添加用户信息")
    public AjaxResult add(@ApiParam @Validated @RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhoneNumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setPassWord(SecurityUtils.encryptPassword(user.getPassWord()));
        user.setCreateTime(DateUtils.getNowDate());
        user.setDelFlag(0);
        int val = userService.insertUser(user);
        if (val > 0) {
            return AjaxResult.success(user);
        }
        return AjaxResult.error("添加用户失败");
    }


    /**
     * 删除用户
     */
    @DeleteMapping("/{userIds}")
    @ApiOperation(value = "删除用户", httpMethod = "DELETE", notes = "删除用户")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 获取用户列表
     */
    @GetMapping("selectUserByVo")
    @ApiOperation(value = "查询用户", httpMethod = "GET", notes = "查询用户信息")
    public TableDataInfo selectUserByVo(SysUser vo) {
        startPage();
        List<SysUser> users = userService.selectUserByVo(vo);
        users.stream().forEach(
                user -> {
                    List<SysRole> sysRoles = roleService.selectRolesByUserId(user.getUserId());
                    user.setRoles(sysRoles);
                }
        );
        return getDataTable(users);
    }

    /**
     * 修改用户
     */
    @PostMapping("/edit")
    @ApiOperation(value = "修改用户", httpMethod = "POST", notes = "修改用户")
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        if (StringUtils.isNotEmpty(user.getPhoneNumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        user.setPassWord(SecurityUtils.encryptPassword(user.getPassWord()));
        return toAjax(userService.updateUser(user));
    }

    /**
     * 用户授权角色
     */
    @PostMapping("/authRole")
    @ApiOperation(value = "用户授权角色", httpMethod = "POST", notes = "用户授权角色")
    public AjaxResult insertAuthRole(@RequestBody UserDTO userDTO) {
        List<SysRole> sysRoles = roleService.selectRolesByUserId(userDTO.getUserId());
        if (sysRoles != null && sysRoles.size() > 0) {
            return AjaxResult.error("用户已存在角色，无法分配");
        }
        userService.insertUserAuth(userDTO);
        return success();
    }

    /**
     * 根据用户编号获取授权角色
     */
    @ApiOperation(value = "根据用户编号获取授权角色", httpMethod = "GET", notes = "根据用户编号获取授权角色")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        //  用户可见菜单
        List<SysMenu> sysMenus = menuService.selectMenuList(userId);
        //  所有菜单
        List<SysMenu> menus = menuService.selectMenuList(new SysMenu());
        //  修改菜单可见状态
        List<SysMenu> menuList = upAvailable(sysMenus, menus);
        ajax.put("user", user);
        ajax.put("menus", menuList);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 根据用户可见菜单修改树形菜单可见状态
     *
     * @param sysMenus  用戶可见菜单
     * @param treeMenus 完整树形结构菜单
     * @return
     */
    public List<SysMenu> upAvailable(List<SysMenu> sysMenus, List<SysMenu> treeMenus) {
        for (SysMenu sysMenu : sysMenus) {
            for (SysMenu treeMenu : treeMenus) {
                if (sysMenu.getMenuId().equals(treeMenu.getMenuId())) {
                    treeMenu.setAvailable(true);
                }
            }
        }
        return treeMenus;
    }

    /**
     * 重置密码
     */
    @PostMapping("/resetPwd")
    @ApiOperation(value = "重置密码", httpMethod = "POST", notes = "重置密码")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setPassWord(SecurityUtils.encryptPassword(user.getPassWord()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

}
