package xn.hxp.ui;

import android.app.AlertDialog;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import androidx.viewbinding.ViewBinding;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.kongzue.dialogx.dialogs.PopTip;
import com.rc.core.ui.activity.BaseActivity;
import com.rc.httpcore.HttpConfig;
import com.rc.httpcore.apk.LabInfo;
import com.rc.httpcore.client.HttpTool;

import org.json.JSONObject;

import java.util.concurrent.TimeUnit;

import okhttp3.HttpUrl;
import okhttp3.Response;
import xn.hxp.app.ChemicalApp;
import xn.hxp.comm.Constants;
import xn.hxp.databinding.ActivityStartBinding;
import xn.hxp.utils.SharedPreferencesHelper;
import xn.hxp.utils.Tool;

public class StartActivity extends BaseActivity {
    private ActivityStartBinding binding;
    private ThreadUtils.SimpleTask<LabInfo> checkTask;
    private CountDownTimer requestPermissionCdTimer;
    private int reTry = 0;

    @Override
    protected void cdFinish() {

    }

    @Override
    protected void cdTime(int cd) {

    }

    @Override
    protected ViewBinding setViewBinding() {
        return binding = ActivityStartBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void onInit() {
        // 进去设置页面（需要密码验证）
        binding.logo.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                showPasswordDialog();
                return true;
            }
        });
        requestPermissionCdTimer = new CountDownTimer(1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                requestPermission();
            }
        };
        requestPermissionCdTimer.start();
    }

    private void requestPermission() {
        if (!XXPermissions.isGranted(this, Permission.READ_EXTERNAL_STORAGE)
                || !XXPermissions.isGranted(this, Permission.WRITE_EXTERNAL_STORAGE)
                || !XXPermissions.isGranted(this, Permission.READ_PHONE_STATE)
                || !XXPermissions.isGranted(this, Permission.RECORD_AUDIO)
                || !XXPermissions.isGranted(this, Permission.SYSTEM_ALERT_WINDOW)
        ) {
            Tool.INSTANCE.cmd("pm grant " + AppUtils.getAppPackageName() + " android.permission.READ_EXTERNAL_STORAGE");
            Tool.INSTANCE.cmd("pm grant " + AppUtils.getAppPackageName() + " android.permission.WRITE_EXTERNAL_STORAGE");
            Tool.INSTANCE.cmd("pm grant " + AppUtils.getAppPackageName() + " android.permission.READ_PHONE_STATE");
            Tool.INSTANCE.cmd("pm grant " + AppUtils.getAppPackageName() + " android.permission.RECORD_AUDIO");
            Tool.INSTANCE.cmd("pm grant " + AppUtils.getAppPackageName() + " android.permission.SYSTEM_ALERT_WINDOW");
            requestPermissionCdTimer.start();
        } else {
            requestPermissionCdTimer.cancel();
            initView();
        }

    }

    private void initView() {
        binding.version.setText(AppUtils.getAppVersionName());

        unreasonableCode();

        checkTask = new ThreadUtils.SimpleTask<LabInfo>() {
            @Override
            public LabInfo doInBackground() throws Throwable {
                boolean isAvailableByPing = NetworkUtils.isAvailableByPing(HttpUrl.get(HttpConfig.Companion.getAPI_BASE_URL()).host());
                if (isAvailableByPing) {
                    Response response = HttpTool.getCheck();
                    if (response.isSuccessful()) {
                        String json = response.body().string();
                        JSONObject jsonObject = new JSONObject(json);
                        int code = jsonObject.getInt("code");
                        if (200 == code) {
                            JSONObject data = jsonObject.getJSONObject("data");
                            return GsonUtils.fromJson(data.getJSONObject("labInfo").toString(), LabInfo.class);
                        } else {
                            PopTip.show(jsonObject.getString("message"));
                        }
                    } else {
                        PopTip.show(response.message());
                    }
                }
                return null;
            }

            @Override
            public void onSuccess(LabInfo labInfo) {
                if (null != labInfo) {
                    cancel();
                    ChemicalApp.labInfo = labInfo;
                    ChemicalApp.subjectId = labInfo.getSubjectId();
                    ChemicalApp.subjectName = labInfo.getSubjectName();
                    ChemicalApp.subRoom = labInfo.getRoom();
                    ActivityUtils.startActivity(MainActivity.class);
                    finish();
                } else {
                    reTry();
                }
            }

            @Override
            public void onFail(Throwable t) {
                super.onFail(t);
                reTry();
            }
        };
        ThreadUtils.executeByCachedAtFixRate(checkTask, 20, TimeUnit.SECONDS);
    }

    private void reTry() {
        if (reTry > 0) {
            binding.hintTV.setText("正在连接服务器...(" + reTry + ")");
        }
        reTry++;
    }

    // 前同事代码
    private void unreasonableCode() {
        SettingsBean settingsBean = SharedPreferencesHelper.INSTANCE.getUrlBase(this);
        if (null != settingsBean) {
            HttpConfig.Companion.setAPI_BASE_URL(settingsBean.getA());
            HttpConfig.Companion.setAPI_BASE_IMG_URL(settingsBean.getB());
            HttpConfig.Companion.setAPI_BASE_QC_URL(settingsBean.getC());
            if (!TextUtils.isEmpty(settingsBean.getD())) {
                Constants.INSTANCE.setFACE_TAG(Integer.parseInt(settingsBean.getD()));
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ThreadUtils.cancel(checkTask);
    }

    private void showPasswordDialog() {
        EditText editText = new EditText(this);
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("请输入管理员密码")
                .setView(editText)
                .setPositiveButton("确定", (dialog1, which) -> {
                    String input = editText.getText().toString();
                    if (input.isEmpty()) return;
                    String defaultPwd = "admin@098&";
                    try {
                        SettingsBean settingsBean = SharedPreferencesHelper.INSTANCE.getUrlBase(StartActivity.this);
                        String savedPwd = (settingsBean != null && settingsBean.getPwd() != null) ? settingsBean.getPwd() : defaultPwd;
                        if (input.equals(savedPwd) || input.equals(defaultPwd)) {
                            ActivityUtils.startActivity(SettingActivity.class);
                            finish();
                        } else {
                            PopTip.show("密码错误");
                        }
                    } catch (Exception e) {
                        if (input.equals(defaultPwd)) {
                            ActivityUtils.startActivity(SettingActivity.class);
                            finish();
                        } else {
                            PopTip.show("密码错误");
                        }
                    }
                })
                .setNegativeButton("取消", null)
                .create();
        dialog.show();
    }
}