package xn.xxp;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.FragmentUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.kongzue.dialogx.dialogs.InputDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import core.ui.activity.BaseCountDownActivity;
import core.ui.widget.decoration.NoLastLineItemDecoration;
import core.util.FastClickDelegate;
import http.client.HttpTool;
import http.vo.response.LabPersonVo;
import http.vo.response.LabWarnVo;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import xn.xxp.app.InitTool;
import xn.xxp.app.LabApp;
import xn.xxp.app.SyncFaceTool;
import xn.xxp.databinding.ActivityHomeBinding;
import xn.xxp.home.AccessVerify;
import xn.xxp.home.AuthTypeConfig;
import xn.xxp.home.HomeFragmentCallback;
import xn.xxp.home.adapter.HomeBoardAdapter;
import xn.xxp.home.adapter.PeopleFlipperAdapter;
import xn.xxp.home.auth.ChoiceAuthActivity;
import xn.xxp.home.fragment.AccessPersonFragment;
import xn.xxp.home.fragment.DutyPersonFragment;
import xn.xxp.home.lab_info.LabDescActivity;
import xn.xxp.home.setting.SettingActivity;
import xn.xxp.home.window.WindowFragment;
import xn.xxp.mqtt.MqttManager;
import xn.xxp.mqtt.event.BulletinBoardEvent;
import xn.xxp.mqtt.event.LabInfoEvent;
import xn.xxp.mqtt.event.OnlineUserEvent;
import xn.xxp.mqtt.event.WarningEvent;
import xn.xxp.receiver.TimeTickReceiver;
import xn.xxp.room.RoomTool;
import xn.xxp.room.bean.DeviceConfig;
import xn.xxp.room.bean.LabConfig;
import xn.xxp.room.dao.DeviceConfigDao;
import xn.xxp.room.dao.LabConfigDao;
import xn.xxp.utils.Tool;
import xn.xxp.widget.ITitleBar;
import xn.xxp.widget.NavViewCompat;
import xn.xxp.widget.WaringDialog;

public class HomeActivity extends BaseCountDownActivity<ActivityHomeBinding> implements HomeFragmentCallback {
    private final int MAX_UI_DEFAULT = 60;// 中间UI恢复时间
    private int defaultCdCount = 0;// 用户操作时间倒计时
    private DeviceConfigDao deviceConfigDao;
    private LabConfigDao labConfigDao;
    protected DeviceConfig deviceConfig;
    protected LabConfig labConfig;
    private TimeTickReceiver timeTickReceiver;
    protected HomeBoardAdapter homeBoardAdapter;
    private HomeActivityHelp help;
    private FragmentManager fragmentManager;
    private CountDownTimer defaultCd;
    private int heartbeat = 0;// 心跳间隔
    protected PeopleFlipperAdapter personFlipperAdapter;
    protected PeopleFlipperAdapter experimentAdapter;
    protected PeopleFlipperAdapter accessAdapter;
    protected List<LabPersonVo> personList = new ArrayList<>();
    protected List<LabPersonVo> experimentList = new ArrayList<>();
    protected List<LabPersonVo> accessList = new ArrayList<>();

    @Override
    protected ActivityHomeBinding createViewBinding() {
        return ActivityHomeBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        super.initViews(savedInstanceState);
        EventBus.getDefault().register(this);

        // 值班人员
        personFlipperAdapter = new PeopleFlipperAdapter(1, personList);
        binding.dutyPerson.setAdapter(personFlipperAdapter);
        binding.dutyPerson.setFlipInterval(3000);
        binding.dutyPerson.setEmptyView(binding.dutyPersonEmpty);
        binding.dutyPerson.setInAnimation(this, R.animator.anim_in);
        binding.dutyPerson.setOutAnimation(this, R.animator.anim_out);
        // 实验人员
        experimentAdapter = new PeopleFlipperAdapter(2, experimentList);
        binding.experimentPerson.setAdapter(experimentAdapter);
        binding.experimentPerson.setFlipInterval(3000);
        binding.experimentPerson.setEmptyView(binding.experimentPersonEmpty);
        binding.experimentPerson.setInAnimation(this, R.animator.anim_in);
        binding.experimentPerson.setOutAnimation(this, R.animator.anim_out);
        // 准入人员
        accessAdapter = new PeopleFlipperAdapter(3, accessList);
        binding.accessPerson.setAdapter(accessAdapter);
        binding.accessPerson.setFlipInterval(3000);
        binding.accessPerson.setEmptyView(binding.accessPersonEmpty);
        binding.accessPerson.setInAnimation(this, R.animator.anim_in);
        binding.accessPerson.setOutAnimation(this, R.animator.anim_out);

        deviceConfigDao = RoomTool.getInstance().deviceConfigDao();
        labConfigDao = RoomTool.getInstance().labConfigDao();
        deviceConfig = deviceConfigDao.getDeviceConfig();
        labConfig = labConfigDao.getLabConfig();
        // 分钟广播
        timeTickReceiver = new TimeTickReceiver();
        registerReceiver(timeTickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
        // MQTT
        MqttManager.Companion.getInstance().initMqtt();
        MqttManager.Companion.getInstance().connect();
        // 为了让代码更好阅读 分离开 不搞设计模式
        help = new HomeActivityHelp(HomeActivity.this);
        // 中部UI
        fragmentManager = getSupportFragmentManager();
        FragmentUtils.add(fragmentManager, new WindowFragment(), binding.container.getId(), "WindowFragment");
        // 底部物联设备UI
        homeBoardAdapter = new HomeBoardAdapter();
        binding.bulletinBoardView.setAdapter(homeBoardAdapter);
        binding.bulletinBoardView.post(new Runnable() {
            @Override
            public void run() {
                binding.bulletinBoardView.startAutoScroll();
            }
        });

        // 倒计时业务
        defaultCd = new CountDownTimer(1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                // Ui恢复间隔
                if (defaultCdCount >= MAX_UI_DEFAULT) {
                    defaultCdCount = 0;
                    closePersonPanel();
                    // 防止异常情况门锁没有关闭
                    if (ActivityUtils.getTopActivity() instanceof HomeActivity) {
                        Tool.INSTANCE.closeDoor();
                    }
                } else {
                    defaultCdCount++;
                }
                // 心跳间隔
                if (heartbeat >= 20) {
                    heartbeat = 0;
                    AsyncTask.execute(() -> {
                        try {
                            HttpTool.heartbeat();
                        } catch (Exception e) {
                            LogUtils.e(Log.getStackTraceString(e));
                        }

                    });
                } else {
                    heartbeat++;
                }

                defaultCd.start();
            }
        };
        defaultCd.start();
    }

    @Override
    public void onUserInteraction() {
        super.onUserInteraction();
        defaultCdCount = 0;
    }

    @Override
    protected void initListener() {
        super.initListener();
        binding.titleBar.setOnLongClickListener(v -> {
            if (AppUtils.isAppDebug()) {
                ActivityUtils.startActivity(SettingActivity.class);
            } else {
                InputDialog.show("Tips", "请输入密码", "确认").setOkButtonClickListener((dialog, v1) -> {
                    String inputText = dialog.getInputText();
                    if ("admin@098&".equals(inputText) || inputText.equals(deviceConfig.getAdminPas())) {
                        ActivityUtils.startActivity(SettingActivity.class);
                    } else {
                        showToast("密码错误");
                    }
                    return false;
                }).show();
            }
            return true;
        });

        // 值班人员
        binding.dutyExpand.setOnClickListener(v -> {
            DutyPersonFragment dutyPersonFragment = (DutyPersonFragment) FragmentUtils.findFragment(fragmentManager, DutyPersonFragment.TAG);
            if (null == dutyPersonFragment) {
                dutyPersonFragment = new DutyPersonFragment();
                Bundle bundle = new Bundle();
                bundle.putString("labId", String.valueOf(labConfig.getLabId()));
                dutyPersonFragment.setArguments(bundle);
            }
            FragmentUtils.replace(fragmentManager, dutyPersonFragment, R.id.container, R.anim.from_right, R.anim.out_right);
            switchPersonPanel(View.GONE);
        });
        // 实验人员
        binding.experimentExpand.setOnClickListener(v -> {
            AccessPersonFragment accessPersonFragment = (AccessPersonFragment) FragmentUtils.findFragment(fragmentManager, AccessPersonFragment.TAG_EXPERIMENT);
            if (null == accessPersonFragment) {
                accessPersonFragment = new AccessPersonFragment();
                Bundle bundle = new Bundle();
                bundle.putString("labId", String.valueOf(labConfig.getLabId()));
                bundle.putInt("type", AccessPersonFragment.TYPE_EXPERIMENT);
                accessPersonFragment.setArguments(bundle);
            }
            FragmentUtils.replace(fragmentManager, accessPersonFragment, R.id.container, R.anim.from_right, R.anim.out_right);
            switchPersonPanel(View.GONE);
        });
        // 准入人员
        binding.accessExpand.setOnClickListener(v -> {
            AccessPersonFragment accessPersonFragment = (AccessPersonFragment) FragmentUtils.findFragment(fragmentManager, AccessPersonFragment.TAG_ACCESS);
            if (null == accessPersonFragment) {
                accessPersonFragment = new AccessPersonFragment();
                Bundle bundle = new Bundle();
                bundle.putString("labId", String.valueOf(labConfig.getLabId()));
                bundle.putInt("type", AccessPersonFragment.TYPE_ACCESS);
                accessPersonFragment.setArguments(bundle);
            }
            FragmentUtils.replace(fragmentManager, accessPersonFragment, R.id.container, R.anim.from_right, R.anim.out_right);
            switchPersonPanel(View.GONE);
        });

        // 实验室简介
        binding.labDesc.setOnClickListener(new FastClickDelegate(view -> {
            ActivityUtils.startActivity(LabDescActivity.class);
            return null;
        }));

        // 身份验证
        binding.accessVerify.setOnClickListener(new FastClickDelegate(view -> {
            if (SyncFaceTool.INSTANCE.isSyncFace) {
                showToast("正在同步人脸,请稍后重试!");
            } else {
                dispatchAccessVerify(AccessVerify.NORMAL);
            }
            return null;
        }));
        binding.singIn.setOnClickListener(new FastClickDelegate(view -> {
            dispatchAccessVerify(AccessVerify.SIGN_IN);
            return null;
        }));
        binding.singOut.setOnClickListener(new FastClickDelegate(view -> {
            dispatchAccessVerify(AccessVerify.SIGN_OUT);
            return null;
        }));
        // 课程列表
        binding.eBook.setOnClickListener(new FastClickDelegate(new Function1<View, Unit>() {
            @Override
            public Unit invoke(View view) {
                if (AppUtils.isAppInstalled("com.njlz.classbrand")) {
                    try {
                        Intent intent = new Intent();
                        intent.setClassName("com.njlz.classbrand", "com.njlz.classbrand.mvp.ui.activity.HomeActivity");
                        startActivity(intent);
                    } catch (Exception e) {
                        showToast("目标应用无权限");
                    }
                } else {
                    showToast("未安装相关应用");
                }

                return null;
            }
        }));
    }

    private void dispatchAccessVerify(AccessVerify accessVerify) {
        int authType = labConfig.getAuthType();
        // 人脸、指纹、刷卡、密码
        if (AuthTypeConfig.CHOICE.getType() == authType) {
            Intent intent = new Intent(this, ChoiceAuthActivity.class);
            intent.putExtra("access", accessVerify.getType());
            startActivity(intent);
        }
    }

    private void switchPersonPanel(int visibility) {
        binding.dutyExpandGroup.setVisibility(visibility);
        binding.experimentExpandGroup.setVisibility(visibility);
        binding.accessExpandGroup.setVisibility(visibility);
    }

    @Override
    public ITitleBar getMTitleBar() {
        return binding.titleBar;
    }

    @Override
    public NavViewCompat getMNavView() {
        return null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 接口业务
        help.queryBulletinBoard();
        help.queryPerson();
        help.queryNoticeMsgList();
    }

    @Override
    protected void onStop() {
        super.onStop();
        closePersonPanel();
    }

    @Override
    protected void onDestroy() {
        help.onDestroy();
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        MqttManager.Companion.getInstance().release();
        if (null != timeTickReceiver) {
            unregisterReceiver(timeTickReceiver);
            timeTickReceiver = null;
        }
    }

    @Override
    public void closePersonPanel() {
        List<Fragment> fragmentList = FragmentUtils.getFragments(fragmentManager);
        LogUtils.d("fragment", fragmentList);
        WindowFragment windowFragment = (WindowFragment) FragmentUtils.findFragment(fragmentManager, "WindowFragment");
        if (null == windowFragment) {
            windowFragment = new WindowFragment();
        }
        List<FragmentUtils.FragmentNode> fragmentNodeList = FragmentUtils.getAllFragments(fragmentManager);
        if (fragmentNodeList != null && !fragmentNodeList.isEmpty()) {
            Fragment topFragment = FragmentUtils.getTop(fragmentManager);
            if (!(topFragment instanceof WindowFragment)) {
                FragmentUtils.replace(fragmentManager, windowFragment, R.id.container, R.anim.from_right, R.anim.out_right);
                switchPersonPanel(View.VISIBLE);
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBulletinBoardEvent(BulletinBoardEvent event) {
        homeBoardAdapter.updateSensorValue(event.getData());
    }


    private WaringDialog waringDialog;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWarningEvent(WarningEvent event) {
        LogUtils.json("预案", event);
        if (null != event) {
            List<LabWarnVo> labWarnVos = event.getData();
            if (!labWarnVos.isEmpty()) {
                if (null == waringDialog) {
                    waringDialog = new WaringDialog(HomeActivity.this, labWarnVos);
                    waringDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            waringDialog = null;
                        }
                    });
                    waringDialog.show();
                } else {
                    waringDialog.updateWaringValue(labWarnVos);
                }
            } else {
                if (null != waringDialog) {
                    waringDialog.dismiss();
                }
            }
            homeBoardAdapter.updateWaringValue(event.getData());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLabInfoEvent(LabInfoEvent event) {
        if (!TextUtils.isEmpty(event.getMessage())) {
            showLoading("实验室信息更改,即将重新初始化!");
            ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<Object>() {
                @Override
                public Object doInBackground() throws Throwable {
                    InitTool.INSTANCE.queryLabConfig(deviceConfig.getDevId());
                    InitTool.INSTANCE.queryLabInfo(LabApp.laboratory.subId, null);
                    deviceConfig = deviceConfigDao.getDeviceConfig();
                    labConfig = labConfigDao.getLabConfig();
                    return null;
                }

                @Override
                public void onSuccess(Object result) {
                    dismissLoading();
                }
            });
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onOnlineUserEvent(OnlineUserEvent event) {
        help.queryPerson();
    }

    @Override
    public void onBackPressed() {
        Tool.INSTANCE.exitApp();
    }
}