package xn.hxp.ui;

import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
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.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.kongzue.dialogx.dialogs.MessageDialog;
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.ArrayList;
import java.util.List;
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;

public class StartActivity extends BaseActivity {
    private ActivityStartBinding binding;
    private ThreadUtils.SimpleTask<LabInfo> checkTask;

    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() {
        requestPermission();
    }

    private void requestPermission() {
        XXPermissions.with(this).permission(Permission.CAMERA,
                Permission.READ_EXTERNAL_STORAGE,
                Permission.WRITE_EXTERNAL_STORAGE,
                Permission.READ_PHONE_STATE,
                Permission.SYSTEM_ALERT_WINDOW,
                Permission.RECORD_AUDIO).request(new OnPermissionCallback() {
            @Override
            public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                if (allGranted) {
                    initView();
                } else {
                    MessageDialog.show("提示", "您必须同意所有权限才可以继续使用", "确定").setCancelable(false).setOkButtonClickListener((dialog, v) -> {
                        requestPermission();
                        return false;
                    });
                }
            }

            @Override
            public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                OnPermissionCallback.super.onDenied(permissions, doNotAskAgain);
                if (doNotAskAgain) {
                    MessageDialog.show("提示", "您必须同意所有权限才可以继续使用", "确定").setCancelable(false).setOkButtonClickListener((dialog, v) -> {
                        XXPermissions.startPermissionActivity(StartActivity.this, permissions);
                        return false;
                    });
                } else {
                    MessageDialog.show("提示", "您必须同意所有权限才可以继续使用", "确定").setCancelable(false).setOkButtonClickListener((dialog, v) -> {
                        requestPermission();
                        return false;
                    });
                }
            }
        });
    }

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

        // 进去设置页面
        binding.logo.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                ActivityUtils.startActivity(SettingActivity.class);
                finish();
                return true;
            }
        });

        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());
            settingsBean.getD();
            if (!TextUtils.isEmpty(settingsBean.getD())) {
                Constants.INSTANCE.setFACE_TAG(Integer.parseInt(settingsBean.getD()));
            }
        }
    }

    public List<String> splitStringIntoChunks(String inputString, int chunkSize) {
        if (chunkSize <= 0) {
            throw new IllegalArgumentException("Chunk size must be greater than 0");
        }

        List<String> result = new ArrayList<>();
        int startIndex = 0;

        while (startIndex < inputString.length()) {
            int endIndex = Math.min(startIndex + chunkSize, inputString.length());
            String chunk = inputString.substring(startIndex, endIndex);
            result.add(chunk);
            startIndex = endIndex;
        }

        return result;
    }

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