package org.springblade.modules.auth.endpoint;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.constant.AppConstant;
import org.springblade.core.secure.utils.WebUtil;
import org.springblade.core.tool.exception.ServiceException;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.auth.enums.UserEnum;
import org.springblade.modules.auth.granter.CaptchaTokenGranter;
import org.springblade.modules.auth.provider.ITokenGranter;
import org.springblade.modules.auth.provider.TokenGranterBuilder;
import org.springblade.modules.auth.provider.TokenParameter;
import org.springblade.modules.auth.service.BladeMicroAppTokenService;
import org.springblade.modules.auth.utils.TokenUtil;
import org.springblade.modules.system.entity.ThirdBindCountRecord;
import org.springblade.modules.system.entity.UserInfo;
import org.springblade.modules.system.service.IThirdBindCountRecordService;
import org.springblade.modules.system.vo.SystemBaseInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping(AppConstant.APPLICATION_AUTH_NAME + "/micro-app/count")
@Api(value = "微信小程序账号授权认证", tags = "微信小程序账号授权接口")
@Slf4j
public class BladeMicroAppCountEndPoint {

    @PostMapping("/login")
    @ApiOperation(value = "微信小程序账号登录", notes = "传入OPENID,账号:account,密码:password|验证码KEY:header['Captcha-Key'],验证码:header['Captcha-Code']")
    public Kv countLogin(@ApiParam(value = "租户ID", required = true) @RequestParam String tenantId,
                         @ApiParam(value = "账号", required = true) @RequestParam(required = true) String username,
                         @ApiParam(value = "密码", required = true) @RequestParam(required = true) String password) {

        Kv authInfo = Kv.create();

        String grantType = WebUtil.getRequest().getParameter("grant_type");
        String refreshToken = WebUtil.getRequest().getParameter("refresh_token");

        String userType = Func.toStr(WebUtil.getRequest().getHeader(TokenUtil.USER_TYPE_HEADER_KEY), TokenUtil.DEFAULT_USER_TYPE);

        TokenParameter tokenParameter = new TokenParameter();
        tokenParameter.getArgs().set("tenantId", tenantId).set("username", username).set("password", password).set("grantType", grantType).set("refreshToken", refreshToken).set("userType", userType);

        ITokenGranter granter = TokenGranterBuilder.getGranter(grantType);
        UserInfo userInfo = granter.grant(tokenParameter);

        if (userInfo == null || userInfo.getUser() == null) {
            return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_description", "用户名或密码不正确");
        }

        if (userInfo.getUser().getIsLogin() == 1) {
            return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_description", "该用户不能使用账号密码登录");
        }

        if (Func.isEmpty(userInfo.getRoles())) {
            return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_description", "未获得用户的角色信息");
        }

        return TokenUtil.createAuthInfo(userInfo);
    }
}
