package uni.deepoil.com;

import android.os.Handler;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.android.dingtalk.openauth.AuthLoginParam;
import com.android.dingtalk.openauth.DDAuthApiFactory;
import com.android.dingtalk.openauth.IDDAuthApi;

import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.common.UniModule;

/**
 * 钉钉登录插件
 *
 * @author Berial
 * @since 2025-06-09
 */
public class DingTalkModule extends UniModule {

    private static String state;
    public static UniJSCallback sCallback;
    public static Handler handler = new Handler(msg -> {
        Log.d("DingTalkModule", "callback: " + sCallback);
        if (sCallback != null && (msg.what == 1 || msg.what == 2)) {
            Log.d("DingTalkModule", "what: " + msg.what + ", obj: " + msg.obj);
            JSONObject data = new JSONObject();
            data.put("success", msg.what);
            data.put("code", msg.obj);
            data.put("state", state);
            sCallback.invoke(data);
        }
        return false;
    });

    @UniJSMethod
    public void login(UniJSCallback callback) {
         sCallback = callback;

        state = String.valueOf(System.currentTimeMillis());
        AuthLoginParam params = AuthLoginParam.AuthLoginParamBuilder.newBuilder()
                .appId("dingmr9ez0ecgbmscfeb")
                .redirectUri("https://iot.deepoil.cc/")
                .responseType("code")
                .scope("openid%20corpid")
                .prompt("consent")
                .nonce("nonce")
                .state(state)
                .build();
        IDDAuthApi api = DDAuthApiFactory.createDDAuthApi(mUniSDKInstance.getContext(), params);
        api.authLogin();
    }
}
