package com.mcwl.web.controller.system;

import com.alibaba.fastjson2.JSONObject;
import com.mcwl.common.annotation.Anonymous;
import com.mcwl.common.constant.Constants;
import com.mcwl.common.constant.HttpStatus;
import com.mcwl.common.constant.QueueConstants;
import com.mcwl.common.constant.RedisConstants;
import com.mcwl.common.core.domain.AjaxResult;
import com.mcwl.common.core.domain.entity.SysMenu;
import com.mcwl.common.core.domain.entity.SysUser;
import com.mcwl.common.core.domain.model.LoginBody;
import com.mcwl.common.core.domain.model.LoginUser;
import com.mcwl.common.core.domain.model.PhoneLoginBody;
import com.mcwl.common.core.redis.RedisCache;
import com.mcwl.common.utils.CodeUtils;
import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.common.utils.StringUtils;
import com.mcwl.framework.web.service.SysLoginService;
import com.mcwl.framework.web.service.SysPermissionService;
import com.mcwl.framework.web.service.TokenService;
import com.mcwl.system.service.ISysMenuService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

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

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Anonymous
    @GetMapping("/getCode")
    public AjaxResult code(@RequestParam String phone){

        if (StringUtils.isEmpty(phone)){
            return AjaxResult.error(HttpStatus.SHOW_ERROR_MSG,"请输入手机号");
        }

        //校验验证码是否存在
        if (redisCache.hasKey(RedisConstants.CODE_PHONE+phone)){

            return AjaxResult.error(HttpStatus.SHOW_ERROR_MSG,"请勿重复发送");
        }

        //生成验证码
        String s = CodeUtils.generateCaptcha();


        //存储redis
        redisCache.setCacheObject(RedisConstants.CODE_PHONE+phone,s,1, TimeUnit.MINUTES);

        PhoneLoginBody phoneLoginBody = PhoneLoginBody.builder().code(s)
                .phone(phone).build();

        rabbitTemplate.convertAndSend(QueueConstants.CODE_QUEUE, JSONObject.toJSONString(phoneLoginBody), message -> {
            message.getMessageProperties().setMessageId(UUID.randomUUID().toString().replace("-",""));
            return message;
        });

        return AjaxResult.success();

    }

    /**
     * 登录方法
     *
     * @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;
    }



    @PostMapping("/phoneLogin")
    @Anonymous
    public AjaxResult phoneLogin(@RequestBody PhoneLoginBody phoneLoginBody){

        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.phoneLogin(phoneLoginBody.getPhone(),phoneLoginBody.getCode());
        ajax.put(Constants.TOKEN, token);
        return ajax;

    }

    /**
     * 获取用户信息
     *
     * @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));
    }
}
