package org.dromara.web.service;


import org.dromara.common.core.domain.model.LoginBody;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.exception.base.BaseException;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.system.domain.app.AppletLoginForm;
import org.dromara.system.domain.SysClient;
import org.dromara.system.domain.app.AppletSessionDTO;
import org.dromara.system.utils.WxCodeSessionUtil;
import org.dromara.web.domain.vo.LoginVo;

/**
 * 授权策略
 *
 * @author Michelle.Chung
 */
public interface IAuthStrategy {

    String BASE_NAME = "AuthStrategy";

    /**
     * 登录
     */
    static LoginVo login(LoginBody loginBody, SysClient client) {
        // 授权类型和客户端id
        String clientId = loginBody.getClientId();
        String grantType = loginBody.getGrantType();
        String beanName = grantType + BASE_NAME;
        if (!SpringUtils.containsBean(beanName)) {
            throw new ServiceException("授权类型不正确!");
        }
        IAuthStrategy instance = SpringUtils.getBean(beanName);
        instance.validate(loginBody);
        return instance.login(clientId, loginBody, client);
    }

    static LoginVo weChatLogin(AppletLoginForm form,LoginBody loginBody,SysClient client) {

        // 授权类型和客户端id
        String clientId = loginBody.getClientId();
        String grantType = loginBody.getGrantType();
        String beanName = grantType + BASE_NAME;

        //用户唯一标识 OpenID 、 用户在微信开放平台帐号下的唯一标识UnionID
        // （若当前小程序已绑定到微信开放平台帐号） 和 会话密钥 session_key
        AppletSessionDTO dto = WxCodeSessionUtil.jscode2Session(form);
        String phoneNumber = dto.getPhoneNumber();
        String openId= dto.getOpenId();
        if (StringUtils.isBlank(phoneNumber) || StringUtils.isBlank(openId)){
            throw new BaseException("对不起，未获取到手机号");
        }
        loginBody.setUsername(phoneNumber);
        loginBody.setPhonenumber(phoneNumber);
        IAuthStrategy instance = SpringUtils.getBean(beanName);
        //instance.validate(loginBody);
        return instance.weChatLogin(clientId, loginBody, client);
    }

    /**
     * 参数校验
     */
    void validate(LoginBody loginBody);

    /**
     * 登录
     */
    LoginVo login(String clientId, LoginBody loginBody, SysClient client);


    /**
     * 登录
     */
    LoginVo weChatLogin(String clientId, LoginBody loginBody, SysClient client);

}
