package com.example.iot_controlhost.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import android.view.MotionEvent;
import android.view.View;

import androidx.lifecycle.ViewModelProvider;

import com.blankj.utilcode.constant.TimeConstants;
import com.blankj.utilcode.util.TimeUtils;
import com.example.iot_controlhost.R;
import com.example.iot_controlhost.adapter.ModelsAdapter;
import com.example.iot_controlhost.base.BaseActivity;
import com.example.iot_controlhost.databinding.ActivityIncubationBinding;
import com.example.iot_controlhost.model.Silkworm;
import com.example.iot_controlhost.model.SilkwormNew;
import com.example.iot_controlhost.model.net.WorkList;
import com.example.iot_controlhost.ui.dialog.ConfirmDialog;
import com.example.iot_controlhost.ui.dialog.LogDialog;
import com.example.iot_controlhost.ui.dialog.MessageDialog;
import com.example.iot_controlhost.ui.dialog.PasswordDialog;
import com.example.iot_controlhost.ui.dialog.SetBaseDialog;
import com.example.iot_controlhost.ui.dialog.THBiasDialog;
import com.example.iot_controlhost.ui.dialog.WeatherDialog;
import com.example.iot_controlhost.ui.dialog.WorkDialog;
import com.example.iot_controlhost.ui.dialog.WorkNewDialog;
import com.example.iot_controlhost.ui.viewmodel.AppBarViewModel;
import com.example.iot_controlhost.utils.AppUpdateUtil;
import com.example.iot_controlhost.utils.DateUtils;
import com.example.iot_controlhost.utils.FrpUpdateUtil;
import com.example.iot_controlhost.utils.MMKVUtil;
import com.example.iot_controlhost.utils.MyUtil;
import com.example.iot_controlhost.utils.PollingTask;
import com.example.iot_controlhost.utils.database.SilkwormDBManager;
import com.example.iot_controlhost.utils.global.AIModelSet;
import com.example.iot_controlhost.utils.global.RoomSensor;
import com.example.iot_controlhost.utils.global.RoomSetting;
import com.example.iot_controlhost.utils.log.MyLog;
import com.xuexiang.rxutil2.rxjava.RxJavaUtils;
import com.xuexiang.rxutil2.rxjava.task.RxAsyncTask;

import java.util.ArrayList;
import java.util.Date;

import es.dmoral.toasty.Toasty;

public class MainActivity extends BaseActivity<ActivityIncubationBinding, MainActivityPresenter> {
    /**
     * 实现再按一次退出程序
     */
    private long mExitTime;
    AppBarViewModel appBarViewModel;
    WorkDialog workDialog;
    private PasswordDialog lockPasswordDialog;
    private final Handler lockHandler = new Handler(Looper.getMainLooper());
    private final Runnable lockRunnable = this::lock;
    private int showingDialogCount;
    private boolean mainPageResumed;

    @Override
    public void initView() {
        //判断是否需要升级
        AppUpdateUtil.updateAPP(mContext, true, false);
        //观察显示开始共育弹窗
        if (RoomSetting.isDarkTheme()) {
            binding.textView7.setTextColor(Color.parseColor("#33FFFFFF"));
            binding.textView8.setTextColor(Color.parseColor("#33FFFFFF"));
            binding.textView0.setTextColor(Color.parseColor("#FFFFFF"));
        } else {
            binding.textView7.setTextColor(Color.parseColor("#993A3A3A"));
            binding.textView8.setTextColor(Color.parseColor("#993A3A3A"));
            binding.textView0.setTextColor(Color.parseColor("#803A3A3A"));
        }
        appBarViewModel = new ViewModelProvider(this).get(AppBarViewModel.class);
        binding.include.setVm(appBarViewModel);
        appBarViewModel.setMainActivityContext(this, binding.include.llError);
        appBarViewModel.getIvServer().observe(this, drawable -> binding.include.ivNetServer.setImageDrawable(getDrawable(drawable)));
        appBarViewModel.getIvNetwork().observe(this, drawable -> binding.include.ivNetState.setImageDrawable(getDrawable(drawable)));
        appBarViewModel.getNoticeLiveData().observe(this, integer -> {
            switch (integer) {
                case 0 ->//询问进入配置
                        new PasswordDialog(mContext, getString(R.string.insert_password), RoomSetting.getSetPassword(), true,
                                v2 -> MyUtil.stopAppControl("正在关闭所有设备", () -> {
                                    //这里额外去掉用户使用的需要的轮询任务
                                    PollingTask.getInstance().stopAllPollingTasks();
                                    startActivity(new Intent(MainActivity.this, SetActivity.class));
                                    finish();
                                }), false).show();
                case 2 ->//SOS
                        new ConfirmDialog(mContext, "提示", "是否请求远程服务？", () -> {
                            appBarViewModel.sos(mContext);
                        }).show();
            }
        });
        //显示天气详细信息
        appBarViewModel.getWeatherLiveData().observe(this, weather -> {
            if (weather.getData() != null) {
                new WeatherDialog(mContext, weather).show();
            }
        });
        binding.setVm(presenter);
        presenter.getWorkListMutableLiveData().observe(this, workList -> {
            workDialog = new WorkDialog(mContext, workList);
            workDialog.show();
        });
        presenter.getNewWorkListMutableLiveData().observe(this, workList -> new WorkNewDialog(mContext).show());
        presenter.getChangeMode().observe(this, mode -> {
            binding.vp2Model.setCurrentItem(mode, false);
            changeModelView(mode);
        });
        presenter.getNoticeLiveData().observe(this, integer -> {
            switch (integer) {
                case 2 ->//锁屏
                        showLockPasswordDialog();
                case 3 ->//进入设置
                        new SetBaseDialog(mContext).show();
                case 4 -> {//结束登记弹窗
                    workDialog = new WorkDialog(mContext, null);
                    workDialog.show();
                }
                case 5 ->//显示详细信息
                        startActivity(new Intent(mContext, InfoActivity.class));
                case 7 ->//切换为手动模式
                        new ConfirmDialog(mContext, getString(R.string.warning), getString(R.string.ask_turn_manual),
                                () -> presenter.initMode(0, MainActivityPresenter.MODE_SOURCE_LOCAL)).show();
                case 8 ->//切换为自动模式
                        new ConfirmDialog(mContext, getString(R.string.warning), getString(R.string.ask_turn_auto),
                                () -> presenter.initMode(1, MainActivityPresenter.MODE_SOURCE_LOCAL)).show();
                case 9 ->//切换为智能模式
                        new ConfirmDialog(mContext, getString(R.string.warning), getString(R.string.ask_turn_intelligence), () -> {
                            if (!SilkwormDBManager.isStarting()) {
                                new ConfirmDialog(mContext, getString(R.string.error), "当前未在" + (RoomSetting.getType() == 4 ? "催青" : "共育") + "，无法进入智能模式", null).show();
                            } else {
                                presenter.initMode(2, MainActivityPresenter.MODE_SOURCE_LOCAL);
                            }
                        }).show();
                case 10 ->//刷新共育状态
                        refreshCultivateState(true);
                case 11 ->//刷新共育状态
                        refreshCultivateState(false);
            }
        });
        //模式切换
        binding.vp2Model.setAdapter(new ModelsAdapter(this));
        binding.vp2Model.setOffscreenPageLimit(2);
        binding.vp2Model.setUserInputEnabled(false);
        refreshCultivateState(false);
        refreshLock();
        // 下载启动最新版本FRP
        FrpUpdateUtil.check(mContext, false);
    }

    /**
     * 刷新共育状态
     *
     * @param needSwitchMode 是否需要刷新状态时匹配状态的模式
     */
    private void refreshCultivateState(boolean needSwitchMode) {
        if (workDialog != null) {
            workDialog.dismiss();
        }
        RxJavaUtils.executeAsyncTask(new RxAsyncTask<Object, CulInfo>(null) {
            @Override
            public CulInfo doInIOThread(Object o) {
                boolean isStarting = SilkwormDBManager.isStarting();
                if (isStarting) {
                    SilkwormNew silkworm = SilkwormDBManager.getLatestSilkworm();
                    int now = DateUtils.daysFromTodayInclusive(silkworm.getStartDate());
                    int process = now * 100 / AIModelSet.getAiControlProgramTotalDays();
                    return new CulInfo(isStarting,
                            "第" + SilkwormDBManager.getStartToNowDays() + "天",
                            silkworm.getVariety(),
                            silkworm.getNumber() + "张",
                            silkworm.getName(),
                            process);
                } else {
                    String none = "未在" + (RoomSetting.getType() == 4 ? "催青" : "共育");
                    return new CulInfo(false, none, none, none, none, 0);
                }
            }

            @Override
            public void doInUIThread(CulInfo culInfo) {
                if (needSwitchMode) {
                    presenter.initMode(culInfo.isStarting ? 1 : 0, MainActivityPresenter.MODE_SOURCE_WORKFLOW);
                }
                fillDataInText(binding.tvAge, culInfo.age);
                fillDataInText(binding.tvVariety, culInfo.variety);
                fillDataInText(binding.tvQuentity, culInfo.quantity);
                fillDataInText(binding.tvSeason, culInfo.season);
                if (RoomSetting.getType() == 4) {
                    fillDataInText(binding.tvCulNumber, "催青数量:");
                    fillDataInText(binding.tvCulBatch, "催青批次:");
                    fillDataInText(binding.tvCulProcess, "催青进度:");
                    fillDataInText(binding.tvCulKinds, "催青品种:");
                    fillDataInText(binding.textView8, "打造智慧催青室，服务蚕农朋友！");
                } else {
                    fillDataInText(binding.tvCulNumber, "共育数量:");
                    fillDataInText(binding.tvCulBatch, "共育批次:");
                    fillDataInText(binding.tvCulProcess, "共育进度:");
                    fillDataInText(binding.tvCulKinds, "共育品种:");
                }
                binding.lpProcess.setProgressCompat(culInfo.process, true);
            }
        });
    }

    /**
     * 共育窗口数据类
     */
    private class CulInfo {
        boolean isStarting;
        String age;
        String variety;
        String quantity;
        String season;
        int process;

        public CulInfo(boolean isStarting, String age, String variety, String quantity, String season, int process) {
            this.isStarting = isStarting;
            this.age = age;
            this.variety = variety;
            this.quantity = quantity;
            this.season = season;
            this.process = process;
        }
    }

    @Override
    public void initListener() {
        binding.vp2Model.setCurrentItem(RoomSetting.getMode(), false);
        changeModelView(RoomSetting.getMode());
        binding.cardKey.setOnClickListener(v -> lock());
        binding.mainEnable.setOnTouchListener((v, event) -> true);
        binding.textView0.setOnClickListener(v -> {
            // todo 消息系统开发完成后打开
//            new MessageDialog(mContext).show();
        });
        binding.tempCard.setOnClickListener(v -> new THBiasDialog(mContext, true).show());
        binding.humidityCard.setOnClickListener(v -> new THBiasDialog(mContext, false).show());
    }

    /**
     * 模式切换的UI效果转换
     *
     * @param target 要转换为的目标模式-手自智
     */
    private void changeModelView(int target) {
        binding.btnManual.setBackgroundColor(Color.parseColor(RoomSetting.isDarkTheme() ? "#33969696" : "#FFFFFF"));
        binding.btnAuto.setBackgroundColor(Color.parseColor(RoomSetting.isDarkTheme() ? "#33969696" : "#FFFFFF"));
        binding.btnIntelligence.setBackgroundColor(Color.parseColor(RoomSetting.isDarkTheme() ? "#33969696" : "#FFFFFF"));
        binding.tvManual.setTextColor(Color.parseColor(RoomSetting.isDarkTheme() ? "#FFFFFF" : "#414141"));
        binding.tvAuto.setTextColor(Color.parseColor(RoomSetting.isDarkTheme() ? "#FFFFFF" : "#414141"));
        binding.tvIntelligence.setTextColor(Color.parseColor(RoomSetting.isDarkTheme() ? "#FFFFFF" : "#414141"));
        binding.ivManual.setImageDrawable(getDrawable(R.mipmap.mode_manual_close));
        binding.ivAuto.setImageDrawable(getDrawable(R.mipmap.mode_auto_close));
        binding.ivIntelligence.setImageDrawable(getDrawable(R.mipmap.mode_intelligence_close));
        if (target == 0) {
            //手动模式
            binding.btnManual.setBackgroundColor(Color.parseColor("#00A1FF"));
            binding.ivManual.setImageDrawable(getDrawable(R.mipmap.mode_manual_open));
            binding.tvManual.setTextColor(Color.parseColor("#FFFFFF"));
        } else if (target == 1) {
            //自动模式
            binding.btnAuto.setBackgroundColor(Color.parseColor("#00A1FF"));
            binding.ivAuto.setImageDrawable(getDrawable(R.mipmap.mode_auto_open));
            binding.tvAuto.setTextColor(Color.parseColor("#FFFFFF"));
        } else {
            //智能模式
            binding.btnIntelligence.setBackgroundColor(Color.parseColor("#00A1FF"));
            binding.ivIntelligence.setImageDrawable(getDrawable(R.mipmap.mode_intelligence_open));
            binding.tvIntelligence.setTextColor(Color.parseColor("#FFFFFF"));
        }
    }

    /**
     * 刷新锁屏时间
     */
    private void refreshLock() {
        stopLockTimer();
        if (!mainPageResumed || showingDialogCount > 0 || binding.mainLock.getVisibility() == View.VISIBLE) {
            return;
        }
        lockHandler.postDelayed(lockRunnable, RoomSetting.getMainActivityOperateLockTimeOut() * 1000L);
    }

    private void lock() {
        if (!mainPageResumed || showingDialogCount > 0 || binding.mainLock.getVisibility() == View.VISIBLE) {
            return;
        }
        MyLog.app("屏幕已锁");
        stopLockTimer();
        binding.mainLock.setVisibility(View.VISIBLE);
        binding.mainKey.setImageDrawable(getDrawable(R.mipmap.lock));
    }

    private void showLockPasswordDialog() {
        if (lockPasswordDialog != null && lockPasswordDialog.isShowing()) {
            return;
        }
        lockPasswordDialog = new PasswordDialog(mContext, "请输入锁屏密码", RoomSetting.getMainActivityLock(), v1 -> {
            binding.mainLock.setVisibility(View.GONE);
            binding.mainKey.setImageDrawable(getDrawable(R.mipmap.unlock));
            refreshLock();
        });
        lockPasswordDialog.setOnDismissListener(dialogInterface -> lockPasswordDialog = null);
        lockPasswordDialog.show();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN
                && binding.mainLock.getVisibility() != View.VISIBLE) {
            refreshLock();
        }
        return super.dispatchTouchEvent(event);
    }

    public void onDialogShown() {
        showingDialogCount++;
        stopLockTimer();
    }

    public void onDialogDismissed() {
        showingDialogCount = Math.max(0, showingDialogCount - 1);
        if (showingDialogCount == 0) {
            refreshLock();
        }
    }

    private void stopLockTimer() {
        lockHandler.removeCallbacks(lockRunnable);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mainPageResumed = true;
        refreshLock();
    }

    @Override
    protected void onPause() {
        mainPageResumed = false;
        stopLockTimer();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        stopLockTimer();
        lockHandler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (System.currentTimeMillis() - mExitTime < 2000) {
            finish();
            System.exit(0);
        } else {
            mExitTime = System.currentTimeMillis();
            Toasty.info(mContext, "再按一次返回键退出程序").show();
        }
    }

}
