package com.gingersoft.coldchain_module.mvp.ui.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.billy.cc.core.component.CC;
import com.gingersoft.coldchain_module.R;
import com.gingersoft.coldchain_module.R2;
import com.gingersoft.coldchain_module.di.component.DaggerColdChainMainComponent;
import com.gingersoft.coldchain_module.di.module.ColdChainMainModule;
import com.gingersoft.coldchain_module.mvp.constans.ColdChainConstants;
import com.gingersoft.coldchain_module.mvp.contract.ColdChainMainContract;
import com.gingersoft.coldchain_module.mvp.model.bean.OrderList;
import com.gingersoft.coldchain_module.mvp.model.bean.SupplementInfoBean;
import com.gingersoft.coldchain_module.mvp.presenter.ColdChainMainPresenter;
import com.gingersoft.coldchain_module.mvp.ui.fragment.OrderListFragment;
import com.gingersoft.gsa.cloud.common.constans.AppConstans;
import com.gingersoft.gsa.cloud.common.constans.DeliveryPickConstans;
import com.gingersoft.gsa.cloud.common.constans.ExpandConstant;
import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager;
import com.gingersoft.gsa.cloud.common.core.restaurant.utils.RestaurantExpandInfoUtils;
import com.gingersoft.gsa.cloud.common.service.GetInfoUpdateService;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.common.utils.toast.ToastUtils;
import com.gingersoft.gsa.cloud.ui.utils.AppDialog;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.google.android.material.tabs.TabLayout;
import com.jess.arms.base.BaseFragmentActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;
import com.xuexiang.rxutil2.exception.RxException;
import com.xuexiang.rxutil2.rxjava.RxJavaUtils;
import com.xuexiang.rxutil2.subsciber.BaseSubscriber;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static androidx.fragment.app.FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT;
import static com.jess.arms.utils.Preconditions.checkNotNull;


public class ColdChainMainActivity extends BaseFragmentActivity<ColdChainMainPresenter> implements ColdChainMainContract.View, View.OnClickListener {

    @BindView(R2.id.view_pager)
    ViewPager viewPager;
    @BindView(R2.id.coldchain_main_top_bar)
    QMUITopBar topBar;
    @BindView(R2.id.coldchain_main_tabs)
    TabLayout tabLayout;
    @BindView(R2.id.tv_balance)
    TextView tvBalance;

    @BindView(R2.id.cold_chain_takeaway_progress)
    ProgressBar mTakeAwayPb;
    @BindView(R2.id.tv_cold_chain_takeaway_num)
    TextView mTvTakeAwayNum;

    @BindView(R2.id.cold_chain_self_progress)
    ProgressBar mSelfPb;
    @BindView(R2.id.tv_cold_chain_self_num)
    TextView mTvSelfNum;
    @BindView(R2.id.ed_cold_chain_order_num_search)
    EditText etSearch;
    @BindView(R2.id.tv_cold_chain_restaurant_state)
    TextView tvRestaurantState;
    @BindView(R2.id.cb_auto_receiving_orders)
    CheckBox autoReceivingOrders;

    private final int autoReceivingOrderInterval = 15;

    public void setOrderNum(OrderList.DataBeanX.DataBean bean) {
        mTakeAwayPb.setMax(bean.getMaxOrder() == 0 ? 1 : bean.getMaxOrder());
        mTakeAwayPb.setProgress(bean.getNum());

        mSelfPb.setMax(bean.getMaxOrderSelf() == 0 ? 1 : bean.getMaxOrder());
        mSelfPb.setProgress(bean.getSelflNum());

        mTvTakeAwayNum.setText(bean.getNum() + "/" + bean.getMaxOrder());
        mTvSelfNum.setText(bean.getSelflNum() + "/" + bean.getMaxOrderSelf());
    }

    public List<String> getStatus() {
        return status;
    }

    private List<String> status = Arrays.asList("0,1,2,3", "0,1", "2", "3");

    private List<OrderListFragment> fragments;

    private ClearHeartBroadcastReceiver clearHeartBroadcastReceiver;

    private int restaurantId;

    private int fragmentPosition;

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

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

    private Disposable autoOrderDisposable;

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

        restaurantId = RestaurantInfoManager.newInstance().getRestaurantId();
        fragments = new ArrayList<>();
        List<String> titles = Arrays.asList("全部", "待確認", "待提交", "派送中");
        for (int i = 0; i < titles.size(); i++) {
            fragments.add(OrderListFragment.newInstance(status.get(i), ColdChainConstants.orderType + "", i));
        }
        getNumByOrderTypeInvoke("loadNumber");
        initViewPager(titles);
        initService();
        initHearBroadcast();

        autoReceivingOrders.setChecked(RestaurantExpandInfoUtils.getValue(ExpandConstant.FrozenChainAutoOrder, false));
        autoReceivingOrders.setOnCheckedChangeListener((buttonView, isChecked) -> {
            RestaurantExpandInfoUtils.setValue(ExpandConstant.FrozenChainAutoOrder, isChecked);
            if (autoOrderDisposable != null && !autoOrderDisposable.isDisposed()) {
                autoOrderDisposable.dispose();
            }
            if (isChecked) {
                //開始自動接單
                autoOrderDisposable = RxJavaUtils.polling(1, autoReceivingOrderInterval, aLong -> mPresenter.startToBeConfirmedOrderList(restaurantId));
            } else {
                mPresenter.stopAutoReceivingOrders();
            }
        });
    }

    public void getNumByOrderTypeInvoke(String functionName) {
        Class[] parameterTypes = {SupplementInfoBean.class};
        try {
            Method method = this.getClass().getDeclaredMethod(functionName, parameterTypes);
            mPresenter.getNumByOrderType(restaurantId, method, this);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    private void initViewPager(List<String> titles) {
        viewPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager(), BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return titles.size();
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return titles.get(position);
            }
        });
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                fragments.get(position).setData(status.get(position));
                fragmentPosition = position;
                fragments.get(viewPager.getCurrentItem()).onRefreshData();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        tabLayout.setupWithViewPager(viewPager);
    }

    private void initService() {
        //開啟websocket
        Intent intent = new Intent(getApplicationContext(), GetInfoUpdateService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent);
        } else {
            startService(intent);
        }
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    private void initHearBroadcast() {
        clearHeartBroadcastReceiver = new ClearHeartBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter(AppConstans.CLEAR_ORDER_RECEIVING_HEART);
        registerReceiver(clearHeartBroadcastReceiver, intentFilter);
    }

    private GetInfoUpdateService.MyBind bind = null;

    private ServiceConnection serviceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            bind = (GetInfoUpdateService.MyBind) service;
            if (bind != null) {
                bind.setOnPostCallBack(type -> {
                    // -1斷開連接,\n-2:消息傳輸錯誤,\n0:連接消息,\n1：登錄通知,\n2：登出通知,\n3：外賣送單通知,\n4：自取送單通知,\n5:歷史訂單通知,\n6:修改訂單狀態通知,\n7:支付成功通知"
                    if (type == 3 || type == 5
                            || type == 6 || type == 7) {//ColdChainConstants.orderType
                        fragments.get(viewPager.getCurrentItem()).onRefreshData();
                        mPresenter.getBalance();
                    }
                    if (type == 3 || type == 6 || type == 7) {
                        getNumByOrderTypeInvoke("loadNumber");
                    }
                    if (autoReceivingOrders.isChecked()) {
                        mPresenter.startToBeConfirmedOrderList(restaurantId);
                    }
                });
                bind.execute(aBoolean -> null);
                bind.setJumpActivity(ColdChainMainActivity.class);
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    private int confirmedOrderNum;

    @Override
    public void loadNumber(SupplementInfoBean bean) {
        if (bean != null && bean.getData() != null && bean.getData().getOrderVOS() != null) {
            topBar.setTitle("凍鏈接單" + "(" + 0 + "/" + bean.getData().getColdChainPickUpNum() + ")");
            for (SupplementInfoBean.DataBean.OrderVOSBean orderVOSBean : bean.getData().getOrderVOS()) {
                if (orderVOSBean.getOrderType() == ColdChainConstants.orderType) {
                    confirmedOrderNum = orderVOSBean.getOrderNum();
                    topBar.setTitle("凍鏈接單" + "(" + confirmedOrderNum + "/" + bean.getData().getColdChainPickUpNum() + ")");
                }
            }
        }
    }

    @Override
    public void loadBalance(double price, double bond, boolean isBlink) {
        tvBalance.setVisibility(View.VISIBLE);
        tvBalance.setText("餘額：" + price + "（保證金" + bond + "）");
        if (isBlink) {
            tvBalance.setTextColor(ContextCompat.getColor(mContext, R.color.theme_red_color));
            //提示餘額不足
//            int colorFrom = ContextCompat.getColor(mContext, R.color.red);
//            int colorTo = ContextCompat.getColor(mContext, R.color.blue);
//            colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
//            colorAnimation.addUpdateListener(animation -> tvBalance.setTextColor((Integer) animation.getAnimatedValue()));
//            colorAnimation.setDuration(200);
//            colorAnimation.setRepeatMode(RESTART);
//            colorAnimation.setRepeatCount(-1);
//            colorAnimation.start();
        } else {
            tvBalance.setTextColor(ContextCompat.getColor(mContext, R.color.theme_333_color));
        }
    }

    @Override
    public void setRestaurantState(int state) {
        if (stateBg == null) {
            stateBg = new GradientDrawable();
        }
        switch (state) {
            case 0:
                tvRestaurantState.setText("休息中");
                stateBg.setColor(ContextCompat.getColor(this, R.color.color_c8));
                break;
            case 1:
                tvRestaurantState.setText("營業中");
                stateBg.setColor(ContextCompat.getColor(this, R.color.restaurant_color_open));
                break;
            case 2:
                tvRestaurantState.setText("繁忙不接");
                stateBg.setColor(ContextCompat.getColor(this, R.color.restaurant_color_busy_close));
                break;
            case 3:
                tvRestaurantState.setText("繁忙可接");
                stateBg.setColor(ContextCompat.getColor(this, R.color.restaurant_color_busy_open));
                break;
        }
        tvRestaurantState.setBackground(stateBg);
    }

    @Override
    public void refreshOrderState(long id) {
        fragments.get(viewPager.getCurrentItem()).notifyDataState(id, ColdChainConstants.ORDER_CONFIRMED);
    }

    @Override
    protected void onStart() {
        super.onStart();
        getNumByOrderTypeInvoke("loadNumber");
    }

    private class ClearHeartBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //收到關閉心跳的廣播後，同時關閉接單頁面
            killMyself();
        }
    }

    @Override
    public void initIntent() {

    }

    private QMUIPopup pop;

    @Override
    public void initTopBar() {
        topBar.setTitle("凍鏈接單");
        topBar.addLeftImageButton(R.drawable.icon_return, R.id.iv_left_back).setOnClickListener(v -> killMyself());
        topBar.addRightImageButton(R.drawable.icon_topbar_overflow, R.id.topbar_right_change_button).setOnClickListener(v -> {
            if (pop == null) {
                View view = LayoutInflater.from(this).inflate(R.layout.cold_chain_main_popup, null);
                pop = QMUIPopups.popup(this)
                        .preferredDirection(QMUIPopup.DIRECTION_BOTTOM)
                        .view(view)
                        .radius(QMUIDisplayHelper.dp2px(this, 5))
                        .arrow(true)
                        .shadow(true)
                        .dimAmount(0.6f)
                        .offsetYIfTop(0)
                        .animStyle(QMUIPopup.ANIM_AUTO)
                        .show(v);
                view.findViewById(R.id.layout_history_order).setOnClickListener(v1 -> {
                    CC.obtainBuilder(com.gingersoft.gsa.cloud.component.ComponentName.COMPONENT_DELIVERYPICK)
                            .setActionName("historyActivity")
                            .addParam(DeliveryPickConstans.ORDER_TYPE, "1")
                            .build()
                            .call();
                    pop.dismiss();
                });
            } else {
                pop.show(v);
            }
        });
        topBar.setBackgroundColor(ContextCompat.getColor(mContext, R.color.theme_color));
    }

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

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

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (autoOrderDisposable != null) {
            autoOrderDisposable.dispose();
        }
        if (bind != null) {
            bind.setOnPostCallBack(null);
        }
        unregisterReceiver(clearHeartBroadcastReceiver);
        unbindService(serviceConnection);
    }

    private QMUIPopup restaurantPopup;
    private GradientDrawable stateBg;

    @OnClick({R2.id.btn_supplement_order, R2.id.btn_pick_up, R2.id.iv_cold_chain_search_order, R2.id.tv_cold_chain_restaurant_state})
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.btn_supplement_order) {
            if (confirmedOrderNum > 15) {
                showMessage("訂單數量足夠，不需要補單");
            } else {
                //補單
                getNumByOrderTypeInvoke("jumpSupplementOrder");
            }
        } else if (viewId == R.id.btn_pick_up) {
            getNumByOrderTypeInvoke("pickUp");
        } else if (viewId == R.id.iv_cold_chain_search_order) {
            //搜索
            if (etSearch.getText() != null && TextUtil.isNotEmptyOrNullOrUndefined(etSearch.getText().toString())) {
                if (fragments != null && fragmentPosition < fragments.size()) {
                    fragments.get(fragmentPosition).getOrderList(etSearch.getText().toString());
                }
            } else {
                ToastUtils.show(mContext, "請輸入手機號或訂單號");
            }
        } else if (viewId == R.id.tv_cold_chain_restaurant_state) {
            if (restaurantPopup == null) {
                View view = LayoutInflater.from(this).inflate(R.layout.popup_layout_restaurant_state, null);
                restaurantPopup = QMUIPopups.popup(this)
                        .preferredDirection(QMUIPopup.DIRECTION_BOTTOM)
                        .view(view)
                        .radius(QMUIDisplayHelper.dp2px(this, 5))
                        .arrow(false)
                        .shadow(false)
                        .offsetYIfTop(0)
                        .animStyle(QMUIPopup.ANIM_AUTO)
                        .show(v);
                view.findViewById(R.id.tv_restaurant_open).setOnClickListener(view1 -> updateRestaurantState(1));
                view.findViewById(R.id.tv_restaurant_close).setOnClickListener(view1 -> updateRestaurantState(0));
                view.findViewById(R.id.tv_restaurant_busy_close).setOnClickListener(view1 -> updateRestaurantState(2));
                view.findViewById(R.id.tv_restaurant_busy_open).setOnClickListener(view1 -> updateRestaurantState(3));
            } else {
                restaurantPopup.show(v);
            }
        }
    }

    private void updateRestaurantState(int state) {
        if (state != 0 && state != 2) {
            mPresenter.updateRestOpenStatus(state, restaurantId);
        } else {
            //提示補單
            new AppDialog().showWaringDialog(this, "是否暫停接單？", (view, dialog) -> {
                mPresenter.updateRestOpenStatus(state, restaurantId);
                dialog.dismiss();
            });
        }
        restaurantPopup.dismiss();
    }

    public void pickUp(SupplementInfoBean bean) {
        if (orderNumIsSatisfyPickUp(bean)) {
            mPresenter.pickUp(restaurantId);
        } else {
            //提示補單
            new AppDialog().showWaringDialog(this, "不滿足送貨條件，是否需要補單？", (view, dialog) -> {
                dialog.dismiss();
                jumpSupplementOrder(bean);
            });
        }
    }

    public void jumpSupplementOrder(SupplementInfoBean bean) {
        if (orderNumIsSatisfyPickUp(bean)) {
            //現有訂單數 < 小於配置的最低訂單數 才允許補單
            showMessage("訂單數已達到最低配送要求，不需要補單");
        } else {
            Intent intent = new Intent(mContext, SupplementOrderActivity.class);
            launchActivity(intent);
        }
    }

    private boolean orderNumIsSatisfyPickUp(SupplementInfoBean bean) {
        if (bean != null && bean.getData() != null && bean.getData().getOrderVOS() != null) {
            int orderNum = 0;
            for (SupplementInfoBean.DataBean.OrderVOSBean orderVOSBean : bean.getData().getOrderVOS()) {
                if (orderVOSBean.getOrderType() == ColdChainConstants.orderType) {
                    orderNum = orderVOSBean.getOrderNum();
                }
            }
            return orderNum >= bean.getData().getColdChainPickUpNum();
        }
        return false;
    }

    public boolean isAutoReceivingOrder() {
        return autoReceivingOrders.isChecked();
    }
}

