package com.sheep.gamegroup.view.fragment;

import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.kfzs.appstore.utils.adapter.recyclerview.RecyclerViewAdapter;
import com.kfzs.appstore.utils.adapter.recyclerview.ViewHolder;
import com.sheep.gamegroup.model.api.ApiService;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.RouserArticlesEntity;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.GlideImageLoader;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.MyGridview;
import com.sheep.gamegroup.util.TestUtil;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.adapter.ArrayAdapter;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.PackageUtil;

import org.afinal.simplecache.ApiKey;

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

import me.iwf.photopicker.PhotoPreview;
import io.reactivex.Observable;

/**
 * Created by realicing on 2018/04/.
 * realicing@sina.com
 * 看点
 */
public class FgtWatchFocus extends BaseListFragment2<RouserArticlesEntity> {

    @Override
    protected RecyclerView.Adapter getAdapter() {
        return new RecyclerViewAdapter<RouserArticlesEntity>(SheepApp.getInstance(), R.layout.rouser_item, onlyShowInstalledApp ? showList : list) {

            @Override
            public void convert(final ViewHolder holder, final RouserArticlesEntity item, int position) {
                View rootConvertView = holder.itemView;
                View padding = rootConvertView.findViewById(R.id.padding);
                padding.setVisibility(holder.getAdapterPosition() == 0 ? View.GONE : View.VISIBLE);
                TextView gridview_item_tag_tv = (TextView) rootConvertView.findViewById(R.id.gridview_item_tag_tv);
                final TextView item_name = (TextView) rootConvertView.findViewById(R.id.rouser_item_name);
                TextView time_tv = (TextView) rootConvertView.findViewById(R.id.time_tv);
                ImageView one_img_iv = (ImageView) rootConvertView.findViewById(R.id.one_img_iv);
                if (item == null) {
                    rootConvertView.setVisibility(View.GONE);
                    return;
                }
                rootConvertView.setVisibility(View.VISIBLE);
                MyGridview home_list_gridview_gv = (MyGridview) rootConvertView.findViewById(R.id.home_list_gridview_gv);
                switch (item.getIdentifier()) {
                    default:
                        gridview_item_tag_tv.setVisibility(View.GONE);
                        break;
                    case 2:
                        gridview_item_tag_tv.setVisibility(View.VISIBLE);
                        gridview_item_tag_tv.setText("火热");
                        gridview_item_tag_tv.setBackgroundResource(R.drawable.shape_red_stroke_rectangle_10_radius);
                        gridview_item_tag_tv.setTextColor(activity.getResources().getColor(R.color.red_FD2D54));
                        break;
                    case 3:
                        gridview_item_tag_tv.setVisibility(View.VISIBLE);
                        gridview_item_tag_tv.setText("最新");
                        gridview_item_tag_tv.setBackgroundResource(R.drawable.shape_blue_stroke_rectangle_10_radius);
                        gridview_item_tag_tv.setTextColor(activity.getResources().getColor(R.color.btn_color_main_stroke));
                        break;
                }
                ViewUtil.setText(item_name, item.getTitle());
                ViewUtil.setText(time_tv, item.getContent());
                if (!TextUtils.isEmpty(item.getImg())) {
                    final String[] images = item.getImg().split(";");
                    String[] images1 = new String[3];
                    if (images.length > 1) {
                        if (images.length > 3) {
                            for (int i = 0; i < 3; i++) {
                                images1[i] = images[i];
                            }
                        } else {
                            images1 = new String[images.length];
                            for (int i = 0; i < images.length; i++) {
                                images1[i] = images[i];
                            }
                        }
                        one_img_iv.setVisibility(View.GONE);
                        home_list_gridview_gv.setVisibility(View.VISIBLE);
                        home_list_gridview_gv.setAdapter(new ArrayAdapter<String>(activity, R.layout.rouser_image_adp, images1) {
                            @Override
                            public boolean convert(int position, View convertView, ViewGroup parent, String item) {
                                ImageView imageView = convertView.findViewById(R.id.item_image_iv);
                                Glide.with(activity)
                                        .load(item + "")
                                        .apply(new RequestOptions().dontAnimate().override(G.WIDTH / 3, G.WIDTH / 3))
                                        .into(imageView);
                                return true;
                            }
                        });
                        final String[] finalImages = images1;
                        home_list_gridview_gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                try {
                                    PhotoPreview.builder()
                                            .setPhotos(new ArrayList<>(Arrays.asList(finalImages)))
                                            .setCurrentItem(position)
                                            .setShowDeleteButton(false)
                                            .start(activity, 101);

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    } else {
                        one_img_iv.setVisibility(View.VISIBLE);
                        home_list_gridview_gv.setVisibility(View.GONE);
                        GlideImageLoader.setImage(one_img_iv, images[0]);
                        one_img_iv.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                try {
                                    PhotoPreview.builder()
                                            .setPhotos(new ArrayList<>(Arrays.asList(images)))
                                            .setCurrentItem(holder.getAdapterPosition())
                                            .setShowDeleteButton(false)
                                            .start(activity, 101);

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }

                } else {
                    one_img_iv.setVisibility(View.GONE);
                    home_list_gridview_gv.setVisibility(View.GONE);
                }


                //snssdk143://detail?groupid=6584333623434936835&gd_label=click_schema_hxhg15
                rootConvertView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        try {
                            String deepLink = item.getDeeplink().trim();
                            Intent intent = Intent.parseUri(deepLink, Intent.URI_INTENT_SCHEME);
                            intent.setComponent(null);
                            startActivity(intent);
                            CommonUtil.getInstance().awakenDetail(item);
                        } catch (Exception e) {
                            e.printStackTrace();
                            if(TestUtil.isTest())
                                G.showToast(e.getMessage());
                            else
                                G.showToast(activity.getString(R.string.not_install, item.getApp_name()));
                        }
                    }
                });
            }
        };
    }

    @Override
    protected String getKey(int page, int per_page) {
        return ApiKey.awakenArticle(page, per_page);
    }

    @Override
    protected Observable<BaseMessage> getApi(ApiService apiService) {
        return apiService.awakenApparticle(page, per_page);
    }

    @Override
    protected Class<RouserArticlesEntity> getTClass() {
        return RouserArticlesEntity.class;
    }
    //只显示已经安装的应用(没有包名的错误数据也不显示)
    private boolean onlyShowInstalledApp = true;
    //key表示包名，value代表是否安装
    private Map<String, ArrayList<RouserArticlesEntity>> map = new HashMap<>();
    //要显示的内容
    protected List<RouserArticlesEntity> showList = ListUtil.emptyList();

    @Override
    protected boolean isFirstGetACache() {
        return !onlyShowInstalledApp;//不显示未安装应用时不获取缓存数据
    }

    @Override
    public void clear() {
        super.clear();
        if(onlyShowInstalledApp) {
            showList.clear();
            map.clear();
        }
    }

    @Override
    protected void updateEmptyView(){
        if(onlyShowInstalledApp) {
            if(newList != null) {
                for (RouserArticlesEntity item : newList) {
                    if (!TextUtils.isEmpty(item.getPackage_name())) {
                        ArrayList<RouserArticlesEntity> entityList;
                        if (map.containsKey(item.getPackage_name())) {
                            entityList = map.get(item.getPackage_name());
                        } else {
                            entityList = new ArrayList<>();
                            map.put(item.getPackage_name(), entityList);
                        }
                        entityList.add(item);
                    }
                }
            }
            showList.clear();
            for (String packageName : map.keySet()) {
                boolean isAppInstalled = PackageUtil.isAppInstalled(activity, packageName);
                if(isAppInstalled){
                    showList.addAll(map.get(packageName));
                }
            }
            CommonUtil.getInstance().updateEmptyView(empty_view, showList.isEmpty());
        } else {
            super.updateEmptyView();
        }
    }
    @Override
    public void notifyData() {
        if(onlyShowInstalledApp && showList.isEmpty() && !list.isEmpty()){//只显示安装的应用情况下，可能显示的数据为空，但是实际数据却很多，这时要直接进行下一页的获取，否则无法翻页
            loadMoreData();
        }
    }
}
