package org.wfc.auth.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
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 org.wfc.auth.service.SysLoginService;
import org.wfc.auth.service.ULoginService;
import org.wfc.common.core.domain.LoginUser;
import org.wfc.common.core.domain.R;
import org.wfc.common.core.utils.JwtUtils;
import org.wfc.common.core.utils.StringUtils;
import org.wfc.common.core.web.form.LoginBody;
import org.wfc.common.core.web.form.RegisterBody;
import org.wfc.common.core.web.form.WANFiRedirectParams;
import org.wfc.common.security.auth.AuthUtil;
import org.wfc.common.security.service.TokenService;
import org.wfc.common.security.utils.SecurityUtils;
import org.wfc.system.api.domain.SysUser;
import org.wfc.user.api.RemoteUUserService;
import org.wfc.user.api.domain.UUser;
import org.wfc.user.api.domain.bo.UClientBo;

import javax.servlet.http.HttpServletRequest;

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

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private ULoginService uLoginService;

    @Autowired
    private RemoteUUserService remoteUUserService;

    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form) {
        if ("u".equals(form.getAuthType())) {
            WANFiRedirectParams wanFiRedirectParams = form.getWanfiRedirectParams();
            if (wanFiRedirectParams == null) {
                return R.fail("auth.invalid.login.parameter");
            }
            // 用户登录
            LoginUser<UUser> userInfo = uLoginService.login(form.getUsername(), form.getPassword());
            userInfo.setWanFiRedirectParams(wanFiRedirectParams);
            // 记录设备所属用户信息
            UClientBo uClientBo = UClientBo.builder().clientMac(wanFiRedirectParams.getClientMac())
                    .siteId(wanFiRedirectParams.getSite())
                    .userId(userInfo.getUser().getUserId()).build();
            remoteUUserService.recordClientUser(uClientBo);
            // 获取登录token
            return R.ok(tokenService.createToken(userInfo));
        }
        if ("sys".equals(form.getAuthType())) {
            // 用户登录
            LoginUser<SysUser> sysInfo = sysLoginService.login(form.getUsername(), form.getPassword());
            // 获取登录token
            return R.ok(tokenService.createToken(sysInfo));
        }

        return R.fail("auth.authentication.type.not.supported");
    }

    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            String username = JwtUtils.getUserName(token);
            String userPlatform = JwtUtils.getUserPlatform(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            if ("user".equals(userPlatform)) {
                uLoginService.logout(username);
            } else {
                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 form) {
        if ("u".equals(form.getAuthType())) {
            uLoginService.register(form);
            return R.ok();
        }
        if ("sys".equals(form.getAuthType())) {
            sysLoginService.register(form);
            return R.ok();
        }
        return R.fail("auth.authentication.type.not.supported");
    }

    @PostMapping("checkRepeat")
    public R<?> checkRepeat(@RequestBody RegisterBody form) {
        if ("u".equals(form.getAuthType())) {
            return R.ok(uLoginService.checkRepeat(form));
        }
        if ("sys".equals(form.getAuthType())) {
        }
        return R.fail("auth.authentication.type.not.supported");
    }

    @GetMapping("health")
    public R<?> health(HttpServletRequest request) {
        // check health
        return R.ok(null, "auth.is.healthy");
    }
}
