package cn.nahco3awa.naouc.ui.ouc.activity;

import static android.widget.Toast.LENGTH_SHORT;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.IOException;
import java.util.Locale;

import cn.nahco3awa.naouc.R;
import cn.nahco3awa.naouc.network.ouc.OUCRequestSender;
import cn.nahco3awa.naouc.network.ouc.request.NetGdcOUCRequest;
import cn.nahco3awa.naouc.network.ouc.request.TsmOUCRequest;
import cn.nahco3awa.naouc.network.ouc.response.NetGdcOUCResponse;
import cn.nahco3awa.naouc.network.ouc.response.OUCCallback;
import cn.nahco3awa.naouc.network.ouc.response.TsmOUCResponse;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OucNetActivity extends AppCompatActivity {
    private TextView netStatusTextView;
    private TextView netBalanceTextView;
    private String account;
    private String sno;
    private SharedPreferences preferences;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ouc_net);
        Intent intent = getIntent();
        account = intent.getStringExtra("account");
        sno = intent.getStringExtra("sno");
        netStatusTextView = findViewById(R.id.netStatusTextView);
        netBalanceTextView = findViewById(R.id.netBalanceBigTextView);
        refreshBalance();
        preferences = getSharedPreferences("net", MODE_PRIVATE);
    }

    private void refreshBalance() {
        OUCRequestSender.getInstance().tsm(new TsmOUCRequest(account, sno), new OUCCallback<>() {
            @Override
            public void onSuccess(TsmOUCResponse response) {
                runOnUiThread(() -> {
                    netBalanceTextView.setText(String.format(Locale.SIMPLIFIED_CHINESE, "%.2f", response.getBalance()));
                    netStatusTextView.setText(response.isFrozen() ? "校园网停机" : "校园网余额");
                    if (response.isFrozen()) netStatusTextView.setTextColor(0xFFF44336);
                });
            }

            @Override
            public void onFailure(Throwable e) {
                runOnUiThread(() -> {
                    netStatusTextView.setText("查询失败");
                    netBalanceTextView.setText("");
                });
            }
        });
    }

    public void onClickPay(View view) {
        EditText editText = new EditText(this);
        editText.setHint("请输入金额（元）：");
        editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        new AlertDialog.Builder(this)
                .setTitle("网费缴纳")
                .setView(editText)
                .setNegativeButton("取消", null)
                .setPositiveButton("缴纳", (dialog, which) -> {
                    String amountString = editText.getText().toString();
                    double amount = Double.parseDouble(amountString) * 100;
                    OUCRequestSender.getInstance().netGdc(new NetGdcOUCRequest(account, sno, (int) amount), new OUCCallback<>() {
                        @Override
                        public void onSuccess(NetGdcOUCResponse response) {
                            runOnUiThread(() -> {
                                if (response.getRetCode() == 0) {
                                    Toast.makeText(OucNetActivity.this, "缴费成功~", LENGTH_SHORT).show();
                                    refreshBalance();
                                } else {
                                    Toast.makeText(OucNetActivity.this, "缴费失败：" + response.getErrMessage(), LENGTH_SHORT).show();
                                }
                            });
                        }

                        @Override
                        public void onFailure(Throwable e) {
                            runOnUiThread(() -> Toast.makeText(OucNetActivity.this, "缴费失败！", LENGTH_SHORT).show());
                        }
                    });
                })
                .show();
    }

    public void onClickLogin(View view) {
        String password = preferences.getString("password", "");
        if (password.isEmpty()) {
            EditText editText = new EditText(this);
            editText.setHint("请输入校园网密码...");
            editText.setAutofillHints(View.AUTOFILL_HINT_PASSWORD);
            editText.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
            new AlertDialog.Builder(this)
                    .setTitle("校园网认证")
                    .setView(editText)
                    .setNegativeButton("登录", (dialogInterface, i) -> {
                        preferences.edit()
                                .putString("password", editText.getText().toString())
                                .apply();
                        onClickLogin(null);
                    })
                    .show();
            return;
        }
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        int iip = wifiManager.getConnectionInfo().getIpAddress();
        String ip = String.format(
                Locale.SIMPLIFIED_CHINESE,
                "%d.%d.%d.%d",
                (iip & 0xff),
                (iip >> 8 & 0xff),
                (iip >> 16 & 0xff),
                (iip >> 24 & 0xff)
        );
        OkHttpClient client = new OkHttpClient();
        var request = new Request.Builder()
                .url(String.format(
                        Locale.SIMPLIFIED_CHINESE,
                        "https://wxrz.ouc.edu.cn:802/eportal/portal/login?&callback=dr1003&login_method=1&user_account=%s&user_password=%s&wlan_user_ip=%s&wlan_user_ipv6=&wlan_user_mac=000000000000&wlan_ac_ip=&wlan_ac_name=&jsVersion=4.1&terminal_type=1&lang=zh-cn&v=3288&lang=zh",
                        sno, password, ip
                ))
                .get()
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Toast.makeText(OucNetActivity.this, "登录失败，请检查校园网连接！", LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                var resp = response.body().string();

                if (!resp.startsWith("dr1003(") || !resp.endsWith(");")) {
                    Toast.makeText(OucNetActivity.this, "登录失败，响应异常！", LENGTH_SHORT).show();
                    return;
                }

                resp = resp.substring(7, resp.length() - 2);
                JsonObject jsonObject = JsonParser.parseString(resp).getAsJsonObject();

                int result = jsonObject.get("result").getAsInt();
                String msg = jsonObject.get("msg").getAsString();
                if (result == 1) {
                    Toast.makeText(OucNetActivity.this, "校园网登录成功~", LENGTH_SHORT).show();
                    return;
                }

                int code = jsonObject.get("ret_code").getAsInt();
                if (code == 2) {
                    Toast.makeText(OucNetActivity.this, "您已经在线啦~", LENGTH_SHORT).show();
                    return;
                }

                new AlertDialog.Builder(OucNetActivity.this)
                        .setTitle("校园网登录失败...")
                        .setMessage(msg)
                        .setNegativeButton("好吧", null)
                        .setPositiveButton("再试一次", (dialogInterface, i) -> onClickLogin(null))
                        .show();
            }
        });
    }

    public void onClickOfficial(View view) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://222.195.158.36/Self/"));
        startActivity(intent);
    }
}