package cc.mrbird.febs.auth.controller;

import cc.mrbird.febs.auth.form.RegisterBody;
import cc.mrbird.febs.auth.service.impl.SysLoginService;
import cn.hutool.json.JSONObject;
import com.ruoyi.common.core.domain.Oauth2LoginUser;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.SysUser;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.annotation.InnerAuth;
import com.ruoyi.common.security.auth.AuthUtil;
import com.ruoyi.common.security.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.redis.JdkSerializationStrategy;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.ruoyi.common.security.service.TokenService.EXPIRE_TIME;

/**
 * @author MrBird
 */
@RestController
@RequiredArgsConstructor
public class SecurityController {

    private final SysLoginService sysLoginService;
    private final RedisService redisService;

    private final JdkSerializationStrategy serializationStrategy = new JdkSerializationStrategy();

    @ResponseBody
    @GetMapping("principal")
    public Principal principal(Principal principal) {
        return principal;
    }

    @ResponseBody
    @GetMapping("user")
    public Oauth2LoginUser currentUser(Principal principal) {
        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication)principal;
        Authentication userAuthentication = oAuth2Authentication.getUserAuthentication();
        Oauth2LoginUser loginUser = (Oauth2LoginUser) userAuthentication.getPrincipal();
        loginUser.getSysUser().setPassword("");
        loginUser.getSysUser().setPayPassword("");
        return loginUser;
    }

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

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

    @InnerAuth
    @PutMapping ("/refreshTokenUserInfo")
    public void refreshTokenUserInfo(@RequestParam("token") String token,@RequestBody SysUser sysUser) {
        byte[] authKey = serializationStrategy.serialize(token);
        Authentication authentication = serializationStrategy.deserialize(redisService.get(authKey), Authentication.class);
        Oauth2LoginUser principal = (Oauth2LoginUser)authentication.getPrincipal();
        SysUser orgSysUser = principal.getSysUser();
        String[] arr = {"nickName", "email", "phonenumber", "sex", "password", "avatar"};
        List<String> list = Arrays.asList(arr);
        JSONObject jsonOrgSysUser = new JSONObject(orgSysUser);
        JSONObject jsonSysUser = new JSONObject(sysUser);
        for(Map.Entry<String, Object> entry : jsonOrgSysUser.entrySet()) {
            if(list.contains(entry.getKey())) {
                jsonOrgSysUser.set(entry.getKey(), jsonSysUser.get(entry.getKey()));
            }
        }
        SysUser bean = jsonOrgSysUser.toBean(SysUser.class);
        principal.setSysUser(bean);

        redisService.set(authKey, serializationStrategy.serialize(authentication),
                Expiration.from(EXPIRE_TIME, TimeUnit.MINUTES), RedisStringCommands.SetOption.UPSERT);
    }
}
