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

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.gingersoft.coldchain_module.R;
import com.gingersoft.coldchain_module.R2;
import com.gingersoft.coldchain_module.di.component.DaggerOrderListComponent;
import com.gingersoft.coldchain_module.di.module.OrderListModule;
import com.gingersoft.coldchain_module.mvp.contract.OrderListContract;
import com.gingersoft.coldchain_module.mvp.model.bean.OrderList;
import com.gingersoft.coldchain_module.mvp.presenter.OrderListPresenter;
import com.gingersoft.coldchain_module.mvp.ui.activity.ColdChainMainActivity;
import com.gingersoft.coldchain_module.mvp.ui.activity.OrderDetailsActivity;
import com.gingersoft.coldchain_module.mvp.ui.adapter.OrderListAdapter;
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.print.bean.OrderDetails;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.List;

import butterknife.BindView;

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


public class OrderListFragment extends BaseFragment<OrderListPresenter> implements OrderListContract.View {

    @BindView(R2.id.cold_chain_order_list)
    RecyclerView mRvOrderList;
    @BindView(R2.id.layout_nodata)
    LinearLayout layoutNoData;
    OrderListAdapter adapter;

    @BindView(R2.id.cold_chain_refresh_layout)
    SmartRefreshLayout mRefreshLayout;
    private int restaurantId;

    private String status;
    private String type;
    private int position;
    private int page = 1;

    public static OrderListFragment newInstance(String status, String type, int position) {
        OrderListFragment fragment = new OrderListFragment();
        Bundle arguments = new Bundle();
        arguments.putString("status", status);
        arguments.putString("type", type);
        arguments.putInt("position", position);
        fragment.setArguments(arguments);
        return fragment;
    }

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

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

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mRefreshLayout.setPrimaryColorsId(android.R.color.transparent, android.R.color.black);
        restaurantId = GsaCloudApplication.getRestaurantId();

        Bundle arguments = getArguments();
        if (arguments != null) {
            status = getArguments().getString("status");
            type = getArguments().getString("type");
            position = getArguments().getInt("position");
        }
        onRefreshData();
        mRefreshLayout.setOnRefreshListener(refreshLayout -> onRefreshData());
        mRefreshLayout.setOnLoadMoreListener(refreshLayout -> {
            page++;
            getOrderList("");
        });
    }

    public void onRefreshData() {
        page = 1;
        mRefreshLayout.setEnableLoadMore(true);
        getOrderList("");
    }

    public void getOrderList(String phone) {
        mPresenter.getOrderList(restaurantId, page, status, type, phone);
    }

//    @Override
//    public void onResume() {
//        super.onResume();
//        onRefreshData();
//    }

    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)} 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     * <p>
     * Example usage:
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {
//        if (data instanceof Message) {
//        mPresenter.getOrderList(restaurantId, 0, status, type);
//        }
    }

    @Override
    public void showLoading(String message) {

    }

    @Override
    public void hideLoading() {

    }

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

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

    @Override
    public void killMyself() {

    }

    @Override
    public void loadOrderList(List<OrderList.DataBeanX.DataBean> data) {
//        if (data.size() <= 0) {
//            page--;
//            mRefreshLayout.setEnableLoadMore(false);
//        }
        mRefreshLayout.finishRefresh();
        mRefreshLayout.finishLoadMore();
        if (data != null) {
            layoutNoData.setVisibility(data.size() <= 0 ? View.VISIBLE : View.GONE);
            mRvOrderList.setVisibility(data.size() <= 0 ? View.GONE : View.VISIBLE);
            if (adapter == null) {
                adapter = new OrderListAdapter(data);
                mRvOrderList.setLayoutManager(new LinearLayoutManager(mContext));
                adapter.setOnItemClickListener((adapter1, view, position) -> {
                    Intent intent = new Intent(mContext, OrderDetailsActivity.class);
                    intent.putExtra("orderId", data.get(position).getId());
                    intent.putExtra("isRead", data.get(position).getIsRead());
                    intent.putExtra("position", position);
                    startActivityForResult(intent, 1001);
                });
                mRvOrderList.setAdapter(adapter);
            } else {
                adapter.setList(data);
            }
        } else {
            layoutNoData.setVisibility(View.VISIBLE);
            mRvOrderList.setVisibility(View.GONE);
        }
    }

    @Override
    public void notifyByPosition(int position, OrderList.DataBeanX.DataBean dataBean) {
        if (adapter != null) {
            adapter.setData(position, dataBean);
            notifyActivityOrderNum();
        }
    }

    public void notifyDataState(long id, int state) {
        if (adapter != null) {
            List<OrderList.DataBeanX.DataBean> data = adapter.getData();
            for (int i = 0; i < data.size(); i++) {
                if (data.get(i).getId() == id) {
                    data.get(i).setSTATUS(state);
                }
            }
            adapter.setList(data);
        }

    }

    @Override
    public void removeItem(int position) {
        if (adapter != null) {
            adapter.removeAt(position);
            notifyActivityOrderNum();
        }
    }

    @Override
    public void loadOrderTotalNum(OrderList.DataBeanX.DataBean bean) {
        if (getActivity() instanceof ColdChainMainActivity && bean != null) {
            if (status.equals(((ColdChainMainActivity) getActivity()).getStatus().get(0))) {
                ((ColdChainMainActivity) getActivity()).setOrderNum(bean);
            }
        }
    }

    @Override
    public void getOrderDetails(OrderDetails.DataBean dataBean) {
        if (getActivity() instanceof ColdChainMainActivity && ((ColdChainMainActivity) getActivity()).isAutoReceivingOrder()) {
            if (dataBean.getOrderStatus() == 0 || dataBean.getOrderStatus() == 1) {
                mPresenter.thirdDelivery(dataBean);
            }
        }
    }

    private void notifyActivityOrderNum() {
        if (getActivity() instanceof ColdChainMainActivity) {
            ((ColdChainMainActivity) getActivity()).getNumByOrderTypeInvoke("loadNumber");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1001 && data != null && mPresenter != null) {
            int position = data.getIntExtra("position", -1);
            boolean isPrint = data.getBooleanExtra("printPdf", false);
            if (isPrint) {
                mPresenter.notifyDataPrintStateByPosition(position, true);
            } else {
                int orderStatus = data.getIntExtra("orderStatus", 0);
                mPresenter.notifyDataByPosition(position, orderStatus);
            }
        }
    }
}
