package com.gingersoft.gsa.cloud.table.mvp.presenter;

import android.app.Application;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;

import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.bean.BaseRespose;
import com.gingersoft.gsa.cloud.database.bean.Function;
import com.gingersoft.gsa.cloud.table.app.GoldConstants;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.TableBean;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.TableActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.BottomFunctionAdapter;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import okhttp3.FormBody;
import okhttp3.RequestBody;

import javax.inject.Inject;

import com.gingersoft.gsa.cloud.table.mvp.contract.TableContract;
import com.jess.arms.utils.RxLifecycleUtils;

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


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 12/27/2019 19:19
 * <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>
 * ================================================
 */
@ActivityScope
public class TablePresenter extends BasePresenter<TableContract.Model, TableContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private TableActivity IActivity;

    private List<TableBean.DataBean> mTableList;

    private BottomFunctionAdapter mBottomFunctionAdapter;
    private List<Function> mBottomFunctionList = new ArrayList<>();

    private TableBean.DataBean mOpenTableBean;

    //定时获取餐台 定时器
    private GetTableTimer tableTimer;
    private Disposable mGetTablesDataDisposable;


    @Inject
    public TablePresenter(TableContract.Model model, TableContract.View rootView) {
        super(model, rootView);
        this.IActivity = (TableActivity) rootView;

        initGetTableTimer();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;

        cancelTableTimer();
    }

    public void initBottomFunction() {
        initBottomFunctionItem();
        if (mBottomFunctionAdapter == null) {
            mBottomFunctionAdapter = new BottomFunctionAdapter(IActivity, mBottomFunctionList);
            mRootView.setBottomFunctionAdapter(mBottomFunctionAdapter);
        }
        initBottomFunctionListener();
    }

    private void initBottomFunctionListener() {
        mBottomFunctionAdapter.setOnItemClickListener(new DefaultAdapter.OnRecyclerViewItemClickListener() {

            @Override
            public void onItemClick(View view, int viewType, Object data, int position) {
                if (mBottomFunctionList.get(position).getResName().equals("↑")) {
                    mBottomFunctionList.add(new Function((long) 5, 1, 2025, "skyorder", "", ""));
                    mBottomFunctionList.add(new Function((long) 6, 1, 2025, "上菜紙", "", ""));
                    for (int i = 0; i < mBottomFunctionList.size(); i++) {
                        boolean isMore = mBottomFunctionList.get(i).getResName().equals("↑");
                        if (isMore)
                            mBottomFunctionList.get(i).setResName("↓");
                    }
                    mBottomFunctionAdapter.notifyDataSetChanged();
                } else if (mBottomFunctionList.get(position).getResName().equals("↓")) {
                    mBottomFunctionList.remove(mBottomFunctionList.size() - 1);
                    mBottomFunctionList.remove(mBottomFunctionList.size() - 1);
                    for (int i = 0; i < mBottomFunctionList.size(); i++) {
                        boolean isMore = mBottomFunctionList.get(i).getResName().equals("↓");
                        if (isMore)
                            mBottomFunctionList.get(i).setResName("↑");
                    }
                    mBottomFunctionAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    public void initBottomFunctionItem() {
        mBottomFunctionList.add(new Function((long) 1, 1, 2025, "重置檯號", "", ""));
        mBottomFunctionList.add(new Function((long) 2, 1, 2025, "轉檯", "", ""));
        mBottomFunctionList.add(new Function((long) 3, 1, 2025, "分檯", "", ""));
        mBottomFunctionList.add(new Function((long) 4, 1, 2025, "↑", "", ""));
    }

    public void getTables(boolean show, int restaurantId) {

        restaurantId = GsaCloudApplication.getRestaurantId(mApplication);

        mModel.getTables(26)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                    if (show)
                        mRootView.showLoading("");
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<TableBean>(mErrorHandler) {

                    @Override
                    public void onSubscribe(Disposable d) {
                        super.onSubscribe(d);
                        mGetTablesDataDisposable = d;
                    }

                    @Override
                    public void onNext(@NonNull TableBean tableBean) {
                        if (tableBean.isSuccess()) {
                            mTableList = tableBean.getData();
                            mRootView.returnTableList(tableBean.getData());
                        } else {
                            if (show)
                                mRootView.showMessage(tableBean.getErrMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                    }
                });
    }

    public void openTable(int id) {

        RequestBody requestBody = new FormBody.Builder()
                .add("id", id + "")
                .build();

        mModel.openTable(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(""))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseRespose>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseRespose respose) {

                        if (respose.isSuccess()) {

                            getTables(false, GoldConstants.restaurantId);

                            //設置當前開台數據
                            mOpenTableBean = getTableById(id);

                            CC.obtainBuilder("Component.Meal")
                                    .setActionName("showMealStandActivity")
                                    .addParam("openTableBean", mOpenTableBean)
                                    .build()
                                    .call();
                        } else {
                            mRootView.showMessage(respose.getErrMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                    }
                });
    }

    public void initTable(int tableId) {

        RequestBody requestBody = new FormBody.Builder()
                .add("id", tableId + "")
                .build();

        mModel.initTable(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(""))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<Object>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull Object tableBean) {
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                    }
                });
    }


    private TableBean.DataBean getTableById(int id) {
        if (mTableList != null) {
            for (int i = 0; i < mTableList.size(); i++) {
                TableBean.DataBean dataBean = mTableList.get(i);
                if (dataBean.getId() == id)
                    return dataBean;
            }
        }
        return null;
    }


    public void initGetTableTimer() {
        if (tableTimer == null) {
            tableTimer = new GetTableTimer(GoldConstants.refreshTime * 1000, GoldConstants.refreshTime * 1000);
        }
        tableTimer.start();
    }

    public void cancelTableTimer() {
        if (tableTimer != null) {
            tableTimer.cancel();
        }
    }

    /**
     * 计时器类 定時更新餐台数据
     */
    private class GetTableTimer extends CountDownTimer {

        public GetTableTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            if (TableActivity.isRefreshData) {
                getTables(false, GoldConstants.restaurantId);
            }
            this.start();
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
        }
    }


    public Disposable getGetTablesDataDisposable() {
        return mGetTablesDataDisposable;
    }
}
