package cn.sh.stc.sict.cloud.upms.controller.web;

import cn.hutool.core.util.StrUtil;
import cn.sh.stc.sict.cloud.common.core.constant.Constant;
import cn.sh.stc.sict.cloud.common.core.util.NumberUtil;
import cn.sh.stc.sict.cloud.common.security.util.SecurityUtils;
import cn.sh.stc.sict.cloud.upms.dto.CurrentUser;
import cn.sh.stc.sict.cloud.upms.dto.UserDTO;
import cn.sh.stc.sict.cloud.upms.model.HpMenu;
import cn.sh.stc.sict.cloud.upms.model.HpRole;
import cn.sh.stc.sict.cloud.upms.model.HpUserRole;
import cn.sh.stc.sict.cloud.upms.service.HpMenuService;
import cn.sh.stc.sict.cloud.upms.service.HpRoleService;
import cn.sh.stc.sict.cloud.upms.service.HpUserRoleService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.sh.stc.sict.cloud.common.core.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import cn.sh.stc.sict.cloud.upms.model.SysUserBase;
import cn.sh.stc.sict.cloud.upms.service.SysUserBaseService;

import java.util.List;


/**
 * 系统基础用户表
 *
 * @author F_xh。
 * @date 2020-12-27 10:34:32
 */
@Slf4j
@RestController
@AllArgsConstructor
@Api(tags = "系统基础用户表")
@RequestMapping("/user/base")
public class SysUserBaseController {

    /**
     * 0. 分页列表[查询]
     * 1. 用户创建（密码）
     * 2. 查询用户的角色
     * 3. 角色配置
     * 4. 重置密码（加密处理）
     */
    private SysUserBaseService sysUserBaseService;
    private HpRoleService hpRoleService;
    private HpUserRoleService hpUserRoleService;
    private HpMenuService hpMenuService;
    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

    @ApiOperation("分页查询 系统基础用户表")
    @GetMapping("/page")
    public R getSysUserBasePage(Page page, SysUserBase sysUserBase) {
        return new R<>(sysUserBaseService.page(page, Wrappers.query(sysUserBase)));
    }

    @ApiOperation("新增/修改用户")
    @PostMapping
    public R save(@RequestBody SysUserBase userBase) {
        if (NumberUtil.isNullOrZero(userBase.getId())) {
            if(StrUtil.isBlank(userBase.getUserName())){
                return new R().error("用户名不可为空！");
            }
            String pw = StrUtil.isBlank(userBase.getPasswd()) ? Constant.DEFAULT_PASSWORD : userBase.getPasswd();
            userBase.setPasswd(ENCODER.encode(pw));
        }
        userBase.setStatus(Constant.BYTE_NO);
        sysUserBaseService.saveOrUpdate(userBase);
        return new R<>();
    }

    @ApiOperation("根据 userId 获取用户信息")
    @GetMapping("/info")
    public R getUserInfo(@RequestParam("userId") Long userId) {
        SysUserBase user = sysUserBaseService.getById(userId);
        if (user == null) {
            return new R().error("未找到用户信息！");
        }
        List<HpRole> roleList = hpRoleService.listByUserId(userId);
        UserDTO dto = new UserDTO();
        dto.setUser(user);
        dto.setRoleList(roleList);
        return new R(dto);
    }


    @ApiOperation("获取当前用户信息")
    @GetMapping("/info/current")
    public R getCurrentUserInfo(){
        CurrentUser current = SecurityUtils.getCurrentUser();
        if (current == null) {
            return new R().error("无登录信息！");
        }
        SysUserBase user = sysUserBaseService.getById(current.getId());
        if (user == null) {
            return new R().error("未找到用户信息！");
        }
        List<HpRole> roleList = hpRoleService.listByUserId(current.getId());
        List<HpMenu> menuList = hpMenuService.listByUserId(current.getId());
        UserDTO dto = new UserDTO();
        dto.setUser(user);
        dto.setRoleList(roleList);
        dto.setMenuList(menuList);

        return new R(dto);
    }


    @ApiOperation("设置用户角色信息")
    @PostMapping("/role")
    public R saveUserRole(@RequestBody UserDTO dto) {
        if (NumberUtil.isNullOrZero(dto.getUser().getId())) {
            return new R().error("用户id不可为空！");
        }

        sysUserBaseService.saveDto(dto);
        return new R();
    }

    /**
     * 通过id删除系统基础用户表
     *
     * @return R
     */
    @ApiOperation("删除系统基础用户表")
    @DeleteMapping("/{userId}")
    @Transactional(rollbackFor = Exception.class)
    public R removeById(@PathVariable Long userId) {
        hpUserRoleService.removeByUserId(userId);
        sysUserBaseService.removeById(userId);
        return new R<>();
    }
}
