package xn.hxp.ui;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.viewbinding.ViewBinding;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.king.zxing.util.CodeUtils;
import com.kongzue.dialogx.dialogs.PopTip;
import com.lxj.xpopup.XPopup;
import com.lztek.toolkit.Lztek;
import com.rc.core.ui.activity.BaseActivity;
import com.rc.httpcore.HttpClient;
import com.rc.httpcore.HttpConfig;
import com.rc.httpcore.bean.HxpChemicalVo;
import com.rc.httpcore.bean.RuleBean;
import com.rc.httpcore.client.ApiRepository;
import com.rc.httpcore.client.HttpTool;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.rxjava3.functions.Consumer;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import okhttp3.Response;
import xn.hxp.R;
import xn.hxp.app.ChemicalApp;
import xn.hxp.databinding.ActivityMainBinding;
import xn.hxp.receiver.TimeTickReceiver;
import xn.hxp.receiver.UhfRfidManager;
import xn.hxp.ui.adapter.CabinetBannerAdapter;
import xn.hxp.ui.discard.LedgerActivity;
import xn.hxp.ui.discard.WasteChemicalsActivity;
import xn.hxp.ui.inquiry.InquiryActivity;
import xn.hxp.ui.login.FaceLoginActivity;
import xn.hxp.ui.login.FacialCardActivity;
import xn.hxp.ui.login.ScanLoginActivity;
import xn.hxp.ui.login.SwipeActivity;
import xn.hxp.ui.plan.PlanAddActivity;
import xn.hxp.ui.plan.already.AlreadyActivity;
import xn.hxp.ui.plan.already.AlreadyAdapter;
import xn.hxp.ui.plan.already.AlreadyBean;
import xn.hxp.ui.still.ChemicalsAlsoActivity;
import xn.hxp.ui.still.MsdsActivity;
import xn.hxp.ui.uses.UseActivity;
import xn.hxp.ui.uses.WarningEventsActivity;
import xn.hxp.ui.warehousing.ChemicalLabelingActivity;
import xn.hxp.utils.RelativeLayoutDebouncer;
import xn.hxp.utils.SharedPreferencesHelper;
import xn.hxp.utils.TimeUpdater;
import xn.hxp.utils.UiManager;
import xn.hxp.weidith.CustomAttachPopup;
import xn.hxp.weidith.CustomDialog;
import xn.hxp.weidith.PlanDialog;

public class MainActivity extends BaseActivity {

    private List<RuleBean> ruleBeanList = new ArrayList<>();

    private ActivityMainBinding viewBinding;
    private TimeUpdater timeUpdater;
    private Lztek mLztek;
    private String mDeviceNum;
    private List<String> faceList;
    private String mLoginType;
    private int mCounter = 0;
    private int MAX_TIME = 60;
    private static final int WHAT_COUNT_DOWN = 1;
    private TimeTickReceiver timeTickReceiver = new TimeTickReceiver();
    private PlanDialog planDialog;
    private CountDownTimer heartbeatCdTimer;

    @Override
    protected void onResume() {
        super.onResume();
        if (ChemicalApp.userData != null) {
            viewBinding.inc.userLogin.setVisibility(View.GONE);
            viewBinding.inc.loggedIn.setVisibility(View.VISIBLE);
            viewBinding.inc.tvName.setText(ChemicalApp.userData.userName);
            Glide.with(this)
                    .load(HttpConfig.Companion.getAPI_BASE_IMG_URL() + ChemicalApp.userData.avatar)
                    .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.AUTOMATIC))
                    .into(viewBinding.inc.imageName);

            viewBinding.inc.imgE.setBackgroundResource(R.mipmap.cshrk_dl_tc);
            MAX_TIME = ChemicalApp.confs.getSignOutTime();
            mCountDownHandler.removeMessages(WHAT_COUNT_DOWN);
            mCountDownHandler.sendEmptyMessage(WHAT_COUNT_DOWN);
        } else {
            viewBinding.inc.loggedIn.setVisibility(View.GONE);
            viewBinding.inc.userLogin.setVisibility(View.VISIBLE);
            viewBinding.inc.imgE.setBackgroundResource(R.mipmap.icon_login_img);
        }

        timeUpdater.startUpdating();
        getCabinetIn();
        basicConf();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerReceiver(timeTickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));

        viewBinding.versionName.setText("版本号：" + AppUtils.getAppVersionName());
        viewBinding.cabinetVP.setIndicatorSliderColor(Color.parseColor("#80E0E0E0"), Color.WHITE);
        viewBinding.cabinetVP.setIndicatorSliderWidth(16);
        viewBinding.cabinetVP.registerLifecycleObserver(getLifecycle()).setAdapter(new CabinetBannerAdapter(new CabinetBannerAdapter.VerifyCallBack() {
            @Override
            public void login() {
                basicConfLog();
            }
        })).create(ruleBeanList);
        viewBinding.test.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {

                if (!AppUtils.isAppDebug()) {
                    showTextInputDialog("请输入内容", new TextInputCallback() {
                        @Override
                        public void onInput(String input) {
                            if (input != null) {
                                if (!input.isEmpty()) {
                                    try {
                                        if ("admin@098&".equals(input)) {
                                            ActivityUtils.startActivity(SettingActivity.class);
                                            finish();
                                        } else {
                                            SettingsBean urlBase = SharedPreferencesHelper.INSTANCE.getUrlBase(MainActivity.this);
                                            if (urlBase != null && urlBase.getPwd() != null) {
                                                if (input.equals(urlBase.getPwd())) {
                                                    ActivityUtils.startActivity(SettingActivity.class);
                                                    finish();
                                                } else {
                                                    showToast("密码错误");
                                                }
                                            }
                                        }
                                    } catch (Exception e) {
                                        ActivityUtils.startActivity(SettingActivity.class);
                                        finish();
                                    }
                                }
                            } else {
                                showToast("用户取消了输入");
                            }
                        }
                    });
                } else {
                    ActivityUtils.startActivity(SettingActivity.class);
                    finish();
                }
            }
        });

        viewBinding.inc.bleIV.setVisibility(View.VISIBLE);
        String sppMac = SPUtils.getInstance().getString("sppMac", "");
        if (sppMac == null || TextUtils.isEmpty(sppMac)) {
            viewBinding.inc.bleIV.setBackgroundResource(R.drawable.ic_ble_unconnected);
            PopTip.show("未配置蓝牙称设备!").showLong();
        }

        // 心跳上报
        heartbeatCdTimer = new

                CountDownTimer(20000, 1000) {
                    @Override
                    public void onTick(long millisUntilFinished) {

                    }

                    @Override
                    public void onFinish() {
                        AsyncTask.execute(() -> {
                            try {
                                HttpTool.heartbeat();
                            } catch (Exception e) {
                                LogUtils.e(Log.getStackTraceString(e));
                            }
                        });
                        heartbeatCdTimer.start();
                    }
                }

        ;
        heartbeatCdTimer.start();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        // 首页不在白名单中，消费掉外置RFID读卡器的输入，避免引起页面异常
        if (UhfRfidManager.INSTANCE.isEnabled(this) && UhfRfidManager.INSTANCE.isUhfRfidEvent(this, event)) {
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onStop() {
        super.onStop();
        LogUtils.i("============onStop");
    }

    @Override
    protected void onPause() {
        LogUtils.i("============onPause");
        try {
            timeUpdater.stopUpdating();
            LogUtils.i("========UI在刷新停止");
            mCountDownHandler.removeMessages(WHAT_COUNT_DOWN);
            mCountDownHandler.removeCallbacksAndMessages(null);
        } catch (Exception e) {
        }
        super.onPause();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    private void getCabinetIn() {
        showLoading("查询中...");
        addDisposable(ApiRepository.INSTANCE.getCabinetBySubId(ChemicalApp.subjectId)
                .subscribe(data -> {
                    dismissLoading();
                    ruleBeanList.clear();
                    ruleBeanList.addAll(data);
                    if (ruleBeanList.size() > 1) {
                        viewBinding.last.setVisibility(View.VISIBLE);
                        viewBinding.next.setVisibility(View.VISIBLE);
                    } else {
                        viewBinding.last.setVisibility(View.GONE);
                        viewBinding.next.setVisibility(View.GONE);
                    }
                    viewBinding.cabinetVP.refreshData(ruleBeanList);
                }, throwable -> {
                    dismissLoading();
                    throwable.printStackTrace();
                }));
    }

    private void getUserIds() {
        if (ChemicalApp.subjectId != null) {
            showLoading("查询中...");
            ApiRepository.INSTANCE.getUserIds(ChemicalApp.subjectId)
                    .subscribe(data -> {
                        dismissLoading();
                        faceList = data;
                    }, throwable -> {
                        dismissLoading();
                    });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(timeTickReceiver);
        try {
            timeUpdater.stopUpdating();
            mCountDownHandler.removeMessages(WHAT_COUNT_DOWN);
            mCountDownHandler.removeCallbacksAndMessages(null);
        } catch (Exception e) {
        }
    }

    private void basicConf() {
        ApiRepository.INSTANCE.basicConfig(ChemicalApp.subjectId)
                .subscribe(data -> {
                    ChemicalApp.confs = data;
                    mLoginType = data.getLoginType();
                    if (data.getLevelName() != null) {
                        if (!TextUtils.isEmpty(data.getLevelName())) {
                            String text = data.getLevelName();
                            if (text.length() > 1) {
                                viewBinding.tvNoName.setText(text.substring(0, 1));
                            }
                        }

                        GradientDrawable shapes = new GradientDrawable();
                        shapes.setShape(GradientDrawable.RECTANGLE);
                        shapes.setColor(Color.parseColor(data.getLevelColor()));
                        shapes.setCornerRadius(5f);
                        viewBinding.levelLL.setBackground(shapes);
                    } else {
                        viewBinding.levelLL.setVisibility(View.GONE);
                    }
                    viewBinding.subName.setText(data.getSubName());
                    viewBinding.inc.deptName.setText(data.getDeptName());
                    Glide.with(this)
                            .load(HttpConfig.Companion.getAPI_BASE_IMG_URL() + data.getCircularLogo())
                            .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.AUTOMATIC))
                            .into(viewBinding.inc.circularLogo);
                }, this::showNetError);
    }

    private void basicConfLog() {
        ApiRepository.INSTANCE.basicConfig(ChemicalApp.subjectId)
                .subscribe(data -> {
                    LogUtils.json(data);
                    ChemicalApp.confs = data;
                    mLoginType = data.getLoginType();
                    if (mLoginType == null) {
                        customDialogView(2, "登录方式配置有误");
                    } else {
                        if (mLoginType.contains("4")) {
                            UiManager.INSTANCE.switcher(this, FacialCardActivity.class);
                        } else {
                            Map<String, String> map = new HashMap<>();
                            if (mLoginType.length() == 1) {
                                switch (mLoginType) {
                                    case "1":
                                        map.put("faceList", faceList.toString());
                                        map.put("mtypes", "1");
                                        UiManager.INSTANCE.switcher(this, map, FaceLoginActivity.class);
                                        break;
                                    case "2":
                                        map.put("mtypes", "1");
                                        UiManager.INSTANCE.switcher(this, map, SwipeActivity.class);
                                        break;
                                    default:
                                        map.put("mtypes", "1");
                                        UiManager.INSTANCE.switcher(this, map, ScanLoginActivity.class);
                                        break;
                                }
                            } else {
                                String[] array = mLoginType.split(",");
                                if (array.length == 2) {
                                    if (mLoginType.equals("1,2") || mLoginType.equals("2,1")) {
                                        map.put("faceList", faceList.toString());
                                        map.put("mtypes", "4");
                                        UiManager.INSTANCE.switcher(this, map, FaceLoginActivity.class);
                                    } else if (mLoginType.equals("1,3") || mLoginType.equals("3,1")) {
                                        map.put("faceList", faceList.toString());
                                        map.put("mtypes", "5");
                                        UiManager.INSTANCE.switcher(this, map, FaceLoginActivity.class);
                                    } else if (mLoginType.equals("2,3") || mLoginType.equals("3,2")) {
                                        map.put("mtypes", "6");
                                        UiManager.INSTANCE.switcher(this, map, SwipeActivity.class);
                                    } else {
                                        showToast("登录方式" + mLoginType);
                                    }
                                } else {
                                    try {
                                        map.put("mtypes", "0");
                                        map.put("faceList", faceList.toString());
                                        UiManager.INSTANCE.switcher(this, map, FaceLoginActivity.class);
                                    } catch (Exception e) {
                                        map.put("mtypes", "0");
                                        UiManager.INSTANCE.switcher(this, map, SwipeActivity.class);
                                    }
                                }
                            }
                        }
                    }
                }, this::showNetError);
    }

    private void customDialogView(int types, String msg) {
        CustomDialog customDialog = new CustomDialog(this, types, msg);
        if (!this.isFinishing() && !this.isDestroyed()) {
            customDialog.show();
        }
    }

    private final Handler mCountDownHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (WHAT_COUNT_DOWN == msg.what) {
                int countDown = MAX_TIME - mCounter;
                if (isDestroyed()) return;
                if (countDown <= 0) {
                    ChemicalApp.confs = null;
                    ChemicalApp.subjectId = null;
                    ChemicalApp.userData = null;
                    callLogoutApis(success -> {
                        ActivityUtils.startActivity(StartActivity.class);
                    });
                } else {
                    sendEmptyMessageDelayed(WHAT_COUNT_DOWN, 1000);
                }
                mCounter++;
            }
        }
    };

    @Override
    public void onUserInteraction() {
        mCounter = 0;
    }

    @Override
    protected void cdFinish() {
    }

    @Override
    protected void cdTime(int cd) {
    }

    @Override
    protected ViewBinding setViewBinding() {
        viewBinding = ActivityMainBinding.inflate(getLayoutInflater());
        return viewBinding;
    }

    @Override
    protected void onInit() {
        getUserIds();
        Handler handler = new Handler(Looper.getMainLooper());
        timeUpdater = new TimeUpdater(handler, new Function1<String, Unit>() {
            @Override
            public Unit invoke(String s) {
                viewBinding.inc.nowTime.setText(s);
                return null;
            }
        });
        timeUpdater.startUpdating();

        viewBinding.last.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                viewBinding.cabinetVP.previousPage();
            }
        });
        viewBinding.next.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                viewBinding.cabinetVP.nextPage();
            }
        });


        RelativeLayoutDebouncer.Companion.setDebouncedOnClickListener(viewBinding.inc.userLogin, 1000L, v -> {
            basicConfLog();
        });

        // 存储
        viewBinding.addChemicals.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                //新增
                if (ChemicalApp.userData != null) {
                    if (ChemicalApp.administrators || ChemicalApp.responsibles) {
                        getHxpStockWait();
                    } else {
                        customDialogView(2, "当前人员无权限");
                    }
                } else {
                    basicConfLog();
                }
            }
        });

        viewBinding.reDis.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                if (ChemicalApp.userData != null) {
                    UiManager.INSTANCE.switcher(MainActivity.this, WasteChemicalsActivity.class);
                } else {
                    basicConfLog();
                }
            }
        });

        viewBinding.reInq.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                Map<String, Object> map = new HashMap<>();
                map.put("logIn", ChemicalApp.userData != null ? 1 : 0);
                map.put("cabinetId", "a");
                map.put("doorId", "a");
                UiManager.INSTANCE.switcher(MainActivity.this, map, InquiryActivity.class);
            }
        });

        viewBinding.reCla.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                if (ChemicalApp.userData != null) {
                    UiManager.INSTANCE.switcher(MainActivity.this, UseActivity.class);
                } else {
                    basicConfLog();
                }
            }
        });

        viewBinding.reRet.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                if (ChemicalApp.userData != null) {
                    UiManager.INSTANCE.switcher(MainActivity.this, ChemicalsAlsoActivity.class);
                } else {
                    basicConfLog();
                }
            }
        });

        viewBinding.rlLedger.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                if (ChemicalApp.userData != null) {
                    UiManager.INSTANCE.switcher(MainActivity.this, LedgerActivity.class);
                } else {
                    basicConfLog();
                }
            }
        });

        viewBinding.reLedger.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                if (ChemicalApp.userData != null) {
                    UiManager.INSTANCE.switcher(MainActivity.this, ChemicalLabelingActivity.class);
                } else {
                    basicConfLog();
                }
            }
        });

        viewBinding.rlWarning.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                if (ChemicalApp.userData != null) {
                    UiManager.INSTANCE.switcher(MainActivity.this, WarningEventsActivity.class);
                } else {
                    basicConfLog();
                }
            }
        });

        viewBinding.rlDem.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                UiManager.INSTANCE.switcher(MainActivity.this, MsdsActivity.class);
            }
        });

        viewBinding.inc.tvOutLogin.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                ChemicalApp.userData = null;
                ChemicalApp.subjectId = null;
                HttpClient.INSTANCE.setToken(null);
                ActivityUtils.startActivity(StartActivity.class);
            }
        });

        basicConf();


        viewBinding.caozuoRL.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                viewBinding.caozuoRL.setVisibility(View.GONE);
                viewBinding.caozuoQrRL.setVisibility(View.VISIBLE);
                viewBinding.caozuoQrRL.postDelayed(() -> {
                    viewBinding.caozuoRL.setVisibility(View.VISIBLE);
                    viewBinding.caozuoQrRL.setVisibility(View.GONE);
                }, 1000 * 60);
            }
        });

        viewBinding.caozuoRL.post(() -> {
            Bitmap qrCode = CodeUtils.createQRCode(
                    "https://labcontrol.nwafu.edu.cn/api/?type=14",
                    120
            );
            viewBinding.caozuoQr.setImageBitmap(qrCode);
        });
    }

    private void callLogoutApis(LogoutCallback callback) {
        showLoading("退出中...");
        ApiRepository.INSTANCE.loginOut().subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Throwable {
                dismissLoading();
                if (callback != null) callback.onComplete(true);
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Throwable {
                dismissLoading();
                if (callback != null) callback.onComplete(false);
            }
        });
    }

    private void showTextInputDialog(String title, TextInputCallback callback) {
        EditText editText = new EditText(this);
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle(title)
                .setView(editText)
                .setPositiveButton("确定", (dialog1, which) -> {
                    String inputText = editText.getText().toString();
                    callback.onInput(inputText);
                })
                .setNegativeButton("取消", (dialog1, which) -> {
                    callback.onInput(null);
                })
                .create();
        dialog.show();
    }

    interface TextInputCallback {
        void onInput(String input);
    }

    interface LogoutCallback {
        void onComplete(boolean success);
    }


    /**
     * 获取已申领未入库列表
     */
    private void getHxpStockWait() {
        showLoading("加载中...");
        ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<AlreadyBean>() {
            @Override
            public AlreadyBean doInBackground() throws Throwable {
                Response response = HttpTool.getHxpStockWait(0, ChemicalApp.subjectId, 1, 10, "", "", "");
                String json = response.body().string();
                JSONObject jsonObject = new JSONObject(json);
                if (jsonObject.getInt("code") == 200) {
                    return GsonUtils.fromJson(jsonObject.getJSONObject("data").toString(), AlreadyBean.class);
                } else {
                    String msg = jsonObject.getString("message");
                    ToastUtils.showLong(msg);
                    return null;
                }
            }

            @Override
            public void onSuccess(AlreadyBean result) {
                if (null != result) {
                    AlreadyBean.PageData pageData = result.getPageData();
                    if (null != pageData && pageData.getPages() > 0) {
                        planDialog = new PlanDialog(MainActivity.this, v -> {
                            UiManager.INSTANCE.switcher(MainActivity.this, AlreadyActivity.class);
                            planDialog.dismiss();
                        }, v -> {
                            UiManager.INSTANCE.switcher(MainActivity.this, PlanAddActivity.class);
                            planDialog.dismiss();
                        });
                        planDialog.show();
                    } else {
                        UiManager.INSTANCE.switcher(MainActivity.this, PlanAddActivity.class);
                    }
                } else {
                    UiManager.INSTANCE.switcher(MainActivity.this, PlanAddActivity.class);
                }
                dismissLoading();
            }
        });
    }
}