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

import android.app.Activity;
import android.content.Intent;
import android.net.ParseException;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import com.gingersoft.gsa.cloud.order.contract.OrderStatusContract;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.R2;
import com.gingersoft.gsa.cloud.table.di.component.DaggerAllOrderComponent;
import com.gingersoft.gsa.cloud.table.mvp.contract.AllOrderContract;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.response.OrderManagerResponse;
import com.gingersoft.gsa.cloud.table.mvp.presenter.orderManager.AllOrderPresenter;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.orderManager.OrderCenterActivity;
import com.google.gson.JsonIOException;
import com.google.gson.JsonParseException;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import org.json.JSONException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.List;
import butterknife.BindView;
import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 03/13/2020 16:25
 * <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 AllOrderFragment extends BaseFragment<AllOrderPresenter> implements AllOrderContract.View {

    @BindView(R2.id.recycle_order)
    RecyclerView recycle_order;
    @BindView(R2.id.refreshLayout)
    RefreshLayout refreshLayout;
    @BindView(R2.id.emptyView)
    QMUIEmptyView mEmptyView;

    private OrderCenterActivity orderCenterActivity;
    private int mCurrentFragmentIndex;

    private int pageIndex = 0;
    private int pageSize = 10;

    public static AllOrderFragment newInstance() {
        AllOrderFragment fragment = new AllOrderFragment();
        return fragment;
    }

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

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_all_order, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mCurrentFragmentIndex = getArguments().getInt("currentFragmentIndex", 0);
        orderCenterActivity = (OrderCenterActivity) mContext;

        mPresenter.initOrderAdapter(mContext);
        initRefreshLayout();
    }

    private void initRefreshLayout() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                //重新獲取第一頁數據
                pageIndex = 0;
                orderCenterActivity.loadOrderList(getOrderType(),getStatusByFragmentIndex(), refreshLayout, false);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                orderCenterActivity.loadOrderList(getOrderType(), getStatusByFragmentIndex(),refreshLayout, true);
            }
        });
    }

    @Override
    public void setData(@Nullable Object data) {
        if (data != null && data instanceof Message) {
            switch (((Message) data).what) {
                case 0:
                    List<OrderManagerResponse> datasBeans = (List<OrderManagerResponse>) ((Message) data).obj;
                    if (mPresenter != null) {
                        mPresenter.updateOrderData(datasBeans);
                    }
                    mEmptyView.hide();
                    recycle_order.setVisibility(View.VISIBLE);
                    break;
                case 1:
                    List<OrderManagerResponse> addDataItem = (List<OrderManagerResponse>) ((Message) data).obj;
                    if (mPresenter != null) {
                        mPresenter.addOrderItem(addDataItem);
                    }
                    mEmptyView.hide();
                    recycle_order.setVisibility(View.VISIBLE);
                    break;
                default:
                    //do something
                    break;
            }
        }
    }


    @Override
    public void showLoading(String message) {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

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

    @Override
    public void killMyself() {

    }

    public Activity getCurrentActivity() {
        return (Activity) mContext;
    }

    private View.OnClickListener onRetryClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //重新加載
            setPageIndex(0);
            orderCenterActivity.loadOrderList(getOrderType(), getStatusByFragmentIndex(),null, false);
        }
    };

    @Override
    public void showEmptyView(boolean isSuccess, int size, Throwable t) {
        if (t != null) {
            if (t instanceof UnknownHostException) {
                //沒有網絡
                mEmptyView.show(false, getResources().getString(R.string.emptyView_mode_desc_fail_title), getResources().getString(R.string.emptyView_mode_desc_fail_desc), getResources().getString(R.string.emptyView_mode_desc_retry), onRetryClickListener);
            } else if (t instanceof SocketTimeoutException) {
                //請求超時
                mEmptyView.show(false, getResources().getString(R.string.emptyView_mode_desc_fail_title), getResources().getString(R.string.emptyView_mode_desc_fail_desc), getResources().getString(R.string.emptyView_mode_desc_retry), onRetryClickListener);
            } else if (t instanceof JsonParseException || t instanceof ParseException || t instanceof JSONException || t instanceof JsonIOException) {
                //數據解析錯誤
                mEmptyView.show(false, getResources().getString(R.string.response_error_data_parsing_error), null, getResources().getString(R.string.emptyView_mode_desc_retry), onRetryClickListener);
            } else {
                //其他error
                mEmptyView.show(false, getResources().getString(R.string.emptyView_mode_desc_fail_title), null, getResources().getString(R.string.emptyView_mode_desc_retry), onRetryClickListener);
            }
            recycle_order.setVisibility(View.INVISIBLE);
            return;
        }
        if (!isSuccess) {
            mEmptyView.show(false, getResources().getString(R.string.emptyView_mode_desc_fail_title), null, getResources().getString(R.string.emptyView_mode_desc_retry), onRetryClickListener);
            recycle_order.setVisibility(View.INVISIBLE);
            return;
        }
        if (size == 0) {
            mEmptyView.show(getResources().getString(R.string.emptyView_mode_desc_double), null);
            recycle_order.setVisibility(View.INVISIBLE);
            return;
        }
        mEmptyView.hide();
        recycle_order.setVisibility(View.VISIBLE);
    }

    @Override
    public void setAllOrderAdapter(DefaultAdapter adapter) {
        recycle_order.setAdapter(adapter);
        initAllOrderRecycleViewLayout();
    }

    private void initAllOrderRecycleViewLayout() {
//        LinearLayoutManager mAllOrderRecycleLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
//        recycle_order.setLayoutManager(mAllOrderRecycleLayoutManager);
//        recycle_order.addItemDecoration(new DividerItemDecoration(orderCenterActivity, LinearLayoutManager.VERTICAL));
    }

    @Override
    public String getOrderType() {
//        switch (mCurrentFragmentIndex) {
//            case 1:
//                return OrderManagerResponse.ORDER_TYPE_TAKEAWAY + "," + OrderManagerResponse.ORDER_TYPE_SELFCOLLECTION;
//            default:
//                return OrderManagerResponse.ORDER_TYPE_DOSHOKU + "";
//        }
        //TODO 账单管理现在只显示餐台模式订单
        return String.valueOf(OrderManagerResponse.ORDER_TYPE_DOSHOKU);
    }

    @Override
    public String getStatusByFragmentIndex(){
        switch (mCurrentFragmentIndex) {
            case 1:
                return OrderStatusContract.STATUS_6+"";
            default:
                return OrderStatusContract.STATUS_4+","+OrderStatusContract.STATUS_5;
        }
    }

    @Nullable
    public OrderManagerResponse getCheckedOrderBean(){
        return mPresenter.getCheckedOrderBean();
    }

    public RefreshLayout getRefreshLayout() {
        return refreshLayout;
    }

    public int getPageIndex() {
        return pageIndex;
    }

    public void setPageIndex(int pageIndex) {
        this.pageIndex = pageIndex;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

}
