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.Message;
import android.os.SystemClock;
import android.view.View;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
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.base.qmui.arch.QMUIFragmentPagerAdapter;
import com.gingersoft.gsa.cloud.base.utils.VibratorUtils;
import com.gingersoft.gsa.cloud.base.utils.log.LogUtil;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.R2;
import com.gingersoft.gsa.cloud.table.app.OrderConentOperatTypeConstant;
import com.gingersoft.gsa.cloud.table.app.TableOperatTypeConstant;
import com.gingersoft.gsa.cloud.table.di.component.DaggerOrderContentComponent;
import com.gingersoft.gsa.cloud.table.mvp.contract.OrderContentContract;
import com.gingersoft.gsa.cloud.table.mvp.presenter.OrderContentPresenter;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.AllTableFragment;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.InputTableFragment;
import com.gingersoft.gsa.cloud.table.mvp.ui.widget.ChooseNumberDialog;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.integration.AppManager;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;
import com.qmuiteam.qmui.widget.tab.QMUITab;
import com.qmuiteam.qmui.widget.tab.QMUITabBuilder;
import com.qmuiteam.qmui.widget.tab.QMUITabIndicator;
import com.qmuiteam.qmui.widget.tab.QMUITabSegment;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.simple.eventbus.EventBus;

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

import javax.inject.Inject;

import androidx.viewpager.widget.ViewPager;
import butterknife.BindView;
import butterknife.OnClick;

import static com.gingersoft.gsa.cloud.table.mvp.ui.activity.TableActivity.FUNCTION_ALL_TABLE;
import static com.gingersoft.gsa.cloud.table.mvp.ui.activity.TableActivity.FUNCTION_STATE_TABLE;
import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description: 賬單內容
 * <p>
 * Created by MVPArmsTemplate on 01/09/2020 19:23
 * <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 OrderContentActivity extends BaseActivity<OrderContentPresenter> implements OrderContentContract.View {

    @Inject
    AppManager mAppManager;

    @BindView(R2.id.ctime)
    Chronometer chronometer;

    @BindView(R2.id.btn_table)
    QMUIAlphaButton btn_table;
    @BindView(R2.id.tv_action_name)
    TextView tv_action_name;

    @BindView(R2.id.tv_server_main)
    TextView tv_server_main;
    @BindView(R2.id.tv_time)
    TextView tv_time;
    @BindView(R2.id.btn_people_num)
    QMUIAlphaButton btn_people_num;
    @BindView(R2.id.rv_top_function)
    RecyclerView rv_top_function;
    @BindView(R2.id.rv_food)
    RecyclerView rv_food;
    @BindView(R2.id.rv_order_detail)
    RecyclerView rv_order_detail;


    @BindView(R2.id.btn_order_count)
    Button btn_order_count;
    @BindView(R2.id.tv_whole)
    TextView tv_whole;
    @BindView(R2.id.tv_total)
    TextView tv_total;

    @BindView(R2.id.vs_transfer_food)
    ViewStub vs_transfer_food;

    public static final int BILL_CODE = 1002;

    private ChooseNumberDialog chooseNumberDialog;

    private TextView tv_table_name, tv_show_popup;
    private QMUITabSegment mTabSegment;
    private ViewPager mContentViewPager;

    private InputTableFragment inputTableFragment;
    private AllTableFragment allTableFragment, stateTableFragment;
    private String[] mTabTitles = {"編號", "全部", "狀態:全部"};
    /**
     * 切換餐檯狀態下拉框
     */
    private QMUIPopup mTableStatusPopup;
    /**
     * 當前顯示頁下標
     */
    private int mCurrentPageIndex = 1;
    /**
     * 當前所顯示餐檯狀態（默認:全部）
     */
    private int mCurrentSelectTableStatus = TableOperatTypeConstant.table_status_0;
    /**
     * 当前选择的操作：
     * 1#賬單內容
     * 2#轉移
     */
    private int mCurrentOperatType = OrderConentOperatTypeConstant.order_conetnt_1;

    private boolean isRefreshData = false;

    private List<TableBean.DataBean> mTableList;


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

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

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        initOrderDetail();
        initTopInfo();
        mPresenter.initTopFunctionData();
        mPresenter.initAdapter();
        mPresenter.initItemListener();
        if (!MyOrderManage.getInstance().isModifyOrder()) {
            //根据倒计时时间自动退出当前页面
            initAutoQuit();
        }
    }

    public void initOrderDetail() {
        int foodCount = mPresenter.getFoodCount();
        if (foodCount > 0) {
            btn_order_count.setText(String.valueOf(foodCount));
            btn_order_count.setVisibility(View.VISIBLE);
        } else {
            btn_order_count.setVisibility(View.INVISIBLE);
        }
        tv_whole.setText("合計 $" + mPresenter.getFoodTotal());
        tv_total.setText("$" + mPresenter.getTotalAmount());
    }

    private void initTopInfo() {

        Date dd = MyOrderManage.getInstance().getOpenTableTime();
        String openTime = String.format("%tH:%tM", dd, dd);

        String tableno = "";
        if (!OpenTableManage.getDefault().isSplite() && OpenTableManage.getDefault().getTableBean() != null) {
            tableno = OpenTableManage.getDefault().getTableBean().getTableName();
        } else {//TODO 暫未分檯功能
//            tableno = GSAApplication.tableContract.getTableno().trim() + "-" + GSAApplication.tableContract.getTableno_split().trim();
        }
        btn_table.setText(tableno);
        tv_time.setText("時間:" + openTime);
        btn_people_num.setText(OpenTableManage.getDefault().getPeopleNumber() + "");
        tv_server_main.setText(GsaCloudApplication.getMemberName(this));
    }

    @Override
    protected void onPause() {
        super.onPause();
        //停止刷新餐檯數據
        onPauseRefreshTableData();
    }

    @OnClick({R2.id.btn_table, R2.id.btn_people_num})
    public void onClick(View v) {
        recordOperat(true);
        int id = v.getId();
        if (id == R.id.btn_table) {
            backPressed();
        } else if (id == R.id.btn_people_num) {
            showChoosePeopleNumDialog(true);
        }
    }

    public void backPressed() {
        switch (mCurrentOperatType) {
            case OrderConentOperatTypeConstant.transfer_food_2:
                hideTransferFoodLayout();
                break;
            default:
                killMyself();
                break;
        }
        mCurrentOperatType = OrderConentOperatTypeConstant.order_conetnt_1;
        tv_action_name.setVisibility(View.GONE);
    }

    @Override
    public void onBackPressed() {
        backPressed();
    }

    @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 returnTableList(List<TableBean.DataBean> dataBeanList) {
        if (dataBeanList != null && dataBeanList.size() > 0) {
            mTableList = dataBeanList;
            nofilyFragmentUpdateTableData(dataBeanList);
        }
    }

    @Override
    public AllTableFragment getCurrentTableFragment() {
        switch (mCurrentPageIndex) {
            case FUNCTION_STATE_TABLE:
                return stateTableFragment;
            default:
                return allTableFragment;
        }
    }

    @Override
    public void clickTableItem(TableBean.DataBean dataBean) {
        switch (mCurrentOperatType) {
            case OrderConentOperatTypeConstant.transfer_food_2:
                mPresenter.getTable(dataBean.getId(), tv_table_name);
                break;
            default:
                break;
        }
    }

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

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

    @Override
    public void showTransferFoodLayout() {
        try {
            View vsContent = vs_transfer_food.inflate();
            tv_table_name = vsContent.findViewById(R.id.tv_table_name);
            tv_show_popup = vsContent.findViewById(R.id.tv_show_popup);
            mContentViewPager = vsContent.findViewById(R.id.contentViewPager);
            mTabSegment = vsContent.findViewById(R.id.tabSegment);
            initTabAndPager();
            //開始刷新餐檯數據
            onStartRefreshTableData();
        } catch (Exception e) {
            vs_transfer_food.setVisibility(View.VISIBLE);
        } finally {
            mCurrentOperatType = OrderConentOperatTypeConstant.transfer_food_2;
            tv_table_name.setHint("請選擇目標檯號");
            setActionName();
        }
    }

    @Override
    public void hideTransferFoodLayout() {
        mCurrentOperatType = OrderConentOperatTypeConstant.order_conetnt_1;
        vs_transfer_food.setVisibility(View.GONE);
    }

    @Override
    public void showChoosePeopleNumDialog(boolean isNeedCancel) {
        if (chooseNumberDialog == null) {
            chooseNumberDialog = new ChooseNumberDialog(this);
            chooseNumberDialog.builder();
            chooseNumberDialog.setValueHint("請輸入人數");
//            mInputNumberDialog2.setTitle(LanguageUtils.get_language_system(this, "Meal.Mannumber", "Number"));
//            mInputNumberDialog2.setHeadLayoutVisibility(View.VISIBLE);
            if (!isNeedCancel)
                chooseNumberDialog.setOnBackClickListener(new ChooseNumberDialog.OnBackClickListener() {

                    @Override
                    public void OnBackClick() {
                        recordOperat(true);
                    }
                });
            int backPageBtnVisibility;
            if (isNeedCancel) {
                backPageBtnVisibility = View.GONE;
            } else {
                backPageBtnVisibility = View.VISIBLE;
            }
//            mInputNumberDialog2.setBackPageBtnVisibility(backPageBtnVisibility);
            chooseNumberDialog.setOnClickListener(new ChooseNumberDialog.OnClickListener() {

                @Override
                public void onComfirmClick(String number) {
                    recordOperat(true);
                    //选择的人数大于0
//                    if (Integer.parseInt(number) > 0) {
//                    }
                    mPresenter.updateOrderPerson(number, btn_people_num);
                }

                @Override
                public void onBackPage() {
                    killMyself();
                }
            });
            chooseNumberDialog.setCancelable(isNeedCancel);
        }
        chooseNumberDialog.show();
    }

    private void initAutoQuit() {
        if (chronometer != null) {
            chronometer.setBase(SystemClock.elapsedRealtime());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
                chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {

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

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

    public void returnTableActivity(boolean initTable) {
        if (initTable && OpenTableManage.getDefault().getTableBean() != null && !MyOrderManage.getInstance().isModifyOrder()) {
            //通知更新餐台状态
            EventBus.getDefault().post(OpenTableManage.getDefault().getTableBean().getId(), "initTable_status_event");
        }
        mAppManager.killActivity(MealStandActivity.class);
        killMyself();
    }

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

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

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

    @Override
    public void setTopFunctionAdapter(DefaultAdapter adapter) {
        rv_top_function.setAdapter(adapter);
        setTopFunctionRecycleLayoutManager();
    }

    @Override
    public void setFoodAdapter(DefaultAdapter adapter) {
        rv_food.setAdapter(adapter);
    }

    @Override
    public void setOrderDetailAdapter(DefaultAdapter adapter) {
        rv_order_detail.setAdapter(adapter);
    }

    @Override
    public void setTopFunctionRecycleLayoutManager() {
        GridLayoutManager funtionRecycleLayoutManager = new GridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        rv_top_function.setLayoutManager(funtionRecycleLayoutManager);
        rv_top_function.setItemAnimator(new DefaultItemAnimator());
    }

    @Override
    public void setFoodRecycleLayoutManager(int orientation) {

    }

    @Override
    public void setTopFunctionRecycleSpanCount(int size) {

    }

    @Override
    public void setFoodRecycleSpanCount(int size) {

    }

    @Override
    public void printSuccess() {
        // 设置返回码和返回携带的数据
        if (OpenTableManage.getDefault() != null) {
            //通知更新餐台状态
            EventBus.getDefault().post(OpenTableManage.getDefault().getTableBean().getId(), "initTable_status_event");
        }
        setResult(Activity.RESULT_OK, null);
        killMyself();
    }

    @Override
    public void sendSuccess() {
        if (OpenTableManage.getDefault() != null) {
            //通知更新餐台状态
            EventBus.getDefault().post(OpenTableManage.getDefault().getTableBean().getId(), "initTable_status_event");
        }
        setResult(Activity.RESULT_OK, null);
        killMyself();
    }

    @Override
    public void startActivityForResult(int Code, Class clazz, Intent intent) {
        if (intent == null) {
            intent = new Intent(mContext, clazz);
        }
        startActivityForResult(intent, Code);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == BILL_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                setResult(Activity.RESULT_OK, null);
                killMyself();
            }
        }
    }

    public void getTables(boolean show, RefreshLayout refreshLayout) {
        mPresenter.getTables(show, refreshLayout);
    }

    /**
     * 根据餐台状态 过滤餐台
     */
    public void filterTableByTableStatus(int status) {
        this.mCurrentSelectTableStatus = status;
        if (mTableList != null) {
            nofilyFragmentUpdateTableData(mTableList);
        }
    }

    /**
     * 更新相應頁面餐檯數據
     *
     * @param dataBeanList
     */
    public void nofilyFragmentUpdateTableData(List<TableBean.DataBean> dataBeanList) {
        Message message = Message.obtain();
        message.what = 1;
        message.obj = dataBeanList;
        message.arg1 = mCurrentSelectTableStatus;
        if (inputTableFragment != null) {
            inputTableFragment.setData(message);
        }
        if (allTableFragment != null) {
            allTableFragment.setData(message);
        }
        if (stateTableFragment != null) {
            stateTableFragment.setData(message);
        }
    }

    private void initTabAndPager() {
        QMUIFragmentPagerAdapter pagerAdapter = new QMUIFragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment createFragment(int position) {
                Bundle bundle = new Bundle();
                switch (position) {
                    case 1:
                        if (allTableFragment != null) {
                            return allTableFragment;
                        }
                        allTableFragment = AllTableFragment.newInstance();
                        bundle.putInt("currentPageIndex", FUNCTION_ALL_TABLE);
                        allTableFragment.setArguments(bundle);
                        return allTableFragment;
                    case 2:
                        if (stateTableFragment != null) {
                            return stateTableFragment;
                        }
                        stateTableFragment = AllTableFragment.newInstance();
                        bundle.putInt("currentPageIndex", FUNCTION_STATE_TABLE);
                        stateTableFragment.setArguments(bundle);
                        return stateTableFragment;
                    default:
                        if (inputTableFragment != null) {
                            return inputTableFragment;
                        }
                        inputTableFragment = InputTableFragment.newInstance();
                        return inputTableFragment;
                }
            }

            @Override
            public int getCount() {
                return mTabTitles.length;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return "";
            }
        };
        QMUITabBuilder builder = mTabSegment.tabBuilder();
        QMUITab tab1 = builder
                .setText(mTabTitles[0])
                .build(mContext);
        QMUITab tab2 = builder
                .setText(mTabTitles[1])
                .build(mContext);
        QMUITab tab3 = builder
                .setNormalDrawable(ContextCompat.getDrawable(mContext, R.drawable.arrow_down_black))
                .setSelectedDrawable(ContextCompat.getDrawable(mContext, R.drawable.arrow_down_black))
                .setIconPosition(QMUITab.ICON_POSITION_RIGHT)
                .setText(mTabTitles[2])
                .build(mContext);
        mTabSegment
                .addTab(tab1)
                .addTab(tab2)
                .addTab(tab3);

        mContentViewPager.setAdapter(pagerAdapter);
        mContentViewPager.setCurrentItem(mCurrentPageIndex);
        int space = QMUIDisplayHelper.dp2px(this, 16);
        mTabSegment.setIndicator(new QMUITabIndicator(QMUIDisplayHelper.dp2px(this, 2), false, true));
        mTabSegment.setDefaultTextSize(QMUIDisplayHelper.dp2px(this, 16), QMUIDisplayHelper.dp2px(this, 16));
        mTabSegment.setPadding(space, 0, space, 0);
        mTabSegment.setupWithViewPager(mContentViewPager, false);
        mTabSegment.setOnTabClickListener(new QMUITabSegment.OnTabClickListener() {
            @Override
            public void onTabClick(int index) {
                //彈出選擇狀態彈窗
                if (mCurrentPageIndex == 2 && index == 2) {
                    showTableStatusListPopup(tv_show_popup);
                }
                mCurrentPageIndex = index;
            }
        });
        mTabSegment.addOnTabSelectedListener(new QMUITabSegment.OnTabSelectedListener() {

            @Override
            public void onTabSelected(int index) {
                mCurrentPageIndex = index;
            }

            @Override
            public void onTabUnselected(int index) {
                //滑動過程中先 暫停刷新數據
            }

            @Override
            public void onTabReselected(int index) {
                LogUtil.d(TAG, "onTabReselected " + index);
            }

            @Override
            public void onDoubleTap(int index) {
                LogUtil.d(TAG, "onDoubleTap " + index);
            }
        });
    }

    private void showTableStatusListPopup(View view) {
        List<Map<String, Object>> lists = new ArrayList<>();
        String[] statusTextList = new String[]{
                "全部",
                "可使用",
                "已使用",
                "已開檯",
                "已印單",
        };
        int[] statusIconList = new int[]{
                R.drawable.table_shape_status_all,
                R.drawable.table_shape_status_be_usable,
                R.drawable.table_shape_status_used,
                R.drawable.table_shape_status_send,
                R.drawable.table_shape_status_print,
        };
        for (int i = 0; i < statusTextList.length; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("text", statusTextList[i]);
            map.put("image", statusIconList[i]);
            lists.add(map);
        }
        SimpleAdapter adapter = new SimpleAdapter(this, lists, R.layout.table_item_popup_select_table_status
                , new String[]{"text", "image"}
                , new int[]{R.id.tv_status, R.id.iv_status});
        mTableStatusPopup = QMUIPopups.listPopup(this, QMUIDisplayHelper.getScreenWidth(this) / 3, QMUIDisplayHelper.getScreenHeight(this), adapter, new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mTableStatusPopup.dismiss();
                mTabSegment.updateTabText(2, "狀態:" + statusTextList[position]);
                //根据选择的餐台操作状态 显示相应的台号
                filterTableByTableStatus(position);
            }
        }).dimAmount(0.6f).show(view);
    }

    private void setActionName() {
        switch (mCurrentOperatType) {
            case OrderConentOperatTypeConstant.transfer_food_2:
                tv_action_name.setVisibility(View.VISIBLE);
                tv_action_name.setText("轉移");
                tv_action_name.setBackgroundColor(mPresenter.getFunctionList().get(3).getBackgroundColor());
                break;
            default:
                tv_action_name.setVisibility(View.GONE);
                break;
        }
    }

    public boolean isRefreshData() {
        return isRefreshData;
    }

    public void setRefreshData(boolean refreshData) {
        isRefreshData = refreshData;
    }
}
