package com.sheep.gamegroup.view.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
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.sheep.gamegroup.absBase.AbsObserver;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.RouserArticlesEntity;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.GlideImageLoader;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.MyGridview;
import com.sheep.gamegroup.util.SysAppUtil;
import com.sheep.gamegroup.util.ViewHolder;
import com.sheep.gamegroup.view.adapter.AdbCommonRecycler;
import com.sheep.gamegroup.view.adapter.ArrayAdapter;
import com.sheep.jiuyan.samllsheep.BuildConfig;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.base.BaseFragment;
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.List;

import butterknife.BindView;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.iwf.photopicker.PhotoPreview;

/**
 * 唤醒
 * Created by ljy on 2018/8/22.
 */

public class FgtRouser extends BaseFragment {

    @BindView(R.id.title)
    View title;
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    @BindView(R.id.empty_view)
    View empty_view;
    @BindView(R.id.check_net_ll)
    View check_net_ll;
    @BindView(R.id.view_list)
    RecyclerView view_list;

    private Activity activity;
    private List<RouserArticlesEntity> list = ListUtil.emptyList();
    @Override
    public int getLayoutId() {
        return R.layout.net_empty_fresh_list;
    }

    @Override
    public void onViewCreated() {
        activity = getActivity();
        initView();
        initData();
    }
    Unbinder unbinder;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        return rootView;
    }
    private void initView(){
        title.setVisibility(View.GONE);
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshData();
                refresh.setRefreshing(false);
            }
        });

        view_list.setLayoutManager(new LinearLayoutManager(SheepApp.getInstance()));
        view_list.setAdapter(new AdbCommonRecycler<RouserArticlesEntity>(SheepApp.getInstance(), list){

            @Override
            public int getItemViewType(int position) {
                return position;
            }
            @Override
            public int getViewIdByType(int type) {//type来源于 getItemViewType 返回的值
                if(type == -1 + list.size()){
                    return R.layout.find_item_bottom;
                }
                return R.layout.rouser_item;
            }

            @Override
            public void convert(final ViewHolder holder, final RouserArticlesEntity item) {
                if(item == null){
                    return;
                }
                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);
                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;
                }

                item_name.setText(item.getTitle()+"");
                time_tv.setText(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 {
                            boolean isInstalled = PackageUtil.isAppInstalled(SheepApp.getInstance(), item.getPackage_name());
                            if(!isInstalled && !BuildConfig.DEBUG){
                                G.showToast("还未安装"+item.getApp_name());
                                return;
                            }

                            String deeplink = item.getDeeplink()+"";
                            if(BuildConfig.DEBUG && TextUtils.isEmpty(deeplink)){
                                deeplink = "snssdk143://detail?groupid=6584333623434936835&gd_label=click_schema_hxhg15";
                            }
                            Intent intent = Intent.parseUri(deeplink, Intent.URI_INTENT_SCHEME);

                            intent.setComponent(null);
                            startActivity(intent);
                            CommonUtil.getInstance().awakenDetail(item);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }
    public void initData(){
        //先尝试获取缓存数据
        List<RouserArticlesEntity> newList = DataUtil.getInstance().getCacheList(ApiKey.awakenApp(), RouserArticlesEntity.class);
        loadList(newList);
        refreshData();
    }
    public void refreshData(){
        empty_view.setVisibility(View.INVISIBLE);
        SysAppUtil.checkNet(new AbsObserver<Integer>() {
            @Override
            public void onNext(Integer result) {
                if(result != 0){//无网络
                    if(check_net_ll != null)
                        check_net_ll.setVisibility(View.VISIBLE);
                } else {
                    if(check_net_ll != null)
                        check_net_ll.setVisibility(View.GONE);
                }
            }
        });
        SheepApp.getInstance().getNetComponent().getApiService().awakenApparticle(1, 100)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        boolean isNewData = DataUtil.getInstance().isNewData(ApiKey.awakenApp());
                        if(isNewData) {
                            List<RouserArticlesEntity> newList = baseMessage.getDatas(RouserArticlesEntity.class);
                            List<RouserArticlesEntity> newLists = new ArrayList<>();
                            newLists.clear();
                            for(RouserArticlesEntity r: newList){
                                boolean isInstalled = PackageUtil.isAppInstalled(SheepApp.getInstance(), r.getPackage_name());
                                if(isInstalled){
                                    newLists.add(r);
                                }
                            }
                            loadList(newLists);
                        }
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        notifyDataSetChanged();
                    }
                });
    }

    private void loadList(List<RouserArticlesEntity> newList){
        if(!ListUtil.isEmpty(newList)){
            list.clear();
            ListUtil.addAll(list, newList);
            if(!list.isEmpty())
                list.add(null);//底部部分----我是有底线的
        }
        notifyDataSetChanged();
    }

    private void notifyDataSetChanged(){
        CommonUtil.getInstance().updateEmptyView(empty_view, list.isEmpty());
        refresh.setRefreshing(false);
        view_list.getAdapter().notifyDataSetChanged();
    }

}
