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.common.bean.OrderBean;
import com.gingersoft.gsa.cloud.base.common.bean.OrderDetail;
import com.gingersoft.gsa.cloud.base.common.bean.TableBean;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.MyOrderManage;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.OpenTableManage;
import com.gingersoft.gsa.cloud.database.bean.Function;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.app.GoldConstants;
import com.gingersoft.gsa.cloud.table.app.TableOperatTypeConstant;
import com.gingersoft.gsa.cloud.table.mvp.contract.TableContract;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.BaseRespose;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.TableDetail;
import com.gingersoft.gsa.cloud.table.mvp.model.utils.OrderAssemblyUtil;
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.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

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

import javax.inject.Inject;

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;


/**
 * ================================================
 * 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 = new ArrayList<>();

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

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

    /**
     * 当前选择的操作：
     * 1、分台
     * 2、上菜纸
     * 3、重置
     * 4、转台
     * 5、sky_order
     * 6、結賬、
     * 10：餐檯模式
     */
    private int currentChooseOperatType = -1;
    /**
     * 选中操作的台名、id
     */
    private String originalTableName = "";
    private int originalTableId;
    /**
     * 转台需要转到台名、id
     */
    private String targetTableName = "";
    private int targetTableId;


    @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("重置檯號")) {
                    mRootView.setCurrentOperatType(TableOperatTypeConstant.init_table_3);
                    return;
                }
                if (mBottomFunctionList.get(position).getResName().equals("轉檯")) {
                    mRootView.setCurrentOperatType(TableOperatTypeConstant.move_table_4);
                    return;
                }
                if (mBottomFunctionList.get(position).getResName().equals("上菜紙")) {
                    CC.obtainBuilder("Component.Print")
                            .setActionName("printActivity")
                            .addParam("type", 0)
                            .build()
                            .callAsync((cc, result) -> {
                                Log.e("error", "是否成功打印：" + result.isSuccess());
                                if (result.isSuccess()) {
                                    //打印成功
                                }
                            });
                    return;
                }
//                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, "重置檯號", "", String.valueOf(R.mipmap.table_init)));
        mBottomFunctionList.add(new Function((long) 2, 1, 2025, "轉檯", "", String.valueOf(R.mipmap.table_move)));
//        mBottomFunctionList.add(new Function((long) 3, 1, 2025, "分檯", "", ""));
//        mBottomFunctionList.add(new Function((long) 4, 1, 2025, "↑", "", ""));
    }

    public void getTables(boolean show) {
        int restaurantId = GsaCloudApplication.getRestaurantId(mApplication);
        mModel.getTables(restaurantId)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                    if (show)
                        mRootView.showLoading(null);
                })
                .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()) {
                            List<TableBean.DataBean> tableBeanData = tableBean.getData();
                            if (tableBeanData != null) {
                                if (mTableList.size() > 0) {
                                    mTableList.clear();
                                }
                                mTableList.addAll(tableBeanData);
                                mRootView.returnTableList(tableBeanData);
                            }
                        } else {
                            if (show)
                                mRootView.showMessage(tableBean.getErrMsg());
                        }
                    }
                });
    }

    public void openTable(int tableId) {
        RequestBody requestBody = new FormBody.Builder()
                .add("id", String.valueOf(tableId))
                .build();
        mModel.openTable(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .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()) {
                            //設置當前開台數據
                            TableBean.DataBean openTableBean = getTableById(tableId);
                            OpenTableManage.getDefault().setTableBean(openTableBean);

                            OrderBean orderBean = respose.getData();
                            if (orderBean != null && respose.getData().getOrderDetails() != null) {

                                OpenTableManage.getDefault().setPeopleNumber(orderBean.getPerson());

                                List<OrderBean.OrderDetailsBean> orderDetailsBeans = respose.getData().getOrderDetails();
                                //緩存訂單信息
                                MyOrderManage.getInstance().setOrderBean(new OrderBean(orderBean));
                                //緩存食品信息
                                List<OrderDetail> orderDetailList = OrderAssemblyUtil.assemblyOrder(OrderDetail.orderTransOrderDetails(orderDetailsBeans));

                                MyOrderManage.getInstance().setOrderFoodList(orderDetailList);
                            } else {
                                MyOrderManage.getInstance().setOrderBean(null);
                                MyOrderManage.getInstance().setOrderFoodList(new ArrayList<>());
                            }

                            mRootView.startMealStandActivity();
                        } else {
                            mRootView.showMessage(respose.getErrMsg());
                        }
                    }
                });
    }

    public void getTable(int tableId) {
        mModel.getTable(tableId)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<TableDetail>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull TableDetail result) {
                        if (result.isSuccess()) {
                            TableBean.DataBean tableBean = result.getData();
                            if (originalTableId == 0) {
                                if (tableBean.getUseStatus() == 1) {
                                    mRootView.showMessage("此檯使用中.");
                                    return;
                                }
                                if (tableBean.getStatus() == 0) {
                                    mRootView.showMessage("此檯未開檯.");
                                    return;
                                }
                                originalTableName = tableBean.getTableName();
                                originalTableId = tableBean.getId();
                                mRootView.setOperatContentText("由: " + originalTableName + " 轉到 ");
                            } else {
                                if (tableBean.getUseStatus() == 1) {
                                    mRootView.showMessage("此檯使用中.");
                                    return;
                                }
                                if (tableBean.getStatus() == 2 || tableBean.getStatus() == 3) {
                                    mRootView.showMessage(tableBean.getTableName() + "檯已開檯不可轉檯");
                                    return;
                                }
                                targetTableName = tableBean.getTableName();
                                targetTableId = tableBean.getId();
                                mRootView.setOperatContentText("由: " + originalTableName + " 轉到 " + targetTableName + " 號檯");
                                showOperatTipDialog(tableBean);
                            }
                        } else {
                            mRootView.showMessage(result.getErrMsg());
                        }
                    }
                });
    }

    public void turnTable(int originalTableId, int targetTableId) {

        RequestBody requestBody = new FormBody.Builder()
                .add("id", String.valueOf(originalTableId))
                .add("tableId", String.valueOf(targetTableId))
                .build();

        mModel.turnTable(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .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()) {
                            mRootView.showMessage("轉檯成功");
                            mRootView.canceOperat();
                            //立即獲取餐檯數據
                            getTables(false);
                        } else {
                            mRootView.showMessage(respose.getErrMsg());
                        }
                    }
                });
    }

    public void initTable(int tableId, boolean showMessage) {

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

        mModel.initTable(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                    if (showMessage) {
                        mRootView.showLoading(null);
                    }
                })
                .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()) {

//                            if (showMessage)
//                                mRootView.showMessage("重置成功!");

                            mRootView.canceOperat();

                            getTables(false);

                        } else {
                            if (showMessage)
                                mRootView.showMessage(respose.getErrMsg());
                        }
                    }

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

    /**
     * 根据操作类型过滤一遍餐台
     */
    public void filterTableByOperatType(int status) {
        if (mTableList.size() == 0) {
            return;
        }
        List<TableBean.DataBean> filterTableBeanList = new ArrayList<>();
        //如果是餐檯操作過一遍筛选
        switch (currentChooseOperatType) {
//            case TableOperatTypeConstant.splite_table_1:
//                for (int i = 0; i < datasBeans.size(); i++) {
//                    if (datasBeans.get(i).getStatus() != 0 || datasBeans.get(i).getSplitStatus() == 1 ? true : false) {
//                        mTableList.add(datasBeans.get(i));
//                    }
//                }
//                break;
//            case TableOperatTypeConstant.print_parper_2:
//                for (int i = 0; i < datasBeans.size(); i++) {
//                    if (!datasBeans.get(i).isUsing() && datasBeans.get(i).getOrderid() > 0 && (datasBeans.get(i).getStatus() != 0 || datasBeans.get(i).getSplitStatus() == 1)) {
//                        mTableList.add(datasBeans.get(i));
//                    }
//                }
//                break;
            case TableOperatTypeConstant.init_table_3:
                for (int i = 0; i < mTableList.size(); i++) {
                    if (mTableList.get(i).getUseStatus() == 1) {
                        filterTableBeanList.add(mTableList.get(i));
                    }
                }
                break;
//            case TableOperatTypeConstant.skyorder_mode_5:
//                for (int i = 0; i < datasBeans.size(); i++) {
//                    mTableList.add(datasBeans.get(i));
//                }
//                break;
            case TableOperatTypeConstant.move_table_4:
            case -1: //正常餐檯模式下顯示所有餐檯數據
                filterTableBeanList.addAll(mTableList);
                break;
        }
        IActivity.nofilyFragmentUpdateTableData(filterTableBeanList, status);
    }

    public void showOperatTipDialog(TableBean.DataBean dataBean) {
        QMUIDialog.MessageDialogBuilder dialogBuilder = new QMUIDialog.MessageDialogBuilder(IActivity);
        dialogBuilder.setTitle("溫馨提示");
        switch (currentChooseOperatType) {
            case TableOperatTypeConstant.splite_table_1:

                break;
            case TableOperatTypeConstant.print_parper_2:

                break;
            case TableOperatTypeConstant.init_table_3:
                dialogBuilder.setMessage("是否確認重置" + dataBean.getTableName() + "號檯?");
                break;
            case TableOperatTypeConstant.move_table_4:
                String message = "是否由%s號檯轉到%s號檯";
                dialogBuilder.setMessage(String.format(message, originalTableName, targetTableName));
                break;
            case TableOperatTypeConstant.skyorder_mode_5:

                break;
        }
        dialogBuilder.addAction("取消", new QMUIDialogAction.ActionListener() {
            @Override
            public void onClick(QMUIDialog dialog, int index) {
                dialog.dismiss();
            }
        });
        dialogBuilder.addAction(0, "確認", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
            @Override
            public void onClick(QMUIDialog dialog, int index) {
                dialog.dismiss();
                switch (currentChooseOperatType) {
                    case TableOperatTypeConstant.splite_table_1:

                        break;
                    case TableOperatTypeConstant.print_parper_2:

                        break;
                    case TableOperatTypeConstant.init_table_3:
                        initTable(dataBean.getId(), true);
                        break;
                    case TableOperatTypeConstant.move_table_4:
                        turnTable(originalTableId, targetTableId);
                        break;
                    case TableOperatTypeConstant.skyorder_mode_5:

                        break;
                }
            }
        });
        dialogBuilder.create(R.style.MyDialogTheme2).show();
    }

    /**
     * 初始化操作參數
     */
    public void initTableParameter() {
        originalTableName = "";
        originalTableId = 0;
        targetTableName = "";
        targetTableId = 0;
    }

    private TableBean.DataBean getTableById(int id) {
        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);
        }
        TableActivity.isRefreshData = true;
        tableTimer.start();
    }

    public void startTableTimer() {
        if (tableTimer != null) {
            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);
            }
            this.start();
        }

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

    public Disposable getGetTablesDataDisposable() {
        return mGetTablesDataDisposable;
    }

    public int getCurrentChooseOperatType() {
        return currentChooseOperatType;
    }

    public void setCurrentChooseOperatType(int currentChooseOperatType) {
        this.currentChooseOperatType = currentChooseOperatType;
    }

    public String getOriginalTableName() {
        return originalTableName;
    }

    public void setOriginalTableName(String originalTableName) {
        this.originalTableName = originalTableName;
    }

    public int getOriginalTableId() {
        return originalTableId;
    }

    public void setOriginalTableId(int originalTableId) {
        this.originalTableId = originalTableId;
    }

    public String getTargetTableName() {
        return targetTableName;
    }

    public void setTargetTableName(String targetTableName) {
        this.targetTableName = targetTableName;
    }

    public int getTargetTableId() {
        return targetTableId;
    }

    public void setTargetTableId(int targetTableId) {
        this.targetTableId = targetTableId;
    }
}
