package com.kfzs.duanduan.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
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.widget.ImageView;
import android.widget.TextView;

import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadTask;
import com.kfzs.android.view.tag.FlowLayout;
import com.kfzs.android.view.tag.TagAdapter;
import com.kfzs.android.view.tag.TagFlowLayout;
import com.kfzs.duanduan.BaseCompatFragment;
import com.kfzs.duanduan.services.DownloadTaskService;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.FindApp;
import com.sheep.gamegroup.model.entity.FindItem;
import com.sheep.gamegroup.model.entity.FindTag;
import com.sheep.gamegroup.model.entity.HomeListEntity;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.SysAppUtil;
import com.sheep.gamegroup.util.ViewHolder;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.adapter.AdbCommonRecycler;
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 org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

import static android.content.Intent.ACTION_PACKAGE_ADDED;
import static android.content.Intent.ACTION_PACKAGE_REMOVED;
import static com.sheep.gamegroup.util.UMConfigUtils.Event.FIND_ITEM;

/**
 * Created by realicing on 2018/6/27.
 * realicing@sina.com
 */
public class FgtFindChild extends BaseCompatFragment {

    private int type;
    public static FgtFindChild newInstance(int type){
        FgtFindChild fgt = new FgtFindChild();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        fgt.setArguments(bundle);
        return fgt;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if(bundle != null){
            type = bundle.getInt("type", 0);
        }
        EventBus.getDefault().register(this);
        Aria.download(this).register();
    }

    private Activity activity;
    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.net_empty_fresh_list);
        activity = getActivity();
        ButterKnife.bind(this, mContentView);
        initView();
        initData();
    }

    @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 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<FindItem>(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.find_item;
            }

            @Override
            public void convert(ViewHolder holder, final FindItem 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 find_item_name = (TextView)rootConvertView.findViewById(R.id.find_item_name);
                TextView find_item_time = (TextView)rootConvertView.findViewById(R.id.find_item_time);
                ImageView find_item_iv = (ImageView)rootConvertView.findViewById(R.id.find_item_iv);
                TextView find_item_des = (TextView)rootConvertView.findViewById(R.id.find_item_des);
//                TextView find_item_pf_label = (TextView)rootConvertView.findViewById(R.id.find_item_pf_label);
                TextView find_item_download = (TextView)rootConvertView.findViewById(R.id.find_item_download);
                TagFlowLayout find_item_tags = (TagFlowLayout)rootConvertView.findViewById(R.id.find_item_tags);

                if(item.isGame()){
                    find_item_download.setVisibility(View.VISIBLE);
                    FindApp findApp = item.getApplication();
//                    find_item_pf_label.setVisibility(View.VISIBLE);
//                    find_item_pf_label.setText(Html.fromHtml(String.format(Locale.CHINA, "评分：<font color='%s'>%.1f</font>分", "#29d6fd", findApp.getScore())));
                    updateView(activity, findApp, find_item_download);
                } else {
                    find_item_download.setVisibility(View.GONE);
//                    find_item_pf_label.setVisibility(View.GONE);
                }
                ViewUtil.setText(find_item_name, item.getTitle());
                ViewUtil.setTextTime(find_item_time, item.getCreated_at(), "yyyy-MM-dd");
                ViewUtil.setImage(find_item_iv, item.getPictures());
                ViewUtil.setText(find_item_des, item.getDes());
                item.removeNullTag();
                if(ListUtil.isEmpty(item.getTages())){
                    find_item_tags.setVisibility(View.GONE);
                } else {
                    find_item_tags.setVisibility(View.VISIBLE);
                    TagAdapter adapter = new TagAdapter<FindTag>(item.getTages()) {
                        @Override
                        public View getView(FlowLayout parent, int position, FindTag item) {
                            TextView tv = (TextView) LayoutInflater.from(activity).inflate(R.layout.find_item_tag, parent, false);
                            ViewUtil.setText(tv, item.getName());
                            return tv;
                        }
                    };
                    find_item_tags.setAdapter(adapter);
                }

                rootConvertView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        onClickItem(item);
                    }
                });
            }
        });
    }

    /**
     * 点击一个发现元素
     * @param item
     */
    private void onClickItem(FindItem item) {
        if(item != null){
            switch (item.getType()){//类型 1：游戏 2：咨询 3：转跳 4：任务 5：栏目
                case 1:
                    Jump2View.getInstance().goFindGame(activity, item);
                    break;
                case 2:
                    Jump2View.getInstance().goFindInformation(activity, item);
                    break;
                case 3:
                    openLink(item);
                    break;
                case 4:
                    Jump2View.getInstance().goTaskDetailView(activity, item.getRelease_task_id());
                    break;
                case 5:
                    openHomeListItem(item);
                    break;
            }
            FIND_ITEM.onEvent("find_id", item.getId());
            SheepApp.getInstance().getNetComponent().getApiService().getFindItemAddClicks(item.getId())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                            @Override
                            public void onNext(BaseMessage baseMessage) {
                            }

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

    /**
     * 打开一个homelist项
     * @param item
     */
    private void openHomeListItem(FindItem item) {
        SheepApp.getInstance().getNetComponent().getApiService().getHomeListItem(item.getHome_list_id())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                            @Override
                            public void onNext(BaseMessage baseMessage) {
                                HomeListEntity homeListEntity = baseMessage.getData(HomeListEntity.class);
                                if(homeListEntity == null){
                                    G.showToast(R.string.error_data);
                                    return;
                                }
                                CommonUtil.getInstance().goWhere(activity, homeListEntity, "发现");
                            }

                            @Override
                            public void onError(BaseMessage baseMessage) {
                                G.showToast(baseMessage);
                            }
                        });
    }

    /**
     * 打开一个链接
     * @param item
     */
    private void openLink(FindItem item) {
        if(TextUtils.isEmpty(item.getUrl())){
            G.showToast(R.string.error_link);
            return;
        }
        switch (item.getIs_in_url()){//是否外部链接 1：是 0：不是
            case 1:
                Jump2View.getInstance().goWeb(activity, item.getUrl());
                break;
            default:
                Jump2View.getInstance().goWeb(activity, item.getUrl(), item.getTitle());
                break;
        }
    }

    public void initData(){
        //先尝试获取缓存数据
        List<FindItem> newList = DataUtil.getInstance().getCacheList(ApiKey.articles(type), FindItem.class);
        loadList(newList);
        refreshData();
    }

    public void refreshData(){
        empty_view.setVisibility(View.INVISIBLE);
        SysAppUtil.checkNet(new Action1<Integer>() {
            @Override
            public void call(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().getFindList(1, 100, type)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                            @Override
                            public void onNext(BaseMessage baseMessage) {
                                boolean isNewData = DataUtil.getInstance().isNewData(ApiKey.articles(type));
                                if(isNewData) {
                                    List<FindItem> newList = baseMessage.getDatas(FindItem.class);
                                    loadList(newList);
                                }
                            }

                            @Override
                            public void onError(BaseMessage baseMessage) {
                                notifyDataSetChanged();
                            }
                        });
    }
    private void loadList(List<FindItem> 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();
    }
    private List<FindItem> list = ListUtil.emptyList();



    private Map<String, FindApp> findAppMap = new HashMap<>();
    //获取任务对应的findApp
    private FindApp getFindAppByKey(String key) {
        if(findAppMap.containsKey(key))
            return findAppMap.get(key);
        return null;
    }
    private Map<String, TextView> downLoadTextViewMap = new HashMap<>();
    //获取任务对应的TextView来更新进度
    private TextView getTextViewByTask(DownloadTask task) {
        return getTextViewByKey(task.getKey());
    }
    private TextView getTextViewByKey(String key) {
        if(downLoadTextViewMap.containsKey(key))
            return downLoadTextViewMap.get(key);
        return null;
    }

    //更新按钮状态与添加点击事件
    private void updateView(Activity activity, FindApp findApp, TextView textView) {
        if(findApp.isCanDonload()){//可下载
            downLoadTextViewMap.put(findApp.getDownload_link(), textView);
            downLoadTextViewMap.put(findApp.getPackage_name(), textView);
            findAppMap.put(findApp.getDownload_link(),findApp);
            findAppMap.put(findApp.getPackage_name(), findApp);
            findApp.getFindAppHelper().updateDownloadTaskView(activity, findApp, textView);
        } else {//预约下载
            findApp.getFindAppHelper().updateReservationView(activity, findApp, textView);
        }
    }
    //下载状态监听

    @Download.onPre void onPre(DownloadTask task) {
        TextView textView = getTextViewByTask(task);
        if(textView != null) {
            textView.setText("准备下载中");
        }
    }

    @Download.onTaskStart void taskStart(DownloadTask task) {
        TextView textView = getTextViewByTask(task);
        if(textView != null) {
            textView.setText("开始下载中");
        }
    }
    @Download.onTaskResume void taskResume(DownloadTask task) {
        TextView textView = getTextViewByTask(task);
        if(textView != null) {
            textView.setText("恢复下载中");
        }
    }
    //在这里处理任务执行中的状态，如进度进度条的刷新
    @Download.onTaskRunning protected void running(DownloadTask task) {
        TextView textView = getTextViewByTask(task);
        if(textView != null) {
            textView.setText(String.format(Locale.CHINA, "%d%%", Math.abs(task.getPercent())));
        }
    }

    @Download.onTaskStop void taskStop(DownloadTask task) {
        TextView textView = getTextViewByTask(task);
        if(textView != null) {
            textView.setText(CommonUtil.CONTINUE_DOWNLOAD);
        }
    }

    @Download.onNoSupportBreakPoint void onNoSupportBreakPoint(DownloadTask task) {
    }

    @Download.onTaskCancel void taskCancel(DownloadTask task) {
        TextView textView = getTextViewByTask(task);
        if(textView != null) {
            textView.setText("已经取消");
        }
    }

    @Download.onTaskFail void taskFail(DownloadTask task) {
        TextView textView = getTextViewByTask(task);
        if(textView != null) {
            textView.setText(CommonUtil.FAIL_DOWNLOAD);
        }
    }

    @Download.onTaskComplete void taskComplete(DownloadTask task) {
        TextView textView = getTextViewByTask(task);
        if(textView != null) {
            textView.setText(CommonUtil.START_INSTALL);
        }
        FindApp findApp = getFindAppByKey(task.getKey());
        if(findApp != null) {
            findApp.updateState(DownloadTaskService.STATUS_FINISH);
        }
    }

    @Subscribe
    public void onEventMainThread(Intent intent) {
        if(intent != null && intent.getAction() != null && intent.getDataString() != null && intent.getDataString().contains("package:")){
            String packageName = intent.getDataString().replace("package:","");

            TextView textView = getTextViewByKey(packageName);
            if(textView != null) {
                switch (intent.getAction()){
                    case ACTION_PACKAGE_ADDED:
                        textView.setText(CommonUtil.GAME_OPEN);
                        break;
                    case ACTION_PACKAGE_REMOVED:
                        String path = PackageUtil.isExistsFile(packageName);
                        if(TextUtils.isEmpty(path)) {
                            textView.setText(CommonUtil.START_DOWNLOAD);
                        } else {
                            textView.setText(CommonUtil.START_INSTALL);
                        }
                        break;
                }
            }

            FindApp findApp = getFindAppByKey(packageName);
            if(findApp != null) {
                switch (intent.getAction()){
                    case ACTION_PACKAGE_ADDED:
                        findApp.updateState(DownloadTaskService.STATUS_INSTALLED);
                        break;
                    case ACTION_PACKAGE_REMOVED:
                        String path = PackageUtil.isExistsFile(packageName);
                        if(TextUtils.isEmpty(path)) {
                            findApp.updateState(DownloadTaskService.STATUS_INIT);
                        } else {
                            findApp.updateState(DownloadTaskService.STATUS_FINISH);
                        }
                        break;
                }
            }
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        Aria.download(this).unRegister();
    }
}
