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

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.app.GsaCloudApplication;
import com.gingersoft.gsa.cloud.common.constans.FoodSummaryConstans;
import com.gingersoft.gsa.cloud.common.constans.MealConstant;
import com.gingersoft.gsa.cloud.common.core.member.MemberInfo;
import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager;
import com.gingersoft.gsa.cloud.common.core.table.TableBean;
import com.gingersoft.gsa.cloud.common.scan.ScanHelper;
import com.gingersoft.gsa.cloud.common.utils.LanguageUtils;
import com.gingersoft.gsa.cloud.common.utils.VibratorUtils;
import com.gingersoft.gsa.cloud.component.ComponentName;
import com.gingersoft.gsa.cloud.database.bean.Food;
import com.gingersoft.gsa.cloud.order.commodity.OrderDetail;
import com.gingersoft.gsa.cloud.order.order.BaseOrder;
import com.gingersoft.gsa.cloud.order.order.DoshokuOrder;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.R2;
import com.gingersoft.gsa.cloud.table.di.component.DaggerMealStand2Component;
import com.gingersoft.gsa.cloud.table.mvp.contract.MealStandContract;
import com.gingersoft.gsa.cloud.table.mvp.contract.MealStandContract2;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.event.InitTableEvent;
import com.gingersoft.gsa.cloud.table.mvp.presenter.mealstand.MealStandPresenter2;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.mealstand.SetMealFragment;
import com.gingersoft.gsa.cloud.table.mvp.ui.widget.CustomFoodDialog;
import com.gingersoft.gsa.cloud.ui.recylcler.Indicator.PagerGridLayoutManager;
import com.gingersoft.gsa.cloud.ui.view.SearchKeyBoardView;
import com.gingersoft.gsa.cloud.ui.widget.dialog.CommonTipDialog;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.gyf.immersionbar.ImmersionBar;
import com.jess.arms.base.BaseFragmentActivity;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import org.simple.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

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


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 12/27/2019 19:17
 * <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 MealStandActivity2 extends BaseFragmentActivity<MealStandPresenter2> implements MealStandContract2.View, PagerGridLayoutManager.PageListener {

    @BindView(R2.id.ctime)
    Chronometer ctime;
    @BindView(R2.id.fl_food_plate)
    FrameLayout flFoodPlate;
    @BindView(R2.id.tv_no_save_return)
    TextView tvNoSaveReturn;
    @BindView(R2.id.btn_order_count)
    Button btnOrderCount;
    @BindView(R2.id.tv_order_content)
    TextView tvOrderContent;
    @BindView(R2.id.fl_order_content)
    FrameLayout flOrderContent;
    @BindView(R2.id.btn_send_order)
    Button btnSendOrder;
    @BindView(R2.id.fl_send_order)
    FrameLayout flSendOrder;
    @BindView(R2.id.btn_order_printer)
    Button btnOrderPrinter;
    @BindView(R2.id.btn_printer_machine_name)
    Button btnPrinterMachineName;
    @BindView(R2.id.fl_printer_order)
    FrameLayout flPrinterOrder;
    @BindView(R2.id.ll_stand_oper)
    LinearLayout llStandOper;

    private static final int ORDER_CONTENT_CODE = 1002;

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

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        EventBus.getDefault().registerSticky(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void configImmersionBar(ImmersionBar immersionBar) {
        immersionBar
                .fitsSystemWindows(true)
                .statusBarColor(R.color.theme_white_color)
                .statusBarDarkFont(true)
                .init();
    }

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

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        if (findFragment(SetMealFragment.class) == null) {
            loadRootFragment(R.id.fl_food_plate, SetMealFragment.newInstance());
        }
        initAutoQuit();
    }

    @OnClick({R2.id.btn_send_order, R2.id.tv_no_save_return, R2.id.tv_order_content})
    public void onClick(View v) {

        recordOperat(true);

        int id = v.getId();
        if (id == R.id.btn_send_order) {
            if (BaseOrder.isCurrentOrderType(FoodSummaryConstans.TAKEAWAY_TYPE)) {
                CC.obtainBuilder(ComponentName.COMPONENT_DELIVERYPICK)
                        .setActionName("SendOrder")
                        .build()
                        .call();
                return;
            }
            if (sendOrderListener != null) {
                sendOrderListener.sendOrder();
            }
        } else if (id == R.id.tv_order_content) {
            //如果打印成功會回調
            Intent intent = new Intent(mContext, OrderContentActivity.class);
            startActivityForResult(intent, MealStandActivity2.ORDER_CONTENT_CODE);
        } else if (id == R.id.tv_no_save_return) {
            returnTableActivity(true);
        }
    }

    @Override
    public void onBackPressedSupport() {
        returnTableActivity(true);
    }

    public void returnTableActivity(boolean initTable) {
        if (mPresenter.hasNesOrderFoods()) {
            //没有过重复下单提示且有未送单食品，提示用户
            String tip = LanguageUtils.get_language_system(this, "food.not.delivered.tip", "有食品未送單, 確認離開?");
            Class[] parameterTypes = {boolean.class};
            Object[] parameters = {initTable};
            CommonTipDialog.showSurpisedDialog(this, tip, MealStandActivity2.class, this,
                    "returnBeforeActivity", parameterTypes, parameters);
        } else {
            returnBeforeActivity(initTable);
        }
    }

    public void returnBeforeActivity(boolean initTable) {
        if (BaseOrder.isTableToMeal() && initTable && !DoshokuOrder.getInstance().isModifyOrder()) {
            TableBean.DataBean dataBean = DoshokuOrder.getInstance().getOpenTableInfo();
            if (dataBean != null) {
                //通知更新餐台状态
                EventBus.getDefault().post(new InitTableEvent(dataBean.getId(), dataBean.getTableNumber()), "initTable_status_event");
            }
        }
        killMyself();
    }

    /**
     * 一段时间内没有操作，退出当前餐台
     */
    private void initAutoQuit() {
        if (ctime != null) {
            ctime.setBase(SystemClock.elapsedRealtime());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
                ctime.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {

                    @Override
                    public void onChronometerTick(Chronometer chronometer) {
                        // 执行一下看看是否按下了home键的线程
                        // 如果开始计时到现在超过了autoQuitTime秒
                        int autoQuitTime = GsaCloudApplication.functionConfiguration.getAutoQuitTimeVaule();
                        if (SystemClock.elapsedRealtime() - chronometer.getBase() > autoQuitTime * 1000) {
                            // 停止计时
                            chronometer.stop();
                            returnBeforeActivity(true);
                        }
                    }
                });
            }
            //开启倒计时
            ctime.start();
        }
    }

    @Override
    public void recordOperat(boolean isPressButtonSound) {
        if (isPressButtonSound) {
            VibratorUtils.pressButtonSound(this);
        }
        //关闭倒计时
        if (ctime != null) {
            ctime.stop();
        }
        //重新开启倒计时
        if (ctime != null) {
            ctime.setBase(SystemClock.elapsedRealtime());
            ctime.start();
        }
    }

    @Override
    public void setFoodAdapter(DefaultAdapter adapter) {
    }

    @Override
    public void setOrderDetailAdapter(DefaultAdapter adapter) {
    }

    @Override
    public void showStandOperLayoutVisibility(boolean show) {
        if (show) {
            llStandOper.setVisibility(View.INVISIBLE);
        } else {
            llStandOper.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void setOrderFoodCount(String number) {
    }

    @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(MealStandActivity2.this, message);
    }

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

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

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public int getFromType() {
        return 1;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ORDER_CONTENT_CODE) {
            //訂單內容回調
            if (resultCode == Activity.RESULT_OK) {
                //打印成功
                //結賬成功
                //關閉當前頁面
                killMyself();
            }
        }
    }

    @Override
    public void onPageSizeChanged(int pageSize) {
    }

    @Override
    public void onPageSelect(int pageIndex) {
    }

    @Override
    public void showBtnMealModifyRestoreVisibility(boolean show) {
    }

    private OnSendOrderListener sendOrderListener;

    public void setSendOrderListener(OnSendOrderListener sendOrderListener) {
        this.sendOrderListener = sendOrderListener;
    }

    public interface OnSendOrderListener {
        void sendOrder();
    }
}
