package com.css.txw.sso.controller.auth;


import static com.css.ggzc.framework.common.pojo.CommonResult.success;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.css.ggzc.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.css.ggzc.framework.common.pojo.CommonResult;
import com.css.ggzc.framework.common.util.gy.GyUtils;
import com.css.ggzc.framework.common.util.servlet.ServletUtils;
import com.css.txw.sso.constants.SsoConstants;
import com.css.txw.sso.enums.LoginLogTypeEnum;
import com.css.txw.sso.pojo.vo.AuthLoginReqVO;
import com.css.txw.sso.pojo.vo.AuthLoginRespVO;
import com.css.txw.sso.pojo.vo.DidBindPhoneReqVO;
import com.css.txw.sso.pojo.vo.SMSLoginReqVO;
import com.css.txw.sso.pojo.vo.SendMsgReqVO;
import com.css.txw.sso.pojo.vo.oauth2.LogoutVO;
import com.css.txw.sso.pojo.vo.thirdparty.did.QrCodeInfo;
import com.css.txw.sso.service.auth.AuthService;
import com.css.txw.sso.util.SecurityFrameworkUtils;

import cn.hutool.core.util.StrUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;


@Tag(name = "管理后台 - 认证")
@RestController
@RequestMapping("/auth")
@Validated
@Slf4j
public class AuthController {

    @Resource
    private AuthService authService;


    @PostMapping("/login")
    @PermitAll
    @Operation(summary = "使用账号密码登录")
    public CommonResult<AuthLoginRespVO> login(@RequestBody @Valid AuthLoginReqVO reqVO) {
        final HttpServletResponse response = ServletUtils.getResponse();
        final AuthLoginRespVO login = authService.login(reqVO);

        final Cookie cookie = new Cookie(SsoConstants.COOKIE_TOKEN_KEY,login.getAccessToken());
        cookie.setPath(SsoConstants.COOKIE_PATH);
        cookie.setHttpOnly(true);
        //cookie.setMaxAge(-1);
        response.addCookie(cookie);
        return success(login);
    }

    @PostMapping("/logout")
    @PermitAll
    @Operation(summary = "登出系统")
    public CommonResult<List<LogoutVO>> logout(HttpServletRequest request) {
        List<LogoutVO> logout = new ArrayList<>();
        String token = SecurityFrameworkUtils.obtainAuthorization(SsoConstants.COOKIE_TOKEN_KEY,request);
        if (StrUtil.isNotBlank(token)) {
            logout = authService.logout(token, LoginLogTypeEnum.LOGOUT_SELF.getType());
            final HttpServletResponse response = ServletUtils.getResponse();
            final Cookie cookie = new Cookie(SsoConstants.COOKIE_TOKEN_KEY,token);
            cookie.setPath(SsoConstants.COOKIE_PATH);
            cookie.setHttpOnly(true);
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }
        log.info("ssologout返回结果：{}",logout);
        return success(logout);
    }

    @PostMapping("/refresh-token")
    @PermitAll
    @Operation(summary = "刷新令牌")
    @Parameter(name = "refreshToken", description = "刷新令牌", required = true)
    public CommonResult<AuthLoginRespVO> refreshToken(@RequestParam("refreshToken") String refreshToken) {
        return success(authService.refreshToken(refreshToken));
    }

    @PostMapping("/sendMsg")
    @PermitAll
    @Operation(summary = "发送手机验证码")
    public CommonResult<Integer> sendMsg(@RequestBody @Valid SendMsgReqVO reqVO) throws Exception{
        return success(authService.sendMsg(reqVO));
    }

    @PostMapping("/loginBySMS")
    @PermitAll
    @Operation(summary = "发送手机验证码")
    public CommonResult<AuthLoginRespVO> loginBySMS(@RequestBody @Valid SMSLoginReqVO reqVO) {
        final HttpServletResponse response = ServletUtils.getResponse();
        final AuthLoginRespVO login = authService.loginBySMS(reqVO);
        final Cookie cookie = new Cookie(SsoConstants.COOKIE_TOKEN_KEY,login.getAccessToken());
        cookie.setPath(SsoConstants.COOKIE_PATH);
        cookie.setHttpOnly(true);
        //cookie.setMaxAge(-1);
        response.addCookie(cookie);
        return success(login);
    }
    
    @PostMapping("/didBindPhone")
    @PermitAll
    @Operation(summary = "绑定手机号")
    public CommonResult<AuthLoginRespVO> didBindPhone(@RequestBody @Valid DidBindPhoneReqVO reqVO) {
    	if (GyUtils.isNull(reqVO)) {
    		CommonResult<AuthLoginRespVO> result = CommonResult.success(null);
			String msg = "入参为空！";
			result.setMsg(msg);
			result.setCode(GlobalErrorCodeConstants.ERROR.getCode());
			return result;
		}
    	if (GyUtils.isNull(reqVO.getReqId())) {
    		CommonResult<AuthLoginRespVO> result = CommonResult.success(null);
			String msg = "入参reqId为空！";
			result.setMsg(msg);
			result.setCode(GlobalErrorCodeConstants.ERROR.getCode());
			return result;
		}
    	final HttpServletResponse response = ServletUtils.getResponse();
        final AuthLoginRespVO login = authService.didBindPhone(reqVO);
        final Cookie cookie = new Cookie(SsoConstants.COOKIE_TOKEN_KEY,login.getAccessToken());
        cookie.setPath(SsoConstants.COOKIE_PATH);
        cookie.setHttpOnly(true);
        //cookie.setMaxAge(-1);
        response.addCookie(cookie);
        return success(login);
    }
}
