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

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gingersoft.gsa.cloud.order.bean.discount.MemberWalletCoupon;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.R2;
import com.gingersoft.gsa.cloud.table.di.component.DaggerCouponComponent;
import com.gingersoft.gsa.cloud.table.mvp.contract.CouponContract;
import com.gingersoft.gsa.cloud.table.mvp.presenter.discount.CouponPresenter;
import com.gingersoft.gsa.cloud.ui.adapter.TagViewAdapter;
import com.gingersoft.gsa.cloud.ui.bean.TagViewItem;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

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

import javax.inject.Inject;

import butterknife.BindView;

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


/**
 * Description:會員錢包優惠券
 * Created by MVPArmsTemplate on 04/02/2021 17:28
 */
public class CouponFragment extends BaseFragment<CouponPresenter> implements CouponContract.View {

    @BindView(R2.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R2.id.rv_coupon)
    RecyclerView rvCoupon;

    @Inject
    List<TagViewItem> mMemberCouponList;
    @Inject
    TagViewAdapter mMemberCouponAdapter;

    /**
     * 0=沒有限制
     * 1=食品專有
     * 2=帳單專有
     */
    public static final byte NO_LIMIT_DISCOUNT = 0;
    public static final byte FOOD_LIMIT_DISCOUNT = 1;
    public static final byte BILL_LIMIT_DISCOUNT = 2;
    private int limitType = NO_LIMIT_DISCOUNT;

    private LoadService loadService;

    public static final String UPDATE_COUPON_CHECKED_STATE = "updateCouponCheckedStateEvent";

    public static CouponFragment newInstance(int limitType) {
        CouponFragment fragment = new CouponFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("limitType", limitType);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerCouponComponent //如找不到该类,请编译一下项目
                .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_coupon, container, false);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        Bundle arguments = getArguments();
        limitType = arguments.getInt("limitType");
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        loadService = LoadSir.getDefault().register(refreshLayout, (v) -> {
            mPresenter.getMemberWalletList(null, false, limitType);
        });

        initAdapter();
        initRefreshLayout();

        EventBus.getDefault().registerSticky(this);
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        mPresenter.getMemberWalletList(null, false, limitType);
    }

    private void initAdapter() {
        rvCoupon.setLayoutManager(createLayoutManager());
        rvCoupon.setAdapter(mMemberCouponAdapter);
        mMemberCouponAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (onCouponItemClickListener != null) {
                onCouponItemClickListener.onItemClick((MemberWalletCoupon) mMemberCouponList.get(position).getTargetObj(), position);
            }
        });
    }

    private RecyclerView.LayoutManager createLayoutManager() {
        return new GridLayoutManager(mContext, 3, LinearLayoutManager.VERTICAL, false) {
            @Override
            public RecyclerView.LayoutParams generateDefaultLayoutParams() {
                return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            }
        };
    }

    private void initRefreshLayout() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                mPresenter.getMemberWalletList(refreshLayout, false, limitType);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                mPresenter.getMemberWalletList(refreshLayout, true, limitType);
            }
        });
        refreshLayout.setEnableLoadMore(false);
    }

    @Subscriber(tag = CouponFragment.UPDATE_COUPON_CHECKED_STATE, mode = ThreadMode.MAIN)
    public void updateCouponCheckedState(Map<String, MemberWalletCoupon> selectCouponMap) {
        if (selectCouponMap.size() > 0) {
            for (TagViewItem<MemberWalletCoupon> tagViewItem : mMemberCouponList) {
                final MemberWalletCoupon walletCoupon = tagViewItem.getTargetObj();
                if (selectCouponMap.containsKey(walletCoupon.getCouponNo())) {
                    tagViewItem.setChecked(true);
                } else {
                    tagViewItem.setChecked(false);
                }
            }
        } else {
            for (TagViewItem<MemberWalletCoupon> tagViewItem : mMemberCouponList) {
                tagViewItem.setChecked(false);
            }
        }
        mMemberCouponAdapter.notifyDataSetChanged();
    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading(String message) {
        if (message != null)
            LoadingDialog.showDialogForLoading(_mActivity, message, true);
        else
            LoadingDialog.showDialogForLoading(_mActivity);
    }

    @Override
    public void hideLoading() {
        LoadingDialog.cancelDialogForLoading();
    }

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

    @Override
    public void launchActivity(@NonNull Intent intent) {
        if (intent != null) {
            ArmsUtils.startActivity(intent);
        }
    }

    @Override
    public void killMyself() {
        pop();
        super.onBackPressedSupport();
    }

    @Override
    public void returnMemberCouponList(List<MemberWalletCoupon> memberCoupons) {
        List<TagViewItem> tagViewItems = castTagItem(memberCoupons);
        if (mMemberCouponList.size() > 0) {
            mMemberCouponList.clear();
        }
        mMemberCouponList.addAll(tagViewItems);
        mMemberCouponAdapter.notifyDataSetChanged();
    }

    private List<TagViewItem> castTagItem(List<MemberWalletCoupon> memberCoupons) {
        List<TagViewItem> tagViewItems = new ArrayList<>();
        for (MemberWalletCoupon coupon : memberCoupons) {
            TagViewItem<MemberWalletCoupon> tagViewItem = new TagViewItem();
            tagViewItem.setId(coupon.getCouponId());
            tagViewItem.setText(coupon.getCouponTypeName());
            tagViewItem.setTargetObj(coupon);
            tagViewItems.add(tagViewItem);
        }
        return tagViewItems;
    }

    @Override
    public void showLoadSirSuccess() {
        loadService.showSuccess();
    }

    @Override
    public void showLoadSirCall(Class<? extends Callback> call) {
        loadService.showCallback(call);
    }

    @Override
    public LoadService getLoadService() {
        return loadService;
    }

    private OnCouponItemClickListener onCouponItemClickListener;

    public void setOnCouponItemClickListener(OnCouponItemClickListener onCouponItemClickListener) {
        this.onCouponItemClickListener = onCouponItemClickListener;
    }

    public interface OnCouponItemClickListener {
        void onItemClick(MemberWalletCoupon item, int position);
    }
}
