package com.ruoyi.auth.controller;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.auth.config.Oauth2ClientProperties;
import com.ruoyi.auth.form.AccessTokenVo;
import com.ruoyi.auth.form.LoginKeyBody;
import com.ruoyi.common.core.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.auth.form.LoginBody;
import com.ruoyi.auth.form.RegisterBody;
import com.ruoyi.auth.service.SysLoginService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.auth.AuthUtil;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * token 控制
 * 
 * @author ruoyi
 */
@RestController
public class TokenController
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private Oauth2ClientProperties oauth2ClientProperties;

    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form)
    {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @PostMapping("loginByKey")
    public R<?> loginByKey(@RequestBody LoginKeyBody form)
    {
        // 用户登录
        LoginUser userInfo = sysLoginService.loginByKey(form.getUsername(), form.getKey());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @PostMapping("loginByOauth2")
    public R<?> loginByOauth2(@RequestBody Map<String,String> params)
    /**
     * {
     *     "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsiZGVtby1hcHAiXSwiZXhwIjoxNzI5MTU0MTExLCJ1c2VyX25hbWUiOiJhZG1pbiIsImp0aSI6IjQzNGVkNmI0LWIzN2MtNDliMS04NTczLWZhNmU4YTg5YTUxYSIsImNsaWVudF9pZCI6IkFCQyIsInNjb3BlIjpbInJlYWQiLCJ3cml0ZSJdfQ.U591q4fUaUBtBt5Ex-S2daM7DIl9-Ov0MsveymNfHxI",
     *     "token_type": "bearer",
     *     "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsiZGVtby1hcHAiXSwidXNlcl9uYW1lIjoiYWRtaW4iLCJzY29wZSI6WyJyZWFkIiwid3JpdGUiXSwiYXRpIjoiNDM0ZWQ2YjQtYjM3Yy00OWIxLTg1NzMtZmE2ZThhODlhNTFhIiwiZXhwIjoxNzMxNjQ5OTY4LCJqdGkiOiJiODFhNmJkMC02ZDQzLTQ4M2QtOThmMy1hZWIxNDcyZDUwNzciLCJjbGllbnRfaWQiOiJBQkMifQ.0uMYVqW1G7j0chwxIdWGwpjDr12ogZPcD1iQfPsAs5k",
     *     "expires_in": 7198,
     *     "scope": "read write",
     *     "account_info": {
     *         "id": 1,
     *         "clientId": "ABC",
     *         "username": "admin",
     *         "mobile": "1232378743",
     *         "email": "abc@123.com"
     *     }
     * }
     */
    {
        if (params.containsKey("code") && StringUtils.isNotBlank(params.get("code"))){
            RestTemplate restTemplate = new RestTemplate();
            String url = oauth2ClientProperties.getAccessTokenUri();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
            map.add("grant_type", "authorization_code");
            map.add("code", params.get("code"));
            map.add("redirect_uri", oauth2ClientProperties.getRedirectUri());
            map.add("client_id", oauth2ClientProperties.getClientId());
            map.add("client_secret", oauth2ClientProperties.getClientSecret());

            HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
            ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
            String body = response.getBody();

            AccessTokenVo accessTokenVo = JSON.parseObject(body, AccessTokenVo.class);
            String accessToken = accessTokenVo.getAccess_token();
            AccessTokenVo.Account_info accountInfo = accessTokenVo.getAccount_info();

            // 用户登录
            LoginUser userInfo = sysLoginService.login(accountInfo);
            // 获取登录token
            Map<String, Object> token = tokenService.createToken(userInfo);
            token.put("checkTokenUri",oauth2ClientProperties.getCheckTokenUri());
            token.put("logoutUri",oauth2ClientProperties.getLogoutUri());
            token.put("oauth2AccessToken",accessToken);
            return R.ok(token);
        }

        throw new ServiceException("用户信息获取失败");
    }


    @GetMapping("oauth2ClientInfo")
    public  R<?> getClientInfo() {
        return R.ok(JSON.toJSON(oauth2ClientProperties));
    }

    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request)
    {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @PostMapping("register")
    public R<?> register(@RequestBody RegisterBody registerBody)
    {
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return R.ok();
    }
}
