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

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewStub;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
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 androidx.viewpager2.widget.ViewPager2;

import com.gingersoft.gsa.cloud.common.constans.FoodSummaryConstans;
import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager;
import com.gingersoft.gsa.cloud.common.core.table.TableBean;
import com.gingersoft.gsa.cloud.common.core.user.UserContext;
import com.gingersoft.gsa.cloud.common.scan.ScanHelper;
import com.gingersoft.gsa.cloud.common.utils.encryption.DESUtil;
import com.gingersoft.gsa.cloud.common.utils.log.LogUtil;
import com.gingersoft.gsa.cloud.common.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.order.order.BaseOrder;
import com.gingersoft.gsa.cloud.order.order.MealOrder;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.R2;
import com.gingersoft.gsa.cloud.table.di.component.DaggerMealBillComponent;
import com.gingersoft.gsa.cloud.table.mvp.constant.OrderConentActionConstant;
import com.gingersoft.gsa.cloud.table.mvp.constant.TableActionConstant;
import com.gingersoft.gsa.cloud.table.mvp.contract.MealBillContract;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.event.InitTableEvent;
import com.gingersoft.gsa.cloud.table.mvp.presenter.mealstand.MealBillPresenter;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.table.InputTableFragment;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.table.RegionTableFragment;
import com.gingersoft.gsa.cloud.table.mvp.ui.widget.ChooseNumberDialog;
import com.gingersoft.gsa.cloud.ui.adapter.ViewPager2Adapter;
import com.gingersoft.gsa.cloud.ui.utils.QMUITabSegmentUtils;
import com.gyf.immersionbar.ImmersionBar;
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.QMUIAlphaTextView;
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.QMUITabSegment;
import com.qmuiteam.qmui.widget.tab.QMUITabSegment2;
import com.qmuiteam.qmui.widget.tab.QMUITabView;
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 butterknife.BindView;
import butterknife.OnClick;

import static com.gingersoft.gsa.cloud.table.mvp.ui.activity.table.TableActivity.FUNCTION_ALL_TABLE;
import static com.gingersoft.gsa.cloud.table.mvp.ui.activity.table.TableActivity.FUNCTION_STATE_TABLE;


/**
 * ================================================
 * 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 MealBillActivity extends BaseMealActivity<MealBillPresenter> implements MealBillContract.View, Window.Callback {

    @Inject
    AppManager mAppManager;

    @BindView(R2.id.tv_action_name)
    TextView tvActionName;
    @BindView(R2.id.tv_server_main)
    TextView tvServerMain;
    @BindView(R2.id.tv_time)
    TextView tvTime;
    @BindView(R2.id.btn_people_num)
    QMUIAlphaTextView btnPeopleNum;
    @BindView(R2.id.tv_order_no)
    TextView tvOrderNo;
    @BindView(R2.id.rv_top_function)
    RecyclerView rvTopFunction;
    @BindView(R2.id.tv_whole)
    TextView tvWhole;
    @BindView(R2.id.tv_total_text)
    TextView tvTotalText;
    @BindView(R2.id.btn_order_count)
    Button btnOrderCount;
    @BindView(R2.id.fl_order_content)
    RelativeLayout flOrderContent;
    @BindView(R2.id.tv_total)
    TextView tvTotal;
    @BindView(R2.id.fl_container)
    FrameLayout flContainer;
    @BindView(R2.id.vs_transfer_food)
    ViewStub vsTransferFood;

    private TextView tv_table_name, tv_show_popup;
    private QMUITabSegment2 mTabSegment;
    private ViewPager2 mContentViewPager;


    public static final int BILL_CODE = 1002;

    private ChooseNumberDialog chooseNumberDialog;

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

    private boolean isRefreshData = false;

    private List<TableBean.DataBean> mTableList;

    private MealOrder mMealOrder;

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

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        mMealOrder = MealOrder.getInstance();
        super.onCreate(savedInstanceState);
        //设置根布局颜色，当layout根布局是FrameLayout时直接使用merge标签，应用DecorView默认就是FrameLayout无需再套一层
        getWindow().getDecorView().setBackgroundColor(ArmsUtils.getColor(mContext, R.color.theme_white_color));
    }

    @Override
    public void configImmersionBar(ImmersionBar immersionBar) {
        immersionBar.fitsSystemWindows(true).statusBarColor("#0E655F").init();
    }

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

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        super.initData(savedInstanceState);

        mPresenter.initTopFunctionData();
        mPresenter.initAdapter();
        mPresenter.initItemListener();
        initTopInfo();
        initBillAmount(mPresenter.getFoodTotal(), mPresenter.getTotalAmount());
    }

    @Override
    public void initBillAmount(double wholeAmount, double totalAmount) {
        int foodCount = mPresenter.getFoodCount();
        if (foodCount > 0) {
            btnOrderCount.setText(String.valueOf(foodCount));
            btnOrderCount.setVisibility(View.VISIBLE);
        } else {
            btnOrderCount.setVisibility(View.INVISIBLE);
        }
        tvWhole.setText("合計  $" + wholeAmount);
        tvTotal.setText("$" + totalAmount);
    }

    private void initTopInfo() {
        if (BaseOrder.isCurrentOrderType(FoodSummaryConstans.TAKEAWAY_TYPE)) {
            btnTable.setText("外賣");
            btnPeopleNum.setText(String.format(getString(R.string.meal_numberman_colon), 1));
            tvTime.setText("時間:" + TimeUtils.getCurrentDate(TimeUtils.DATE_FORMAT_DATE_HM));
            tvServerMain.setText("");
            tvOrderNo.setVisibility(View.GONE);
        } else {
            TableBean.DataBean tableInfo = mMealOrder.getOpenTableInfo();
            Date dd = mMealOrder.getOpenTableTime();
            String openTime = String.format("%tH:%tM", dd, dd);
            String tableno;
            if (tableInfo.getSplitStatus() != 0) {
                tableno = tableInfo.getTableName().trim() + "-" + tableInfo.getTableNumber().trim();
            } else {
                tableno = tableInfo.getTableName();
            }
            btnTable.setText(tableno);
            tvOrderNo.setText(String.format(getString(R.string.meal_order_number), MealOrder.getInstance().getOrderNo()));
            btnPeopleNum.setText(String.format(getString(R.string.meal_numberman_colon), tableInfo.getPerson()));
            tvTime.setText("時間:" + openTime);
            tvServerMain.setText(UserContext.newInstance().getMemberName());
        }
    }

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

    @OnClick({R2.id.btn_table, R2.id.btn_people_num})
    public void onClick(View v) {
        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 OrderConentActionConstant.transfer_food_2:
                hideTransferFoodLayout();
                break;
            default:
                killMyself();
                break;
        }
        mCurrentOperatType = OrderConentActionConstant.order_conetnt_1;
        tvActionName.setVisibility(View.GONE);
    }

    @Override
    public void onBackPressedSupport() {
        super.onBackPressedSupport();
        if (mCurrentOperatType == OrderConentActionConstant.transfer_food_2) {
            hideTransferFoodLayout();
            mCurrentOperatType = OrderConentActionConstant.order_conetnt_1;
            tvActionName.setVisibility(View.GONE);
        }
    }

    @Override
    public void returnTableList(List<TableBean.DataBean> dataBeanList) {
        if (dataBeanList != null && dataBeanList.size() > 0) {
            mTableList = dataBeanList;
            nofilyFragmentUpdateTableData(dataBeanList);
        }
    }

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

    @Override
    public void clickTableItem(TableBean.DataBean dataBean) {
        if (!mPresenter.transferFoodConditionFilter(dataBean.getMemberId())) {
            return;
        }
        switch (mCurrentOperatType) {
            case OrderConentActionConstant.transfer_food_2:
                if (dataBean.getSplitStatus() == 1) {
                    mPresenter.showSplitTableDialog(dataBean.getId());
                } else {
                    //獲取餐檯狀態
                    mPresenter.getTable(dataBean);
                }
                break;
            default:
                break;
        }
    }

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

    @Override
    public void onPauseRefreshTableData() {
        isRefreshData = false;
        mPresenter.stopTablePolling();
        //立刻停止獲取餐檯接口
        mPresenter.disposeGetTablesDataDisposable();
    }

    @Override
    public void showTransferFoodLayout() {
        try {
            View vsContent = vsTransferFood.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) {
            vsTransferFood.setVisibility(View.VISIBLE);
        } finally {
            mCurrentOperatType = OrderConentActionConstant.transfer_food_2;
            tv_table_name.setHint("請選擇目標檯號");
            setActionName();
        }
    }

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

    @Override
    public void showChoosePeopleNumDialog(boolean isNeedCancel) {
        if (chooseNumberDialog == null) {
            chooseNumberDialog = new ChooseNumberDialog(this);
            chooseNumberDialog.builder();
            chooseNumberDialog.setValueHint("請輸入人數");
            if (!isNeedCancel) {
                chooseNumberDialog.setOnBackClickListener(new ChooseNumberDialog.OnBackClickListener() {

                    @Override
                    public void OnBackClick() {
                        recordOperat(true);
                    }
                });
            }
            chooseNumberDialog.setOnClickListener(new ChooseNumberDialog.OnClickListener() {

                @Override
                public void onComfirmClick(String number) {
                    recordOperat(true);
                    mPresenter.updateOrderPerson(number, btnPeopleNum);
                }

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

    @Override
    public void returnTableActivity(boolean initTable) {
        super.returnBeforeActivity(initTable);
    }

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

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

    @Override
    public void setFoodRecycleSpanCount(int size) {
    }

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

    @Override
    public void sendSuccess() {
        TableBean.DataBean tableInfo = MealOrder.getInstance().getOpenTableInfo();
        if (tableInfo != null) {
            //通知更新餐台状态
            EventBus.getDefault().post(new InitTableEvent(tableInfo.getId(), tableInfo.getTableNumber()), "initTable_status_event");
        }
        setResult(Activity.RESULT_OK, null);
        killMyself();
    }

    @Override
    public void setTransferTableName(String tableName) {
        tv_table_name.setText(tableName + "號檯操作中");
    }

    @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();
            }
        } else if (requestCode == ScanHelper.CALL_BACK_QR_RESULT) {

            String qrCodeResult = data.getStringExtra("qrCodeResult");
            String encryptQRCode;
            try {
                encryptQRCode = DESUtil.decryptDES(qrCodeResult, DESUtil.KEY);
                if (!TextUtils.isEmpty(encryptQRCode)) {
                    String qrCodeContent[] = encryptQRCode.split("/");
                    if (qrCodeContent.length == 2) {
                        long couponMemberId = Long.parseLong(qrCodeContent[0]);
                        Long memberId = null;
                        if (mMealOrder.getMemberInfo() != null) {
                            memberId = mMealOrder.getMemberInfo().getId();
                            if (memberId != couponMemberId) {
                                showMessage("請掃描當前會員的優惠券碼");
                                return;
                            }
                        }
                        mPresenter.queryCoupon(memberId, couponMemberId, qrCodeContent[1], RestaurantInfoManager.newInstance().getRestaurantId());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    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() {
        QMUITabBuilder builder = mTabSegment.tabBuilder();
        QMUITab tab1 = builder
                .setText(mTabList[0])
                .build(mContext);
        QMUITab tab2 = builder
                .setText(mTabList[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(mTabList[2])
                .build(mContext);
        mTabSegment
                .addTab(tab1)
                .addTab(tab2)
                .addTab(tab3);
        mContentViewPager.setAdapter(new ViewPager2Adapter(this, createFragments()));
        mContentViewPager.setCurrentItem(mCurrentPageIndex);
        mTabSegment.setOnTabClickListener(new QMUITabSegment.OnTabClickListener() {
            @Override
            public boolean onTabClick(QMUITabView tabView, int index) {
                //彈出選擇狀態彈窗
                if (mCurrentPageIndex == 2 && index == 2) {
                    showTableStatusListPopup(tv_show_popup);
                }
                mCurrentPageIndex = index;
                return false;
            }
        });
        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);
            }
        });
        QMUITabSegmentUtils.setNomalTabSegmentStyle(mTabSegment, mContentViewPager);
    }

    private List<Fragment> createFragments() {

        List<Fragment> fragments = new ArrayList<>();

        inputTableFragment = InputTableFragment.newInstance();
        fragments.add(inputTableFragment);

        allTableFragment = RegionTableFragment.newInstance();
        Bundle bundle = new Bundle();
        bundle.putInt("currentPageIndex", FUNCTION_ALL_TABLE);
        allTableFragment.setArguments(bundle);
        fragments.add(allTableFragment);

        stateTableFragment = RegionTableFragment.newInstance();
        Bundle bundle2 = new Bundle();
        bundle2.putInt("currentPageIndex", FUNCTION_STATE_TABLE);
        stateTableFragment.setArguments(bundle2);
        fragments.add(stateTableFragment);

        return fragments;
    }

    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 OrderConentActionConstant.transfer_food_2:
                tvActionName.setVisibility(View.VISIBLE);
                tvActionName.setText("轉移");
                tvActionName.setBackgroundColor(mPresenter.getFunctionList().get(3).getBackgroundColor());
                break;
            default:
                tvActionName.setVisibility(View.GONE);
                break;
        }
    }

    public boolean isRefreshData() {
        return isRefreshData;
    }

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