package org.springblade.modules.auth.endpoint;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springblade.auth.enums.ThirdPartyLoginType;
import org.springblade.auth.model.ThirdPartyLogin;
import org.springblade.auth.thirdparty.ThirdPartyAuthRequest;
import org.springblade.common.cache.CacheNames;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.modules.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.Duration;


@RestController
@RequestMapping("blade-auth/mq")
@Api(value = "三方授权登录", tags = "微信公众号小程序登录相关接口")
@Slf4j
public class BladeWechatLoginController extends BladeController {


    @Autowired
    private BladeRedis bladeRedis;

    @Autowired
    private ThirdPartyAuthRequest thirdPartyAuthRequest;

    @Autowired
    private IThirdLoginConfigService thirdLoginConfigService;


    @ApiOperation("公众号校验token接口")
    @GetMapping(value = "/callBack")
    public String checkSignature(@RequestParam(value = "signature",required = false) String signature
            , @RequestParam(value = "timestamp",required = false) String timestamp
            , @RequestParam(value = "nonce",required = false) String nonce
            , @RequestParam(value = "echostr",required = false) String echostr){

        return thirdPartyAuthRequest.checkSignature(signature, timestamp, nonce, echostr);
    }

    @ApiOperation("公众号事件推送接口")
    @PostMapping("/callBack")
    public String subscribeProcessor(HttpServletRequest request) {
        log.info("测试账号能进来...");
        String openId;
        ThirdPartyLogin login = new ThirdPartyLogin();
        login.setLoginType(ThirdPartyLoginType.publicAccount);
        openId = thirdPartyAuthRequest.login(login, null, request);
        if (StrUtil.isNotEmpty(openId)) {
            if ("unSubscribe".equals(openId) || "noUserInfo".equals(openId)) {
                return openId;
            } else {
                String[] split = openId.split(",");
                bladeRedis.setEx(CacheNames.THIRD_OPENID + split[1], split[0], Duration.ofMinutes(10));
            }
        }
        return "ok";
    }

    @GetMapping("/openid")
    public String getOpenid(@RequestParam(required = false) String ticket) {
        return bladeRedis.get(CacheNames.THIRD_OPENID + ticket);
    }
}
