package com.qs.mp.web.controller.system;


import com.qs.mp.common.constant.Constants;
import com.qs.mp.common.core.domain.AjaxResult;
import com.qs.mp.common.core.domain.model.LoginBody;
import com.qs.mp.common.enums.UserIdentityEnum;
import com.qs.mp.framework.security.handle.HostHolder;
import com.qs.mp.framework.web.service.SysLoginService;
import com.qs.mp.framework.web.service.SysPermissionService;
import com.qs.mp.sms.domain.SmsCode;
import com.qs.mp.system.domain.SysMenu;
import com.qs.mp.system.domain.SysUser;
import com.qs.mp.system.service.ISysMenuService;
import com.qs.mp.system.service.ISysUserService;
import com.qs.mp.utils.SecurityUtils;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
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;

/**
 * 登录验证
 *
 * @author ygp
 */
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private HostHolder hostHolder;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        //校验验证码
        loginService.validateCaptcha(loginBody.getUsername(), loginBody.getCode(),
            loginBody.getUuid());

        // 生成令牌
        Map<String, String> result = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid(), loginBody.getIdentity());
        for (String key : result.keySet()) {
            ajax.put(key, result.get(key));
        }
        return ajax;
    }

    @PostMapping("/wxlogin")
    public AjaxResult wxlogin(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        Map<String, String> result = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
            loginBody.getUuid(), loginBody.getIdentity());
        for (String key : result.keySet()) {
            ajax.put(key, result.get(key));
        }
        return ajax;
    }

    @PostMapping("/auth/mobile")
    public AjaxResult login(@RequestBody SmsCode smsCode)
    {
        Pattern codePattern = Pattern.compile("^[0-9]{6}");
        if (!codePattern.matcher(smsCode.getCode()).matches()) {
            return AjaxResult.error("请输入6位验证码");
        }
        SysUser sysUser = sysUserService.selectUserByUserName(smsCode.getMobile());
        if (null == sysUser) {
            if (smsCode.getIdentity() != UserIdentityEnum.USER.ordinal()) {
                return AjaxResult.error("账号不存在");
            }
            // C端直接注册新用户
            sysUser = new SysUser();
            sysUser.setUserName(smsCode.getMobile());
            sysUser.setNickName(smsCode.getMobile());
            sysUser.setPhonenumber(smsCode.getMobile());
            sysUserService.registerUser(sysUser);
        }

        AjaxResult ajax = AjaxResult.success();
        Map<String, String> result = loginService.login(smsCode);
        for (String key : result.keySet()) {
            ajax.put(key, result.get(key));
        }
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        List<SysMenu> permMenus = menuService.getChildPerms(menus, 0);
        return AjaxResult.success(menuService.buildMenus(permMenus));
    }
}
