package com.wasu.cs.mvp.presenter;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;

import com.wasu.authsdk.AuthListener;
import com.wasu.authsdk.AuthSDK;
import com.wasu.authsdk.IAuthInterface;
import com.wasu.authsdk.entity.PriceInfo;
import com.wasu.common.WError;
import com.wasu.comp.ad.AdView;
import com.wasu.comp.ad.WasuAdEngine;
import com.wasu.cs.model.DemandProgram;
import com.wasu.cs.model.DemandRecommand;
import com.wasu.cs.model.DetailSeriesSet;
import com.wasu.cs.module.ChildFavModule;
import com.wasu.cs.module.FavAndHisModule;
import com.wasu.cs.module.WasuCacheModule;
import com.wasu.cs.mvp.IView.DetailView;
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 com.wasu.statistics.PlayInfo;
import com.wasu.statistics.WasuStatistics;

import org.json.JSONObject;

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

import basic.BuilderTypeManager.BuildType;
import basic.db.model.DBProgramChildFavorite;
import basic.db.model.DBProgramFavorite;
import basic.db.model.DBProgramHistory;
import cn.com.wasu.main.R;

/**
 * Created by hudong on 16-6-30.
 */
public class DetailLogic {
    private static final String TAG = "DetailLogic";
    private DetailView view;
    private DemandProgram mDemandInfo;
    private DemandRecommand demandRecommand;
    public static final String ACTION_PROGRAM = "com.wasuali.action.programinfo";
    public static final String ACTION_FAVORITE_TCL = "com.wasu.tcl.history";
    /**
     * 网络数据请求重试次数
     **/
    private int fetchDataRetryCount = 3;
    private int fetchSeriesSetRetryCount = 3;
    private final int RECOMMEND_MAXNUM = 10;
    private String traceid = "";
    public int adFree = -1;
    /**
     * 历史
     **/
    private DBProgramHistory mHistory;
    Context context;

    public DetailLogic(DetailView view) {
        this.view = view;
    }

    public void attachView(DetailView view) {
        this.view = view;

    }

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

    /**
     * 根据url请求详情页数据
     *
     * @param programUrl 请求地址
     * @param hasCache   请求前是否有缓存
     **/
    private void simpleLoadDetailData(final String programUrl, final boolean hasCache) {
        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) {
                    if(view != null)
                    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();
                }
                WasuCacheModule.getInstance().put(url, JsonUtil.toJson(data));
            }
        };
        DataFetchModule.getInstance().fetchObjectGet(url, DemandProgram.class, objectListener);

    }

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

    protected void addDataToStatistics(DemandProgram mDemandInfo2) {
        if (mDemandInfo2 == null) {
            WLog.i(TAG, "addDataToStatistics mDemandInfo2=" + mDemandInfo2);
            return;
        }
        WasuStatistics.getInstance().addPageElem(
                new PlayInfo(mDemandInfo2.getId(), mDemandInfo2.getTitle(), "",
                        "", mDemandInfo2.getPpv(), BuildType.SITE_ID, traceid,
                        mDemandInfo2.getPriceInfo().getPrice() + "", mDemandInfo2
                        .getAssetTypeText(), "-1"));
    }

    public void readHistory() {
        if (mDemandInfo == null || TextUtils.isEmpty(mDemandInfo.getId()))
            return;
        try {
            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();
        }
    }

    private void initDetailData() {
        if (mDemandInfo.getAssetType() == DemandProgram.SHOWTYPE_TV_SERIES) {//如果是电视剧则请求集数个数
            loadSeriesSet(mDemandInfo.getOnlineEpisodesUrl());
        }
        if (mDemandInfo.getNowItem() < 1) {// 没有更新的资产
            view.fatalError("资产已下线");
            return;
        }
        //更新收藏UI
        view.updateFavoriteUi(FavAndHisModule.getInstance().hasFavorite(mDemandInfo.getId()));
        readHistory();
        view.loadAssetDetailSuccess(mDemandInfo);
        addDataToStatistics(mDemandInfo);
        WasuStatistics.getInstance().BigDatadetailView(mDemandInfo.getId(), traceid);
    }

    public synchronized void loadSeriesSet(final String url) {
        WLog.i(TAG, "detail seriesSet url=" + url);
        final DataFetchListener.ObjectListener objectListener = new DataFetchListener.ObjectListener() {

            @Override
            public void onObjectGet(int retcode, String extraMsg,
                                    ObjectBase data) {
                if (view == null ||view.uiIsFinishing()) {
                    return;
                }
                //1.请求成功则引用到详情页数据中，返回
                if (retcode == WError.ERROR_NONE) {
                    DetailSeriesSet mDetailSeriesSet = (DetailSeriesSet) data;
                    WLog.i(TAG, "mDetailSeriesSet=" + mDetailSeriesSet);
                    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 loadRecommend(final String recommendUrl) {
        final DataFetchListener.ObjectListener objectListener = new DataFetchListener.ObjectListener() {

            @Override
            public void onObjectGet(int retcode, String extraMsg,
                                    ObjectBase data) {
                // TODO Auto-generated method stub
                if (retcode == WError.ERROR_INVALID_DATA
                        || retcode == WError.ERROR_NET) {
                    if (fetchDataRetryCount > 0) {
                        DataFetchModule.getInstance().fetchObjectGet(
                                recommendUrl, DemandRecommand.class, this);
                        fetchDataRetryCount--;
                        return;
                    }
                }
                if (view != null) {
                    if (retcode != 0) {
                        WLog.e(TAG, extraMsg);
                        view.loadRecommendFailed(retcode, extraMsg);
                        return;
                    }
                    if (view.uiIsFinishing()) {
                        return;
                    }
                    fetchDataRetryCount = 3;
                    demandRecommand = (DemandRecommand) data;
                    view.loadRecommendSuccess(demandRecommand);
                    //推荐为曝光统计
                    addRecommendListView();
                }
            }
        };
        WLog.i(TAG, "recommendUrl=" + recommendUrl);
        DataFetchModule.getInstance().fetchObjectGet(recommendUrl,
                DemandRecommand.class, objectListener);
    }

    /**
     * 推荐列表埋点，分2种情况，当前的详细页资产是大数据推荐和非大数据推荐
     **/
    private void addRecommendListView() {
        int len = demandRecommand.getRecommendItems().size();
        if (len > RECOMMEND_MAXNUM)
            len = RECOMMEND_MAXNUM;
        String[] ids = new String[len];
        String[] traceids = new String[len];
        for (int i = 0; i < len; i++) {
            ids[i] = demandRecommand.getRecommendItems().get(i).getId();
            traceids[i] = demandRecommand.getRecommendItems().get(i)
                    .getTraceid();
        }
        if (TextUtils.isEmpty(traceid)) {
            WasuStatistics.getInstance().BigDataRecommendListView(mDemandInfo.getId(),"");
        } else {
            WasuStatistics.getInstance().BigDataRecommendListView(mDemandInfo.getId(), traceid);
        }
    }

    public void loadAdData() {
        // 显示广告
        WasuAdEngine.getInstance().removeDirectP();
        Map<String, String> params = new HashMap<String, String>();
        params.put("userid",
                AuthSDK.getInstance().getValue(IAuthInterface.KEY_TVID));
        if (mDemandInfo != null) {
            params.put("columnid", mDemandInfo.getCatId());
            params.put("programid", mDemandInfo.getId());
            params.put("prol", "CS4.0_" + getAppVersion((Context) view));
            params.put("ccid", mDemandInfo.getCatId());
            params.put("cid", mDemandInfo.getId());
            params.put("ccName", mDemandInfo.getCatName());
            params.put("cName", mDemandInfo.getTitle());
        }
        params.put("featureid", mDemandInfo.getPrice() == 0 ? "true" : "false");
        params.put("pay", mDemandInfo.getPrice() == 0 ? "0" : "1");

        AdView adview = WasuAdEngine.getInstance().getImageAd(74, R.drawable.default_wasu_bg, true, params, false, null);
        if (adview != null) {
            view.loadAdSuccess(adview);
        } else {
            view.loadAdFailed();
        }
    }

    // app版本
    public String getAppVersion(Context context) {

        String appVersion = "";
        PackageManager manager = context.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(),
                    0);
            appVersion = info.versionName; // 版本名

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return appVersion;

    }

    public void queryPrice(final boolean guidtobuy) {
        /** 询价 **/
        if (mDemandInfo == null) {
            return;
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("resourceId", mDemandInfo.getId());
        params.put("resourceName", mDemandInfo.getTitle());
        params.put("orderType", 0);
        AuthSDK.getInstance().queryPrice(params, new AuthListener() {
            @Override
            public void result(int ret, String extra, Object retData) {
                //hideLoading();
                if (view==null|| view.uiIsFinishing() || mDemandInfo == null) {
                    return;
                }
                if (ret == WError.ERROR_NONE && mDemandInfo != null) {//询价成功
                    PriceInfo priceInfo = (PriceInfo) retData;
                    view.queryPriceSuccess(priceInfo, guidtobuy);
                } else {// 询价失败
                    view.queryPriceFailed(ret, extra);
                }
                view.notifyPlayerPriceChanged(ret, extra, retData);
            }
        });
    }

    public void adFreeQuery() {
        if (AuthSDK.getInstance().getValue(IAuthInterface.KEY_USERKEY).isEmpty()) {//未登录用户不能调免广告查询接口
            return;
        }
        AuthSDK.getInstance().verifyUserIsAdFree(new AuthListener() {
            @Override
            public void result(int ret, String extra, Object retData) {
                if (ret != WError.ERROR_NONE) {
                    WLog.e(TAG, "adFreeQuery verifyUserIsAdFree fail:" + extra);
                    view.adFreeQueryFailed(ret, extra);
                } else {
                    try {
                        JSONObject root = new JSONObject(new String((byte[]) retData, "utf-8"));
                        adFree = root.optInt("isFree");
                        if (adFree != 1) {
                            adFree = 0;
                        }
                        if (view!=null && !view.uiIsFinishing()) {
                            view.adFreeQuerySuccess(adFree);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    public void setTraceid(String traceid) {
        this.traceid = traceid;
    }

    public int getAdFree() {
        return adFree;
    }

    public void doFavorite() {
        boolean mIsFavorite = FavAndHisModule.getInstance().hasFavorite(mDemandInfo.getId());
        mIsFavorite = !mIsFavorite;
        doTclFavorite(mIsFavorite);
        doAliFavorite(mIsFavorite);
        doWasuFavorite(mIsFavorite);
        view.updateFavoriteUi(mIsFavorite);//更新UI
        if (mDemandInfo != null) {
            if (mIsFavorite) {
                view.toastMsg(String.format(((Context) view).getString(R.string.tips_favorite_in),
                        mDemandInfo.getTitle()));
                // 单参数是大数据收藏
                WasuStatistics.getInstance().collect(mDemandInfo.getId());
            } else {
                view.toastMsg(String.format(
                        ((Context) view).getString(R.string.tips_favorite_out),
                        mDemandInfo.getTitle()));
            }
        }
    }

    private void doTclFavorite(boolean favorite) {
        if (favorite) {
            saveFavoriteToTcl();
        } else {
            cancleFavoriteToTcl();
        }
    }

    private void doAliFavorite(boolean favorite) {
        try {
            Intent intent = new Intent("com.wasuali.action.favorite ");
            intent.putExtra("Id", mDemandInfo.getId());
            intent.putExtra("IsFavorite", favorite);
            intent.putExtra("poster", mDemandInfo.getPicUrl());
            intent.putExtra("proName", mDemandInfo.getTitle());
            intent.putExtra("showType", mDemandInfo.getAssetType());
            intent.putExtra("seriesCount", mDemandInfo.getNowItem());
            ((Context) view).sendBroadcast(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * children_collect（TCL版）
     **/
    private void saveFavoriteToTcl() {
        WLog.i(TAG, "saveFavoriteToTcl");
        try {
            // 必选
            Intent intent = new Intent("com.tv.favorite.add");
            intent.putExtra("srcApp", ACTION_FAVORITE_TCL);
            intent.putExtra("videoId", mDemandInfo.getId());
            intent.putExtra("videoName", mDemandInfo.getTitle());
            intent.putExtra("videoImgUrl", mDemandInfo.getPicUrl());
            // 可选
            intent.putExtra("episodeId", ""
                    + (mDemandInfo.getCurPlayIndex()));
            intent.putExtra("episodeName", mDemandInfo.getTitle());
            intent.putExtra("episodeCount", mDemandInfo.getNowItem());
            intent.putExtra("currentPosition", 0);
            intent.putExtra("duration", 0);
            WLog.i("ActivityDetail",
                    "saveFavoriteToTcl videoId=" + mDemandInfo.getId());
            ((Context) view).sendBroadcast(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 取消收藏（TCL版）
     **/
    private void cancleFavoriteToTcl() {
        WLog.i(TAG, "cancleFavoriteToTcl");
        try {
            Intent intent = new Intent("com.tv.favorite.del.tolauncher");
            intent.putExtra("srcApp", ACTION_PROGRAM);
            intent.putExtra("videoId", mDemandInfo.getId());
            ((Context) view).sendBroadcast(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void doWasuFavorite(boolean bFavorite) {
        if (mDemandInfo == null) {
            return;
        }
        try {
            if (bFavorite) {//children_collect
                if (mDemandInfo == null) {
                    return;
                }
                DBProgramFavorite mFavorite = new DBProgramFavorite();
                mFavorite.programId = Integer.parseInt(mDemandInfo.getId());
                mFavorite.domain = "";
                mFavorite.programPic = mDemandInfo.getPicUrl();
                mFavorite.programName = mDemandInfo.getTitle();
                mFavorite.detailUrl = mDemandInfo.getDetailUrl();
                mFavorite.playUrl = "";
                mFavorite.showType = mDemandInfo.getAssetType();// 0非影视剧
                mFavorite.preUpdateSeries = mDemandInfo.getNowItem();
                mFavorite.updateSeries = mDemandInfo.getNowItem();
                mFavorite.totalSeries = mDemandInfo.getItemNum();
                mFavorite.savefavoritetime = System.currentTimeMillis();
                //favoriteDao.createOrUpdate(mFavorite);
                mFavorite.insertOrUpdate();
                view.toastMsg(String.format(((Context) view).getString(R.string.tips_favorite_in),
                        mDemandInfo.getTitle()));
            } else {//取消收藏
                DBManage.deleteBy(DBProgramFavorite.class, "programId", mDemandInfo.getId());
                view.toastMsg(String.format(
                        ((Context) view).getString(R.string.tips_favorite_out),
                        mDemandInfo.getTitle()));
            }
        } catch (Exception e) {
            e.printStackTrace();
            WLog.d(TAG, e.toString());
        }
    }
    public void doWasuChildFavorite() {
        boolean bFavorite = ChildFavModule.getInstance().hasFavorite(mDemandInfo.getId());
        bFavorite = !bFavorite;
        view.updateFavoriteUi(bFavorite);
        if (mDemandInfo == null) {
            return;
        }
        try {
            if (bFavorite) {//收藏
                if (mDemandInfo == null) {
                    return;
                }
                DBProgramChildFavorite mFavorite = new DBProgramChildFavorite();
                mFavorite.programId = Integer.parseInt(mDemandInfo.getId());
                mFavorite.domain = "";
                mFavorite.programPic = mDemandInfo.getPicUrl();
                mFavorite.programName = mDemandInfo.getTitle();
                mFavorite.detailUrl = mDemandInfo.getDetailUrl();
                mFavorite.playUrl = "";
                mFavorite.showType = mDemandInfo.getAssetType();// 0非影视剧
                mFavorite.preUpdateSeries = mDemandInfo.getNowItem();
                mFavorite.updateSeries = mDemandInfo.getNowItem();
                mFavorite.totalSeries = mDemandInfo.getItemNum();
                mFavorite.savefavoritetime = System.currentTimeMillis();
                //favoriteDao.createOrUpdate(mFavorite);
                mFavorite.insertOrUpdate();
            } else {//取消收藏
                DBManage.deleteBy(DBProgramChildFavorite.class, "programId", mDemandInfo.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
            WLog.d(TAG, e.toString());
        }
    }
}
