package com.wasu.cs.mvp.presenter;

import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.SparseArray;

import com.wasu.authsdk.AuthListener;
import com.wasu.authsdk.AuthSDK;
import com.wasu.authsdk.entity.PriceInfo;
import com.wasu.common.WError;
import com.wasu.cs.model.ChildrenData;
import com.wasu.cs.model.DemandProgram;
import com.wasu.cs.model.DetailSeriesSet;
import com.wasu.cs.module.WasuCacheModule;
import com.wasu.cs.mvp.IView.IChildrenSongView;
import com.wasu.cs.utils.JsonUtil;
import com.wasu.module.datafetch.DataFetchListener;
import com.wasu.module.datafetch.DataFetchModule;
import com.wasu.module.datafetch.ObjectBase;
import com.wasu.module.db.DBManage;
import com.wasu.module.log.WLog;

import java.util.HashMap;
import java.util.Map;

import basic.BuilderTypeManager.BuildType;
import basic.db.model.DBProgramHistory;
import cn.com.wasu.main.BuildConfig;
import cn.com.wasu.main.ChannelFlavor;
import cn.com.wasu.main.Common;

/**
 * Created by jeepc on 2016/10/24.
 */

public class ChildrenSongPresenter {

    public static final int NOFREE = 1;
    public static final int FREE = 0;
    private static final String TAG = "jeepc";

    private IChildrenSongView view;
    private ChildrenData mData;
    private SparseArray mPriceMap = new SparseArray();
    private int fetchDataRetryCount = 3;

    public void attachView(IChildrenSongView view) {
        this.view = view;
    }

    public void detachView() {
        if (view != null) {
            view = null;
        }
    }

    boolean isLeTv = BuildConfig.FLAVOR.equalsIgnoreCase(ChannelFlavor.LETV_MARKET);
    String jsonUrl = BuildType.HTTP_DOMAIN + "?s=" + BuildType.SITE_ID
            + (isLeTv ? "|" + BuildType.ChannelId:"")
            + "&p=sntAssetDetail&k=1&v=1&catId=221793&assetId=2902091"
            + (isLeTv ? "&c=" + BuildType.ChannelId : "");
    String json = "{code:200,data: {bgPicUrl:\"\",list: [" +
            "{fee:0,catId:\"221793\",id:\"2902091\",jsonUrl: " + jsonUrl + ",layout: \"Detail_Series\",picUrl: \"https://s-cms.wasu.tv/pic/wsimage/2016/11/16/107/107/20161116164834888ab14c336.jpg\"," +
            "title: \"那年那兔那些事儿第三季\"}," +
            "{fee:0,catId: 221793,id: 817879,jsonUrl: " + jsonUrl + ",layout: \"Detail_Series\"," +
            "picUrl: \"https://s-cms.wasu.tv/pic/wsimage/2016/11/11/101/101/20161111105955275060a6886.jpg\",title: \"斗龙战士2\" }]},message: \"请求成功\"}";


    String url;

    public void loadData(String jsonUrl) {
        this.url = jsonUrl;
        if (view != null) {
            view.showLoading();
        }
        DataFetchModule.getInstance().fetchObjectGet(url, ChildrenData.class, new DataFetchListener.ObjectListener() {

            @Override
            public void onObjectGet(int retcode, String extraMsg, ObjectBase data) {
                if (retcode == WError.ERROR_NONE) {
                    mData = (ChildrenData) data;
                    if (view != null && !view.uiIsFinishing()) {
                        view.hideLoading();
                        view.onDataLoaded(mData);
                    }
                } else {
                    if (view != null && !view.uiIsFinishing()) {
                        view.hideLoading();
                        view.showErrorExitDlg();
                    }
                }
            }
        });
    }

    public boolean isFree(PriceInfo priceInfo) {
        if (priceInfo.mPrice <= 0 || priceInfo.mOriginalPrice <= 0) {
            return true;
        }
        return false;
    }


    int curPos = -1;
    boolean curIsFree = false;

    /**
     * @param position
     * @param isFirst 是否是首次播放，首次播放跳过付费资产
     */
    public void queryPriceToPlay(final int position, final boolean isFirst) {
        curPos = position;
        if (mPriceMap.get(position) != null) {
            if ((int) mPriceMap.get(position) == FREE) {
                // view.playVideo(position,true);
                loadAssetDetail(mData.getList().get(position).getJsonUrl(),position);
            } else {
                if (!isFirst) {
                    //view.playVideo(position,false);
                    loadAssetDetail(mData.getList().get(position).getJsonUrl(),position);
                } else {
                    if(view!=null&&!view.uiIsFinishing()){
                        view.playNextVideo();
                    }
                }
            }
            return;
        }
        final ChildrenData.ListBean bean = mData.getList().get(position);
        /** 询价 **/
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("resourceId", bean.getId());
        params.put("resourceName", bean.getTitle());
        params.put("orderType", 0);
        AuthSDK.getInstance().queryPrice(params, new AuthListener() {
            @Override
            public void result(int ret, String extra, Object retData) {
                if (ret == WError.ERROR_NONE) {//询价成功
                    PriceInfo priceInfo = (PriceInfo) retData;
                    if (isFree(priceInfo)) {
                        // view.playVideo(position,true);
                        loadAssetDetail(bean.getJsonUrl(),position);
                        mPriceMap.put(curPos, FREE);
                        if (bean.getFee() != FREE) {
                            if (view != null && !view.uiIsFinishing()) {
                                view.onPriceChange(curPos, FREE);
                            }
                        }
                    } else {
                        if (!isFirst) {
                            // view.playVideo(position,false);
                            loadAssetDetail(bean.getJsonUrl(),position);
                        } else {
                            if(view!=null&&!view.uiIsFinishing()){
                                view.playNextVideo();
                            }
                        }
                        if (bean.getFee() != NOFREE) {
                            if (view != null && !view.uiIsFinishing()) {
                                view.onPriceChange(curPos, NOFREE);
                            }
                        }
                        mPriceMap.put(curPos, NOFREE);

                    }
                } else {// 询价失败
                    if(view!=null&&!view.uiIsFinishing()){
                        view.playNextVideo();
                    }
                }
            }
        });
    }

    DemandProgram mDemandInfo;

    /**
     * 根据url请求详情页数据
     **/
    public void loadAssetDetail(String programUrl,int pos) {
        String strData = WasuCacheModule.getInstance().getAsString(programUrl);
        //判断是否有缓存
        if (strData != null && !strData.isEmpty()) {
            mDemandInfo = JsonUtil.fromJson(strData, DemandProgram.class);
            initDetailData(pos);
            simpleLoadDetailData(programUrl, true,pos);
        } else {
            simpleLoadDetailData(programUrl, false,pos);
        }
    }

    private void initDetailData(int pos) {
        if (mDemandInfo.getAssetType() == DemandProgram.SHOWTYPE_TV_SERIES) {//如果是电视剧则请求集数个数
            loadSeriesSet(mDemandInfo.getOnlineEpisodesUrl());
        }
        if (mDemandInfo.getNowItem() < 1) {// 没有更新的资产
            //view.fatalError("资产已下线");
            return;
        }
        readHistory();
        if (view != null && !view.uiIsFinishing()) {
            view.playVideo(mDemandInfo, pos);
        }
    }

    private int fetchSeriesSetRetryCount = 3;

    public synchronized void loadSeriesSet(final String url) {
        final DataFetchListener.ObjectListener objectListener = new DataFetchListener.ObjectListener() {

            @Override
            public void onObjectGet(int retcode, String extraMsg,
                                    ObjectBase data) {
                if (view.uiIsFinishing()) {
                    return;
                }
                //1.请求成功则引用到详情页数据中，返回
                if (retcode == WError.ERROR_NONE) {
                    DetailSeriesSet mDetailSeriesSet = (DetailSeriesSet) data;
                    if (mDetailSeriesSet != null)
                        mDemandInfo.setDetailSeriesSet(mDetailSeriesSet);
                    //恢复重试次数
                    fetchSeriesSetRetryCount = 3;
                    return;
                } else {//2.失败，重新请求3次
                    if (fetchSeriesSetRetryCount > 0) {
                        DataFetchModule.getInstance().fetchObjectGet(url, DetailSeriesSet.class, this);
                        fetchSeriesSetRetryCount--;
                        return;
                    }
                }
                //3.失败3次，打印log 返回
                if (fetchSeriesSetRetryCount <= 0) {
                    WLog.e(TAG, "fetchSeriesSet failed reach 3 times");
                }
            }
        };
        DataFetchModule.getInstance().fetchObjectGet(url,
                DetailSeriesSet.class, objectListener);
    }

    public void readHistory() {
        if (mDemandInfo == null || TextUtils.isEmpty(mDemandInfo.getId()))
            return;
        try {
            DBProgramHistory mHistory = DBManage.queryBy(DBProgramHistory.class, "programId", mDemandInfo.getId());

            if (mHistory != null) {
                mDemandInfo.setCurPlayIndex(mHistory.lastSeries);
            } else {
                if (mDemandInfo.getDetailSeriesSet() != null && mDemandInfo.getDetailSeriesSet().getSerieslist().size() > 0) {
                    mDemandInfo.setCurPlayIndex(mDemandInfo.getDetailSeriesSet().getSerieslist().get(0));
                } else {
                    mDemandInfo.setCurPlayIndex(mDemandInfo.getMinEpisode());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据url请求详情页数据
     *
     * @param programUrl 请求地址
     * @param hasCache   请求前是否有缓存
     **/
    private void simpleLoadDetailData(final String programUrl, final boolean hasCache, final int pos) {
        final String url = programUrl + "&page=" + 1 + "&psize=" + 30;
        DataFetchListener.ObjectListener objectListener = new DataFetchListener.ObjectListener() {

            @Override
            public void onObjectGet(int retcode, String extraMsg, ObjectBase data) {
                if (retcode == WError.ERROR_INVALID_DATA || retcode == WError.ERROR_NET) {//网络错误重试
                    if (fetchDataRetryCount > 0) {
                        DataFetchModule.getInstance().fetchObjectGet(url, DemandProgram.class, this);
                        fetchDataRetryCount--;
                        return;
                    }
                }
                if (retcode != WError.ERROR_NONE) {
                        //view.loadAssetDetailFailed(retcode, extraMsg);
                        return;
                }
                if (view == null || view.uiIsFinishing()) {
                    return;
                }
                fetchDataRetryCount = 3;
                mDemandInfo = (DemandProgram) data;
                mDemandInfo.setDetailUrl(programUrl);
                if (hasCache) {
                    WasuCacheModule.getInstance().remove(url);
                } else {
                    initDetailData(pos);
                }
                WasuCacheModule.getInstance().put(url, JsonUtil.toJson(data));
            }
        };
        DataFetchModule.getInstance().fetchObjectGet(url, DemandProgram.class, objectListener);

    }


}
