package com.gingersoft.gsa.cloud.manager.mvp.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.InputQueue;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.gingersoft.gsa.cloud.common.core.table.TableArea;
import com.gingersoft.gsa.cloud.common.core.table.TableManagerItem;
import com.gingersoft.gsa.cloud.manager.R;
import com.gingersoft.gsa.cloud.manager.di.component.DaggerTableManageComponent;
import com.gingersoft.gsa.cloud.manager.mvp.contract.TableManageContract;
import com.gingersoft.gsa.cloud.manager.mvp.model.bean.request.AreaRequest;
import com.gingersoft.gsa.cloud.manager.mvp.model.bean.request.TableRequest;
import com.gingersoft.gsa.cloud.manager.mvp.presenter.TableManagePresenter;
import com.gingersoft.gsa.cloud.manager.mvp.ui.fragment.AddTableFragment;
import com.gingersoft.gsa.cloud.manager.mvp.ui.fragment.AreaListFragment;
import com.gingersoft.gsa.cloud.manager.mvp.ui.fragment.TableListFragment;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.jess.arms.base.BaseFragmentActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

import me.yokeyword.fragmentation.ISupportFragment;
import me.yokeyword.fragmentation.anim.DefaultHorizontalAnimator;
import me.yokeyword.fragmentation.anim.FragmentAnimator;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 05/13/2020 14:47
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class TableManageActivity extends BaseFragmentActivity<TableManagePresenter> implements TableManageContract.View {

    /**
     * 輪訓刷新餐檯數據
     */
    public static boolean isRefreshData = true;

    public static final int ADD_TABLE_RESULT_SUCCESS = 100;
    public static final int ADD_AREA_RESULT_SUCCESS = 200;

    public static final int ADD_AREA_SUCCESS = 10;
    public static final int DELETE_AREA_SUCCESS = 11;
    public static final int UPDATE_AREA_SUCCESS = 12;
    public static final int QUERY_AREA_SUCCESS = 13;

    public static final byte ADD_TABLE_SUCCESS = 20;
    public static final byte DELETE_TABLE_SUCCESS = 21;
    public static final byte UPDATE_TABLE_SUCCESS = 22;
    public static final byte QUERY_TABLE_SUCCESS = 23;


    public static final byte CHANGE_AREA_SORT = 30;
    public static final byte CHANGE_TABLE_SORT = 31;
    public static final byte UPDATE_TABLE_SERVICE_CHARGE = 32;


    private List<TableArea> mTableAreaList = new ArrayList<>();
    private List<TableManagerItem> mTableList = new ArrayList<>();

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerTableManageComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return 0; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        if (findFragment(TableListFragment.class) == null) {
            loadRootFragment(Window.ID_ANDROID_CONTENT, TableListFragment.newInstance());
        }
//        generateSystemAlert();
    }

    private void generateSystemAlert() {
        //Activity Context
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        //Application Context
        //WindowManager wm = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        final WindowManager.LayoutParams params = new WindowManager.LayoutParams();
        params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.height = 500;
        params.gravity = Gravity.CENTER;
        final View view = LayoutInflater.from(this).inflate(R.layout.window_system_alert, null);
        wm.addView(view, params);
    }

    public void initGetTableTimer() {
        mPresenter.initGetTableTimer();
    }

    @Override
    public void onBackPressedSupport() {
        // 对于 4个类别的主Fragment内的回退back逻辑,已经在其onBackPressedSupport里各自处理了
        super.onBackPressedSupport();
    }

    @Override
    public FragmentAnimator onCreateFragmentAnimator() {
        // 设置横向(和安卓4.x动画相同)
        return new DefaultHorizontalAnimator();
    }

    public void addArea(AreaRequest.Add request) {
        mPresenter.addArea(request);
    }

    public void deleteArea(String ids) {
        mPresenter.deleteArea(ids);
    }

    public void updateArea(AreaRequest.Update request) {
        mPresenter.updateArea(request);
    }

    public void queryAreas(RefreshLayout refreshLayout) {
        mPresenter.queryAreas(refreshLayout, true);
    }

    public void addTable(TableRequest.Add request) {
        mPresenter.addTable(request);
    }

    public void deleteTable(String ids) {
        mPresenter.deleteTable(ids);
    }

    public void updateTable(TableRequest.Update request) {
        mPresenter.updateTable(request);
    }

    public void queryTables(RefreshLayout refreshLayout) {
        mPresenter.queryTables(refreshLayout, true);
    }

    public void changeAreaSort(String ids) {
        mPresenter.changeAreaSort(ids);
    }

    public void changeTableSort(String ids) {
        mPresenter.changeTableSort(ids);
    }

    public void updateTableServiceCharge(List<TableRequest.UpdateServiceCharge> request) {
        mPresenter.updateTableServiceCharge(request);
    }

    @Override
    public void initIntent() {
    }

    @Override
    public void initTopBar() {
    }

    @Override
    public void initLanguage() {

    }

    @Override
    public void initLayoutParams() {

    }

    @Override
    public void initLayoutVisible() {

    }

    @Override
    public void showLoading(String message) {
        if (message != null)
            LoadingDialog.showDialogForLoading(this, message, true);
        else
            LoadingDialog.showDialogForLoading(this);
    }

    @Override
    public void hideLoading() {
        LoadingDialog.cancelDialogForLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void queryAreasSuccess(List<TableArea> areas, int type) {
        if (mTableAreaList.size() > 0) {
            mTableAreaList.clear();
        }
        mTableAreaList.addAll(areas);

        ISupportFragment fragment = getTopFragment();
        if (fragment != null) {
            if (fragment instanceof AreaListFragment) {
                AreaListFragment areaListFragment = (AreaListFragment) fragment;
                if (type == DELETE_AREA_SUCCESS) {
                    areaListFragment.deleteSuccess();
                }
                if (!areaListFragment.isRadioEdit()) {
                    areaListFragment.updateAreaData(areas);
                }
            } else if (fragment instanceof TableListFragment) {
                TableListFragment tableListFragment = (TableListFragment) fragment;
                tableListFragment.setAreaData(areas);
            }
            switch (type) {
                case ADD_AREA_SUCCESS:
                    if (fragment instanceof AreaListFragment) {
                        AreaListFragment areaListFragment = (AreaListFragment) fragment;
                        areaListFragment.addSuccess();
                    }
                    break;
                case UPDATE_AREA_SUCCESS:
                    TableListFragment tableListFragment = findFragment(TableListFragment.class);
                    if (tableListFragment != null) {
                        tableListFragment.updateTableData(mTableAreaList, mTableList);
                    }
                    break;
                case DELETE_AREA_SUCCESS:
                    break;
                case QUERY_AREA_SUCCESS:

                    break;
                case CHANGE_AREA_SORT:

                    break;
            }
        }
    }

    @Override
    public void queryTablesSuccess(List<TableManagerItem> tables, int type) {
        if (mTableList.size() > 0) {
            mTableList.clear();
        }
        this.mTableList.addAll(tables);

        ISupportFragment fragment = getTopFragment();
        if (fragment != null) {
            if (fragment instanceof TableListFragment) {
                TableListFragment tableListFragment = (TableListFragment) fragment;
                tableListFragment.updateTableData(mTableAreaList, tables);
            }
            TableListFragment tableListFragment = findFragment(TableListFragment.class);
            switch (type) {
                case ADD_TABLE_SUCCESS:
                case UPDATE_TABLE_SUCCESS:
                    AddTableFragment addTableFragment = (AddTableFragment) fragment;
                    addTableFragment.pop();
                    if (tableListFragment != null) {
                        tableListFragment.updateTableData(mTableAreaList, tables);
                    }
                    break;
                case DELETE_TABLE_SUCCESS:
                case UPDATE_TABLE_SERVICE_CHARGE:
                    if (fragment instanceof TableListFragment) {
                        tableListFragment.backEdit();
                    }
                    break;
                case CHANGE_TABLE_SORT:

                    break;
                case QUERY_TABLE_SUCCESS:

                    break;
            }
        }
    }

    @Override
    public void showEmptyView(boolean isSuccess, int size, Throwable t) {
        ISupportFragment fragment = getTopFragment();
        size = mTableList.size() != 0 ? mTableList.size() : mTableAreaList.size();
        if (fragment instanceof TableListFragment) {
            TableListFragment tableListFragment = (TableListFragment) fragment;
            tableListFragment.showEmptyView(isSuccess, size, t);
        } else if (fragment instanceof AreaListFragment) {
            AreaListFragment areaListFragment = (AreaListFragment) fragment;
            areaListFragment.showEmptyView(isSuccess, size, t);
        }
    }

    @Override
    public void onStartRefreshTableData() {
        isRefreshData = true;
        mPresenter.startTableTimer();
        mPresenter.queryTables(null, false);
    }

    @Override
    public void onPauseRefreshTableData() {
        isRefreshData = false;
        mPresenter.cancelTableTimer();
        //立刻停止獲取餐檯接口
        if (mPresenter.getGetTablesDataDisposable() != null && !mPresenter.getGetTablesDataDisposable().isDisposed()) {
            mPresenter.getGetTablesDataDisposable().dispose();
        }
    }


    public List<TableArea> getTableAreaList() {
        return mTableAreaList;
    }

    public List<TableManagerItem> getTableList() {
        return mTableList;
    }

    public boolean isRadioEdit() {
        TableListFragment tableListFragment = findFragment(TableListFragment.class);
        if (tableListFragment != null) {
            return tableListFragment.isRadioEdit();
        } else {
            return false;
        }
    }
}
