package com.cooleshow.student.ui.mine;

import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.activity.BaseMVPActivity;
import com.cooleshow.base.utils.NetworkUtil;
import com.cooleshow.base.widgets.BaseDialog;
import com.cooleshow.base.widgets.DialogUtil;
import com.cooleshow.base.widgets.RoundProgressBar;
import com.cooleshow.base.widgets.ViewHolder;
import com.cooleshow.base.widgets.loading.SpinKitView;
import com.cooleshow.student.R;
import com.cooleshow.student.contract.NetworkMonitoringContract;
import com.cooleshow.student.databinding.ActivityNetworkMonitoringBinding;
import com.cooleshow.student.presenter.mine.NetworkMonitoringPresenter;

import java.util.Random;

import io.rong.imkit.utils.StatusBarUtil;

/**
 * 创建日期：2022/6/1 14:50
 *
 * @author Ryan
 * 类说明：
 */
@Route(path = RouterPath.MineCenter.MINE_NETWORK_MONITORING)
public class NetworkMonitoringActivity extends BaseMVPActivity<ActivityNetworkMonitoringBinding, NetworkMonitoringPresenter> implements NetworkMonitoringContract.NetworkMonitoringView, View.OnClickListener {
    RoundProgressBar progess;
    ImageView ivOne;
    SpinKitView skOne;
    ImageView ivTwo;
    SpinKitView skTwo;
    ImageView ivThree;
    SpinKitView skThree;
    ImageView ivFour;
    SpinKitView skFour;
    boolean isSuccess = false;
    Handler mHandler;
    Runnable mRunnable;
    int proges = 0;
    int position = 0;
    boolean isStart = true;
    private int delayMillis;
    private boolean isNetwork = false;
    private boolean isStop = false;
    private int normal = R.drawable.icon_network_normal;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setStatusBarDarkTheme(this, true);

    }
    @Override
    public void onClick(View view) {

    }

    @Override
    protected void initView() {
        initMidTitleToolBar(viewBinding.toolbarInclude.toolbar, "网络检测");
        progess=viewBinding.progess;
        ivOne=viewBinding.ivOne;
        skOne=viewBinding.skOne;
        ivTwo=viewBinding.ivTwo;
        skTwo=viewBinding.skTwo;
        ivThree=viewBinding.ivThree;
        skThree=viewBinding.skThree;
        ivFour=viewBinding.ivFour;
        skFour=viewBinding.skFour;



        mHandler = new Handler();
        progess.setOnProgressListener(position -> {
            this.position = position;
            try {
                if (position == 5) {
                    getNetWorkType(1);
                }
                if (position == 30) {
                    if (!isNetwork) {
                        isStop = true;
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (isNetwork) {
                                    mHandler.post(mRunnable);
                                    getNetWorkType(2);
                                } else {
                                    initPopu("失败", "路由检测失败，请尝试一下措施：\n1.重启路由器，并靠近路由器重试\n2.切换4G网络重试");
                                    ivTwo.setVisibility(View.VISIBLE);
                                    skTwo.setVisibility(View.GONE);
                                    ivTwo.setImageResource(com.cooleshow.base.R.drawable.ic_network_error);
                                }
                            }
                        }, 2000);
                    } else {
                        getNetWorkType(2);
                    }
                }
                if (position == 60) {
                    getNetWorkType(3);
                }
                if (position == 100) {
                    getNetWorkType(4);
                }
            } catch (Exception e) {
            }
        });
    }
    @Override
    protected void onResume() {
        super.onResume();
        //        progess.setProgress(1);
        //        getNetWorkType(0);
        new Thread(new Runnable() {
            @Override
            public void run() {
                isNetwork = NetworkUtil.ping();
            }
        }).start();

    }


    @Override
    protected ActivityNetworkMonitoringBinding getLayoutView() {
        return ActivityNetworkMonitoringBinding.inflate(getLayoutInflater());
    }

    @Override
    protected NetworkMonitoringPresenter createPresenter() {
        return new NetworkMonitoringPresenter();
    }


    private void getNetWorkType(int i) {

        if (NetworkUtil.getNetWorkType(getApplicationContext()) == NetworkUtil.NETWORKTYPE_WIFI) {
            progess.setType("Wi-Fi");
        } else if (NetworkUtil.getNetWorkType(getApplicationContext()) == NetworkUtil.NETWORKTYPE_3G) {
            progess.setType("4G");
        } else if (NetworkUtil.getNetWorkType(getApplicationContext()) == NetworkUtil.NETWORKTYPE_2G) {
            progess.setType("2G");
        } else if (NetworkUtil.getNetWorkType(getApplicationContext()) == NetworkUtil.NETWORKTYPE_WAP) {
            progess.setType("WAP");
        } else if (NetworkUtil.getNetWorkType(getApplicationContext()) == NetworkUtil.NETWORKTYPE_INVALID) {
            progess.setType("无网络");
        }

        if (NetworkUtil.isNetworkAvailable(getApplicationContext())) {
            if (i == 1) {
                ivOne.setImageResource(normal);
            }
            if (i == 2) {
                ivTwo.setImageResource(normal);
            }
            if (i == 3) {
                ivThree.setImageResource(normal);
            }
            if (i == 4) {
                ivFour.setImageResource(normal);
            }
        } else {
            if (i == 1) {
                ivOne.setImageResource(com.cooleshow.base.R.drawable.ic_network_error);
                ivTwo.setImageResource(com.cooleshow.base.R.drawable.ic_network_error);
                ivThree.setImageResource(com.cooleshow.base.R.drawable.ic_network_error);
                ivFour.setImageResource(com.cooleshow.base.R.drawable.ic_network_error);
            }
            if (i == 2) {
                ivTwo.setImageResource(com.cooleshow.base.R.drawable.ic_network_error);
                ivThree.setImageResource(com.cooleshow.base.R.drawable.ic_network_error);
                ivFour.setImageResource(com.cooleshow.base.R.drawable.ic_network_error);
            }
            if (i == 3) {
                ivThree.setImageResource(com.cooleshow.base.R.drawable.ic_network_error);
                ivFour.setImageResource(com.cooleshow.base.R.drawable.ic_network_error);
            }
            if (i == 4) {
                ivFour.setImageResource(com.cooleshow.base.R.drawable.ic_network_error);
            }
        }
        if (0 == i) {
            ivOne.setVisibility(View.GONE);
            skOne.setVisibility(View.VISIBLE);
            ivTwo.setVisibility(View.GONE);
            skTwo.setVisibility(View.GONE);
            ivThree.setVisibility(View.GONE);
            skThree.setVisibility(View.GONE);
            ivFour.setVisibility(View.GONE);
            skFour.setVisibility(View.GONE);
        }
        if (1 == i) {
            ivOne.setVisibility(View.VISIBLE);
            skOne.setVisibility(View.GONE);
            ivTwo.setVisibility(View.GONE);
            skTwo.setVisibility(View.VISIBLE);
            ivThree.setVisibility(View.GONE);
            skThree.setVisibility(View.GONE);
            ivFour.setVisibility(View.GONE);
            skFour.setVisibility(View.GONE);
        }
        if (2 == i) {
            ivOne.setVisibility(View.VISIBLE);
            skOne.setVisibility(View.GONE);
            ivTwo.setVisibility(View.VISIBLE);
            skTwo.setVisibility(View.GONE);
            ivThree.setVisibility(View.GONE);
            skThree.setVisibility(View.VISIBLE);
            ivFour.setVisibility(View.GONE);
            skFour.setVisibility(View.GONE);
        }
        if (3 == i) {
            ivOne.setVisibility(View.VISIBLE);
            skOne.setVisibility(View.GONE);
            ivTwo.setVisibility(View.VISIBLE);
            skTwo.setVisibility(View.GONE);
            ivThree.setVisibility(View.VISIBLE);
            skThree.setVisibility(View.GONE);
            ivFour.setVisibility(View.GONE);
            skFour.setVisibility(View.VISIBLE);
        }
        if (4 == i) {
            ivOne.setVisibility(View.VISIBLE);
            skOne.setVisibility(View.GONE);
            ivTwo.setVisibility(View.VISIBLE);
            skTwo.setVisibility(View.GONE);
            ivThree.setVisibility(View.VISIBLE);
            skThree.setVisibility(View.GONE);
            ivFour.setVisibility(View.VISIBLE);
            skFour.setVisibility(View.GONE);

            if (NetworkUtil.getNetWorkType(getApplicationContext()) == NetworkUtil.NETWORKTYPE_3G
                    || NetworkUtil.getNetWorkType(getApplicationContext()) == NetworkUtil.NETWORKTYPE_WIFI) {
                initPopu("良好", "恭喜你！网络十分流畅");
            } else if (NetworkUtil.isNetworkAvailable(getApplicationContext())) {
                initPopu("不佳", "网络连接不佳，请尝试一下措施：\n1.重启路由器，并靠近路由器重试\n2.切换4G网络重试");
            } else {
                initPopu("无网络", "网络连接不佳，请尝试一下措施：\n1.重启路由器，并靠近路由器重试\n2.切换4G网络重试");
            }
        }


    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (hasFocus && isStart) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            isNetwork = false;
                            isNetwork = NetworkUtil.ping();
                        }
                    }).start();
                    isStart = false;
                    proges = 0;
                    ivOne.setVisibility(View.GONE);
                    skOne.setVisibility(View.VISIBLE);
                    ivTwo.setVisibility(View.GONE);
                    skTwo.setVisibility(View.GONE);
                    ivThree.setVisibility(View.GONE);
                    skThree.setVisibility(View.GONE);
                    ivFour.setVisibility(View.GONE);
                    skFour.setVisibility(View.GONE);
                    ivTwo.setImageResource(com.cooleshow.base.R.drawable.ic_network_error);
                    ivThree.setImageResource(com.cooleshow.base.R.drawable.ic_network_error);
                    ivFour.setImageResource(com.cooleshow.base.R.drawable.ic_network_error);
                    mRunnable = () -> {
                        if (isStop) {
                            isStop = false;
                            mHandler.removeCallbacks(mRunnable);
                        } else if (proges == 100) {
                            mHandler.removeCallbacks(mRunnable);
                        } else if (!NetworkUtil.isNetworkAvailable(getApplicationContext())) {
                            progess.setProgress(100);
                            mHandler.removeCallbacks(mRunnable);
                        } else {
                            progess.setProgress(proges += 1);
                            Random rand = new Random();
                            if (NetworkUtil.getNetWorkType(getApplicationContext()) == NetworkUtil.NETWORKTYPE_WIFI) {
                                if (5 < position && position < 30) {
                                    delayMillis = rand.nextInt(400);
                                } else {
                                    delayMillis = rand.nextInt(100);
                                }
                            } else if (NetworkUtil.getNetWorkType(getApplicationContext()) == NetworkUtil.NETWORKTYPE_3G) {
                                if (5 < position && position < 30) {
                                    delayMillis = rand.nextInt(400);
                                } else {
                                    delayMillis = rand.nextInt(100);
                                }
                            } else {
                                delayMillis = rand.nextInt(500);
                            }

                            mHandler.postDelayed(mRunnable, delayMillis);
                        }
                    };
                    mHandler.post(mRunnable);
                }
            }
        }, 500);

    }

    private void initPopu(String title, String content) {
        proges = 100;
        DialogUtil.showInCenter(getSupportFragmentManager(), R.layout.network_popu, new DialogUtil.ShowListener() {
            @Override
            public void onShow(ViewHolder holder, BaseDialog dialog) {
                TextView tvTitle = holder.getView(R.id.tv_title);
                TextView tvContent = holder.getView(R.id.tv_content);
                TextView btncancel = holder.getView(R.id.btn_cancel);
                TextView btnCommit = holder.getView(R.id.btn_commit);

                tvTitle.setText(title);
                if (title.equals("良好")) {
                    tvTitle.setTextColor(getResources().getColor(com.cooleshow.base.R.color.colorPrimary));
                    tvContent.setGravity(Gravity.CENTER);
                } else {
                    tvTitle.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_f85043));
                }
                tvContent.setText(content);
                btncancel.setOnClickListener(view1 -> {
                    finish();
                    dialog.dismiss();
                });
                btnCommit.setOnClickListener(view1 -> {
                    proges = 0;
                    isStart = true;
                    dialog.dismiss();
                });
            }
        });
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }
}
