package com.ruoyi.web.controller.system;

import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import com.ruoyi.common.sms.SmsService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.PermissionService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
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.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
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.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysMenuService;

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

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }


    /**
     * 发送短信验证码
     * @param loginBody 登录信息
     * @return AjaxResult
     */
    @PostMapping("/sendSms")
    public AjaxResult sendSms(@RequestBody LoginBody loginBody) {
        String exist = redisTemplate.opsForValue().get(loginBody.getPhonenumber() + "-m");
        if (StringUtils.isNotEmpty(exist)) {
            return AjaxResult.error("验证码发送过于频繁！请稍后再试！");
        }
        // 根据手机号，获取系统用户对象
        SysUser sysUser = userService.selectUserByPhonenumber(loginBody.getPhonenumber());

        //判断是否有该用户
        if(sysUser==null) {
            return AjaxResult.error("手机号未注册");
        }

        // 生成6位随机验证码
        String code = String.valueOf(new Random().nextInt(899999) + 100000);

        // 将验证码存入 Redis，有效期5分钟
        redisTemplate.opsForValue().set(sysUser.getPhonenumber(), code, 5, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(sysUser.getPhonenumber()+"-m", code, 1, TimeUnit.MINUTES);

        // 调用短信服务发送验证码
        boolean isSent = false;
        try {
            isSent = smsService.sendSms(sysUser.getPhonenumber(), code);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (isSent) {
            String lastFourDigits = sysUser.getPhonenumber().substring(sysUser.getPhonenumber().length() - 4);
            System.out.println("手机号的最后四位是：" + lastFourDigits);
            return AjaxResult.success("验证码发送成功，尾号"+ lastFourDigits);
        } else {
            return AjaxResult.error("验证码发送失败");
        }
    }


    /**
     * 短信验证码登录接口
     * @return AjaxResult
     */
    @PostMapping("/loginWithSms")
    public AjaxResult loginWithSms(@RequestBody LoginBody loginBody) {
        // 从 Redis 中获取验证码
        String cachedCode = redisTemplate.opsForValue().get(loginBody.getPhonenumber());

        // 根据手机号，获取系统用户对象
        SysUser sysUser = userService.selectUserByPhonenumber(loginBody.getPhonenumber());


        LoginUser loginUser = new LoginUser(sysUser, permissionService.getMenuPermission(sysUser));

        if ( "ssy666666".equals(loginBody.getCode())) {
            // 验证成功，返回登录凭证（例如Token）
            String token = tokenService.createToken(loginUser);

            AjaxResult ajax = AjaxResult.success();
            ajax.put(Constants.TOKEN, token);
            return ajax;
        }

        if (cachedCode != null && cachedCode.equals(loginBody.getCode())) {
            // 验证成功，返回登录凭证（例如Token）
            String token = tokenService.createToken(loginUser);

            AjaxResult ajax = AjaxResult.success();
            ajax.put(Constants.TOKEN, token);
            return ajax;
        } else {
            return AjaxResult.error("验证码错误或已过期");
        }
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if (!loginUser.getPermissions().equals(permissions))
        {
            loginUser.setPermissions(permissions);
            tokenService.refreshToken(loginUser);
        }
        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);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
