package com.itant.joycity.fragment.first;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.andexert.expandablelayout.library.ExpandableLayoutListView;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bumptech.glide.Glide;
import com.itant.joycity.R;
import com.itant.joycity.adapter.NewestImageAdapter;
import com.itant.joycity.api.JoyUrl;
import com.itant.joycity.bean.Banner;
import com.itant.joycity.bean.NewestImage;
import com.itant.joycity.fragment.BaseFragment;
import com.itant.joycity.tool.StringTool;
import com.itant.joycity.tool.ToastTool;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Jason on 2016/10/6.
 */
public class NewestFragment extends BaseFragment {
    private ConvenientBanner cb_image_ad;

    private List<NewestImage> newestImages;
    private NewestImageAdapter newestImageAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_newest, null);

        cb_image_ad = (ConvenientBanner) view.findViewById(R.id.cb_image_ad);

        ExpandableLayoutListView ellv_newest = (ExpandableLayoutListView) view.findViewById(R.id.ellv_newest);
        newestImages = new ArrayList<>();
        newestImageAdapter = new NewestImageAdapter(getActivity(), newestImages);
        ellv_newest.setAdapter(newestImageAdapter);

        getBanners();
        getExpandableImages();

        return view;
    }

    /**
     * 获取图片列表
     */
    private void getExpandableImages() {
        RequestParams params = new RequestParams(JoyUrl.URL_PICLIST);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!TextUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject != null) {
                            JSONArray jsonArray = jsonObject.getJSONArray("PicList");
                            if (jsonArray != null) {
                                List<NewestImage> imageList = StringTool.stringToList(jsonArray.toString(), NewestImage.class);
                                if (imageList != null) {
                                    if (newestImages != null && newestImages.size() > 0) {
                                        newestImages.clear();
                                    }
                                    newestImages.addAll(imageList);
                                    newestImageAdapter.notifyDataSetChanged();
                                }
                            }
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastTool.showShort(getActivity(), "获取数据失败");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                //Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                //Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 获取Banner图
     */
    private void getBanners() {
        RequestParams params = new RequestParams(JoyUrl.URL_BANNER);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                if (!TextUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject != null) {
                            JSONArray jsonArray = jsonObject.getJSONArray("Banner");

                            if (jsonArray != null) {
                                List<Banner> bannerList = StringTool.stringToList(jsonArray.toString(), Banner.class);
                                if (bannerList != null) {
                                    initialBanner(bannerList);
                                }
                            }
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastTool.showShort(getActivity(), "获取数据失败");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                //Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                //Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 初始化Banner图
     */
    private void initialBanner(List<Banner> bannerList) {
        //自定义你的Holder，实现更多复杂的界面，不一定是图片翻页，其他任何控件翻页亦可。
        //convenientBanner.setManualPageable(false);//设置不能手动影响
        //加载网络图片
        /*List<String> networkImages = new ArrayList<>();
        networkImages.add("http://www.0739i.com.cn/data/attachment/portal/201609/12/150149suhgxupgsyxd4d8s.jpg");
        networkImages.add("http://img.pconline.com.cn/images/upload/upc/tx/wallpaper/1609/27/c0/27587200_1474952314810_800x600.jpg");
        networkImages.add("http://pic2016.5442.com:82/2016/0830/6/11.jpg%21960.jpg");*/

        cb_image_ad.setPages(new CBViewHolderCreator<BannerAdapter>() {
            @Override
            public BannerAdapter createHolder() {
                return new BannerAdapter();
            }
        }, bannerList)
                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                .setPageIndicator(new int[]{R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused})
                //设置指示器的方向
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT);
        cb_image_ad.startTurning(5000);
    }


    private View bannerView;
    class BannerAdapter implements Holder<Banner> {
        ImageView iv_banner;
        TextView tv_banner_title;

        @Override
        public android.view.View createView(Context context) {
            bannerView = LayoutInflater.from(context).inflate(R.layout.view_banner, null);
            iv_banner = (ImageView) bannerView.findViewById(R.id.iv_banner);
            tv_banner_title = (TextView) bannerView.findViewById(R.id.tv_banner_title);

            return bannerView;
        }

        @Override
        public void UpdateUI(Context context, final int position, Banner banner) {
            Glide.with(context)
                    .load(banner.getPicUrl().trim())
                    .into(iv_banner);

            tv_banner_title.setText(banner.getTitle());
        }
    }
}