package com.sysu.edu.studentAffair;
import static com.sysu.edu.api.CommonUtil.extractValue;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.alibaba.fastjson2.JSONObject;
import com.sysu.edu.R;
import com.sysu.edu.api.AuthorizationManager;
import com.sysu.edu.api.HttpManager;
import com.sysu.edu.api.Params;
import com.sysu.edu.api.TargetUrl;
import com.sysu.edu.view.StaggeredFragment;
import java.util.List;
public class Template extends StaggeredFragment {
final AuthorizationManager authorizationManager = new AuthorizationManager("https://xgxt.sysu.edu.cn/", "https://xgxt-443.webvpn.sysu.edu.cn/");
HttpManager http;
View view;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
if (view == null) {
view = super.onCreateView(inflater, container, savedInstanceState);
Params params = new Params(requireActivity());
params.setCallback(this, () -> getData(""));
http = new HttpManager(new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
boolean isJSON = msg.getData().getBoolean("isJSON");
int code = msg.getData().getInt("code");
String response = (String) msg.obj;
if (code == 0) {
authorizationManager.setAccessible(false);
getData("");
return;
}
if (response == null) {
params.toast(R.string.no_wifi_warning);
return;
}
if (!isJSON) {
if (!authorizationManager.isAuthorized(response)) {
params.toast(R.string.login_warning);
params.gotoLogin(view, authorizationManager.isAccessible() ? TargetUrl.XGXT : TargetUrl.XGXT_WEBVPN);
return;
}
if (!authorizationManager.isAccessible(response)) {
params.toast(R.string.educational_wifi_warning);
getData("");
return;
}
}
if (msg.what == -1) {
params.toast(R.string.no_wifi_warning);
return;
} else {
JSONObject data = JSONObject.parseObject(response);
if (data.containsKey("code") && data.getInteger("code") == 200) {
switch (msg.what) {
case 0 -> {
add("", List.of("中文"),
extractValue(data.getJSONObject("data"), new String[]{"key"}));
}
case 1 -> {
data.getJSONArray("data").forEach(i ->
add("", List.of("中文"),
extractValue((JSONObject) i, new String[]{"key"})));
}
}
} else if (data.getJSONObject("meta").getInteger("statusCode") == 302) {
params.toast(R.string.login_warning);
params.gotoLogin(view, authorizationManager.isAccessible() ? TargetUrl.XGXT : TargetUrl.XGXT_WEBVPN);
}
}
}
});
http.setParams(params);
getData("");
}
return view;
}
void getData(String path) {
http.getRequest(authorizationManager.getBaseUrl() + path, 0);
}
}