package com.rdiot.yx485.fragment;

import static com.rdiot.yx485.http.Url.BASE_URL2;

import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.rdiot.yx485.R;
import com.rdiot.yx485.adapter.HotListAdapter;
import com.rdiot.yx485.base.BaseFragment;
import com.rdiot.yx485.bean.BannerListBean;
import com.rdiot.yx485.bean.GoodListBean;
import com.rdiot.yx485.databinding.FragmentDiscoverBinding;
import com.rdiot.yx485.http.Url;
import com.rdiot.yx485.main.MainViewModel;
import com.rdiot.yx485.webview.WebViewActivity;
import com.zhouwei.mzbanner.holder.MZHolderCreator;
import com.zhouwei.mzbanner.holder.MZViewHolder;

import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link DiscoverFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class DiscoverFragment extends BaseFragment implements View.OnClickListener {
    private final MainViewModel mViewModel = new MainViewModel();
    private FragmentDiscoverBinding mBinding;

    public DiscoverFragment() {
        // Required empty public constructor
    }

    public static DiscoverFragment newInstance() {
        return new DiscoverFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mBinding = FragmentDiscoverBinding.inflate(inflater, container, false);
        initView();
        initData();
        return mBinding.getRoot();
    }

    private void initView() {
        mBinding.fuwu.setOnClickListener(this);
        mBinding.shangcheng.setOnClickListener(this);
        mBinding.huodong.setOnClickListener(this);
        mBinding.gengduo.setOnClickListener(this);
    }

    private void initData() {
        mViewModel.getErrorMessage().observe(mActivity, this::showMessage);
        mViewModel.getGoodList().observe(mActivity, this::refreshGoodListView);

        mViewModel.getBannerList().observe(mActivity, bannerBeans ->
                mBinding.imageViewBanner.setPages(bannerBeans, (MZHolderCreator<BannerViewHolder>) BannerViewHolder::new));
        mViewModel.loadBannerList();
        mViewModel.loadRecommendGoodList();
    }

    private void refreshGoodListView(List<GoodListBean.DataBean.GoodBean> data) {
        mBinding.recyclerExample.setLayoutManager(new GridLayoutManager(getContext(), 2));
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        int spacingInPixels = (int) (8 * displayMetrics.density); // 间隔大小（单位：像素）
        boolean includeEdge = false; // 是否包含边缘间隔
        mBinding.recyclerExample.addItemDecoration(new GridSpacingItemDecoration(2, spacingInPixels, includeEdge));
        HotListAdapter myAdapter = new HotListAdapter(mActivity, data);
        mBinding.recyclerExample.setAdapter(myAdapter);
    }

    @Override
    public void onClick(View v) {
        String path = "/#/findMore/";
        switch (v.getId()) {
            case R.id.fuwu:
                path += "serviceHome";
                break;
            case R.id.shangcheng:
                path += "mallHome";
                break;
            case R.id.huodong:
                path += "activityHome";
                break;
            case R.id.gengduo:
                path += "moreHome";
                break;
            default:
                break;
        }
        WebViewActivity.newIntent(mActivity, BASE_URL2 + path, null);
    }

    public static class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
        private int spanCount; // 每行的列数
        private int spacing;   // 间隔大小（单位：像素）
        private boolean includeEdge; // 是否包含边缘的间隔

        public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
            this.spanCount = spanCount;
            this.spacing = spacing;
            this.includeEdge = includeEdge;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int position = parent.getChildAdapterPosition(view); // 获取当前项的位置
            int column = position % spanCount; // 当前项所在的列

            if (includeEdge) {
                // 如果包含边缘间隔，计算左右间隔
                outRect.left = spacing - column * spacing / spanCount; // 左边间隔
                outRect.right = (column + 1) * spacing / spanCount;   // 右边间隔
                if (position < spanCount) { // 如果是第一行，设置顶部间隔
                    outRect.top = spacing;
                }
                outRect.bottom = spacing; // 设置底部间隔
            } else {
                // 如果不包含边缘间隔，只设置内部间隔
                outRect.left = column * spacing / spanCount; // 左边间隔
                outRect.right = spacing - (column + 1) * spacing / spanCount; // 右边间隔
                if (position >= spanCount) {
                    outRect.top = spacing; // 如果不是第一行，设置顶部间隔
                }
            }
        }
    }

    public class BannerViewHolder implements MZViewHolder<BannerListBean.DataBean.BannerBean> {
        private ImageView mImageView;

        @Override
        public View createView(Context context) {
            // 返回页面布局
            View view = LayoutInflater.from(context).inflate(R.layout.banner_item, null);
            mImageView = view.findViewById(R.id.banner_image);
            return view;
        }

        @Override
        public void onBind(Context context, int position, BannerListBean.DataBean.BannerBean data) {
            if (data == null) {
                return;
            }

            // 数据绑定
            if (!TextUtils.isEmpty(data.url)) {
                Glide.with(mActivity)
                        .load(Url.BASE_URL2 + data.url)
                        .error(Glide.with(mActivity).load(R.drawable.find_d))
                        .into(mImageView);
            }

            if (!TextUtils.isEmpty(data.detail_url)) {
                mImageView.setOnClickListener(v -> WebViewActivity.newIntent(mActivity, data.detail_url, null));
            }
        }
    }
}