package com.ruoyi.web.controller.system;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.lang.LangUnit;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.utils.Global;
import com.ruoyi.framework.web.service.EmailService;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.LocaleResolver;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@Api(tags = "3 登录验证")
@ApiSupport(order = 3)
@RestController
public class SysLoginController extends BaseController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private RedisCache redisCache;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    @Autowired
    private Global global;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private LocaleResolver localeResolver;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private EmailService emailService;

    @PostConstruct
    public void init()
    {
        System.out.println("---------------------------Login init");
        // clearLoginCache(); 服务重开 不会断线
    }

    /**
     * 清空
     */
//    public void clearLoginCache()
//    {
//        Collection<String> Rolekeys = redisCache.keys(Constants.LOGIN_TOKEN_ROLE_KEY + "*");
//        redisCache.deleteObject(Rolekeys);
//
//        Collection<String> tokenKeys = redisCache.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
//        redisCache.deleteObject(tokenKeys);
//    }


    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation(value = "3.1 登录")
    @ApiOperationSupport(order = 1)
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody, HttpServletRequest request, HttpServletResponse response)
    {
        AjaxResult ajax = AjaxResult.success();
        String userName = loginBody.getUsername();

        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(), loginBody.getUuid(), request);
        ajax.put(Constants.TOKEN, token);

        //读取配置文件
        if (StringUtils.isNotNull(token) && StringUtils.isNotEmpty(token)){
            SysUser sysUser = userService.selectUserByUserName(userName);
            if (sysUser != null) {
                String langStr  = sysUser.getLanguage();
                if (langStr == null || langStr == ""){
                    langStr = "zh";
                }
                Locale locale = new Locale(langStr);
                localeResolver.setLocale(request, response, locale);
                // 保存用户语言到redis中
                redisCache.setCacheObject(Constants.USER_LANGUAGE_KEY + sysUser.getUserId(), langStr);
            }
        }

        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @ApiOperation(value = "3.2 获取用户信息")
    @ApiOperationSupport(order = 2)
    @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();
        String language = user.getLanguage();
        // 部门名称
        if (StringUtils.isNotNull(language) && StringUtils.isNotEmpty(language) && (language.equals("zh") == false)) {
            //查对应语言部门名称
            String deptNameEn = sysDeptService.selectDeptName(user.getDeptId(), language);
            if (StringUtils.isNotEmpty(deptNameEn)) {
                SysDept sysDept = user.getDept();
                sysDept.setDeptName(deptNameEn);
                user.setDept(sysDept);
            }
        }
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);

        String uuid  = getUserUUID();
        ajax.put("uuid", uuid);

        String rolesStr = roles.toString();
        redisCache.setCacheObject(Constants.LOGIN_TOKEN_ROLE_KEY + uuid, rolesStr, expireTime, TimeUnit.MINUTES);

        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @ApiOperation(value = "3.3 获取路由信息")
    @ApiOperationSupport(order = 3)
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        String userName = getUsername();
        SysUser sysUser = userService.selectUserByUserName(userName);
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus, sysUser.getLanguage()));
    }

    @ApiOperation(value = "3.4 发送找回密码验证码")
    @ApiOperationSupport(order = 4)
    @PostMapping("/sendRestEmailCode")
    public AjaxResult sendRestEmailCode(@RequestParam(required = true) String email)
    {
        AjaxResult ajax = AjaxResult.success();
        String uuid = IdUtils.simpleUUID();
        emailService.sendEmailCode(email, uuid, "重置密码验证码");
        ajax.put("uuid", uuid);
        return ajax;
    }

    @ApiOperation(value = "3.5 重置密码")
    @ApiOperationSupport(order = 5)
    @PostMapping("/restPassword")
    public AjaxResult restPassword(String email, String code, String uuid, String newPassword, HttpServletRequest request)
    {
        emailService.validateEmailCode(email, code, uuid);

        SysUser sysUser = userService.selectUserByEmail(email);

        String language = global.getCurrentLanguage(request);

        if (SecurityUtils.matchesPassword(newPassword, sysUser.getPassword()))
        {
            return error(MessageUtils.message("sysProfile.updatePwd.1002", language));
        }
        if (userService.resetUserPwd(sysUser.getUserName(), SecurityUtils.encryptPassword(newPassword)) > 0)
        {
            return success();
        }
        return error(MessageUtils.message("sysProfile.updatePwd.1003", language));
    }
}
