package com.bs.web.controller.system;

import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bs.common.constant.Constants;
import com.bs.common.core.domain.entity.SysRole;
import com.bs.common.core.domain.entity.SysTenant;
import com.bs.common.core.domain.entity.SysUser;
import com.bs.common.core.domain.model.LoginUser;
import com.bs.framework.web.service.SysLoginService;
import com.bs.framework.web.service.SysPermissionService;
import com.bs.framework.web.service.TokenService;
import com.bs.system.domain.SysUserRole;
import com.bs.system.mapper.SysRoleMapper;
import com.bs.system.mapper.SysUserMapper;
import com.bs.system.mapper.SysUserRoleMapper;
import com.bs.system.service.ISysUserService;
import io.swagger.util.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.bs.common.core.controller.BaseController;
import com.bs.common.core.domain.AjaxResult;
import com.bs.common.core.domain.model.RegisterBody;
import com.bs.common.utils.StringUtils;
import com.bs.framework.web.service.SysRegisterService;
import com.bs.system.service.ISysConfigService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 注册验证
 * 
 * @author bs
 */
@RestController
public class SysRegisterController extends BaseController
{
    @Autowired
    private SysRegisterService registerService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysPermissionService permissionService;
    @PostMapping("/register")
    public AjaxResult register(@RequestBody RegisterBody user)
    {
//        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser"))))
//        {
//            return error("当前系统没有开启注册功能！");
//        }
        String msg = registerService.register(user);
        if (Validator.isNotEmpty(msg)) {
            return error(msg);
        }
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserName,user.getUsername());
        List<SysUser> sysUsers = userMapper.selectList(wrapper);
        SysUser sysUser = sysUsers.get(0);
        userService.insertUserAuth(sysUser.getUserId(), new Long[]{2L});
        LoginUser loginUser = createLoginUser(sysUser, null);
        String token = tokenService.createToken(loginUser);
        AjaxResult ajax = AjaxResult.success();
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    @GetMapping("/ceshi")
    public AjaxResult ceshi()
    {
//        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser"))))
//        {
//            return error("当前系统没有开启注册功能！");
//        }
        RegisterBody user = new RegisterBody();
        user.setPassword("123456");
        user.setUsername("测试手机号5");
        user.setPhonenumber("18396103855");
//        INSERT INTO sys_user (user_id, dept_id, user_name, nick_name, email, phonenumber, sex, avatar, password, status, review_status,
//            tenant_id, user_type, create_time)
//    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
//        09:56:48.703 [http-nio-8089-exec-19] DEBUG c.b.s.m.S.insertNew - [debug,137] - ==> Parameters: 1737683808874(Long), 0(Long),
//            测试手机号2(String), 测试手机号2(String), null, 18396103859(String), null, null

        String msg = registerService.register(user);
        if (Validator.isNotEmpty(msg)) {
            return error(msg);
        }
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserName,user.getUsername());
        List<SysUser> sysUsers = userMapper.selectList(wrapper);
        SysUser sysUser = sysUsers.get(0);
        userService.insertUserAuth(sysUser.getUserId(), new Long[]{2L});
        LoginUser loginUser = createLoginUser(sysUser, null);
        String token = tokenService.createToken(loginUser);
        AjaxResult ajax = AjaxResult.success();
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    public LoginUser createLoginUser(SysUser user, SysTenant tenant) {
        //查询用户下的权限
        LambdaQueryWrapper<SysUserRole> userRoleWrapper = new LambdaQueryWrapper<>();
        userRoleWrapper.select(SysUserRole::getRoleId);
        userRoleWrapper.eq(SysUserRole::getUserId,user.getUserId());
        List<Object> roleIds = sysUserRoleMapper.selectObjs(userRoleWrapper);
        //查询用户下的权限
        LambdaQueryWrapper<SysRole> roleWrapper = new LambdaQueryWrapper<>();
        roleWrapper.in(SysRole::getRoleId,roleIds);
        user.setRoles(sysRoleMapper.selectList(roleWrapper));
        return new LoginUser(user.getUserId(),  user.getDeptId(), user, permissionService.getMenuPermission(user));
    }
}
