package com.zxhl.main.page.presenter

import android.app.Activity
import android.os.Build
import android.text.TextUtils
import android.view.View
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.TTAdNative
import com.bytedance.sdk.openadsdk.TTAdSdk
import com.bytedance.sdk.openadsdk.TTSplashAd
import com.zxhl.cms.AppContext
import com.zxhl.cms.ad.upload.Utils.AdUpload
import com.zxhl.cms.ad.upload.model.NewsEntity
import com.zxhl.cms.common.Constant
import com.zxhl.cms.net.ApiClient
import com.zxhl.cms.net.RxSchedulers
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.net.callback.BaseObserver
import com.zxhl.cms.net.model.uc.UserInfo
import com.zxhl.cms.utils.*
import com.zxhl.main.page.contract.SplashContract
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers

/**
 * Created by gaoleichao on 2019/3/16
 */
class SplashPresenter : SplashContract.Presenter {

    private val mView: SplashContract.View

    private val mActivity:Activity

    constructor(mView: SplashContract.View, mActivity: Activity) {
        this.mView = mView
        this.mActivity = mActivity
        checkPermissions()
    }


    companion object {
        val PERMISSIONS = arrayOf(
//            Constant.Permission.PERMISSION_READ_STORAGE,
                Constant.Permission.PERMISSION_PHONE
//                Constant.Permission.PERMISSION_COARSE_LOCATION,
//                Constant.Permission.PERMISSION_FINE_LOCATION
//            , Constant.Permission.PERMISSION_CAMERA
        )
    }

    private var mDisposablePermissions: Disposable? = null


    fun checkPermissions() {
        Observable.create(ObservableOnSubscribe<Boolean> { e ->
            val flag = Utils.needPermissions(*PERMISSIONS)
            e?.onNext(flag)
            e?.onComplete()
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<Boolean> {
                override fun onSubscribe(d: Disposable) {
                    mDisposablePermissions = d
                }

                override fun onNext(aBoolean: Boolean) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mView.getDestroyed()) {
                        return
                    }
                    // 缺少权限时, 进入权限配置页面
                    if (aBoolean) {
                        mView.jumpPermissionsPage()
                    } else {
                        checkLogin()
                    }
                }

                override fun onError(e: Throwable) {

                }

                override fun onComplete() {
                    if (mDisposablePermissions != null && mDisposablePermissions?.isDisposed == false) {
                        mDisposablePermissions?.dispose()
                    }
                }
            })
    }

    override fun checkLogin() {
        val user = SettingPreference.getUserInfoData()
        val token =SettingPreference.getUserToken()
        if (user == null&&TextUtils.isEmpty(token)) {
            if(TextUtils.equals( Utils.getChannel(AppContext.get()), "toutiao_h5")){
              //  deviceLogin()
                getAds()
            }else{
                deviceLogin()
            }


        } else {
            UserDataUtils.updateUserInfo(null)
            getAds()
        }
    }


    private fun deviceLogin() {
        ApiClient.userInfoAPi.deviceLogin().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<UserInfo>() {
                override fun onSuccess(result: UserInfo) {
                    val token = result.token
                    SettingPreference.saveToken(token)
                    UserDataUtils.updateUserInfo(null)
//                    mView?.jumpMainPage()
                    getAds()
                }

                override fun onFailure(e: Throwable, code: String, errorMsg: String) {
                    SettingPreference.saveToken("")
                    SettingPreference.saveUserInfo(null)
                    getAds()
                }
            })
    }

    private fun getAds() {
        ApiClient.adApi.getAds("splash")
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<List<NewsEntity>>() {
                override fun onSuccess(result: List<NewsEntity>) {
                    if (result != null && result?.size > 0) {
                        val data = result[0]
                        if (TextUtils.equals(data.adPlatform, "chuanshanjia")) {
                            loadToutiao(data, 0, "splash")
                        }
                    } else {
                        mView.jumpMainPage()
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    mView.jumpMainPage()
                }
            })
    }
    private var mTTAdNative: TTAdNative? = null

    private fun loadToutiao(data: NewsEntity, count: Int, slotNameL: String) {
        mTTAdNative = TTAdSdk.getAdManager().createAdNative(mActivity)//baseContext建议为activity
        val adSlot = AdSlot.Builder()
            .setCodeId(data?.codeId)
            .setSupportDeepLink(true)
            .setImageAcceptedSize(
                PhoneUtils.getScreenWidth(AppContext.get()),
                PhoneUtils.getScreenHeight(AppContext.get())
            )
            .build()
        mTTAdNative?.loadSplashAd(adSlot, object : TTAdNative.SplashAdListener {
            override fun onError(i: Int, s: String) {
                mView.jumpMainPage()
            }

            override fun onTimeout() {
                mView.jumpMainPage()
            }

            override fun onSplashAdLoad(ad: TTSplashAd) {
                val view = ad.splashView
                mView?.setToutiaoView(view)
                ad.setSplashInteractionListener(object : TTSplashAd.AdInteractionListener {
                    override fun onAdClicked(view: View, i: Int) {
                        EventUtils.onEvent("splash_click")
                        AdUpload.onAdClick(data)
                    }

                    override fun onAdShow(view: View, i: Int) {
                        EventUtils.onEvent("splash_show")
                        AdUpload.onAdImpression(data)
                    }

                    override fun onAdSkip() {
                        mView.jumpMainPage()
                    }

                    override fun onAdTimeOver() {
                        mView.jumpMainPage()
                    }
                })
            }
        }, 5000)
    }


}