package com.ym.klccy

import android.app.Activity
import android.os.Build
import android.text.TextUtils
import com.zxhl.detector.news.SplashContract
import com.ym.modulecommon.AppliContext
import com.ym.modulecommon.AdConfig
import com.ym.modulecommon.AdConstant
import com.ym.modulecommon.net.*
import com.ym.modulecommon.utils.*
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/5/18
 */
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
    }

    companion object {
        val PERMISSIONS = arrayOf(
            CommentConfig.Permission.PERMISSION_STORAGE,
            CommentConfig.Permission.PERMISSION_PHONE,
            CommentConfig.Permission.PERMISSION_COARSE_LOCATION,
            CommentConfig.Permission.PERMISSION_FINE_LOCATION
//                Constant.Permission.CAMERA
        )
    }

    private var mDisposablePermissions: Disposable? = null


    //*
    override 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 {
                        getAppConfig()
                    }
                }

                override fun onError(e: Throwable) {

                }

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

    override fun getAppConfig() {

        LogUtils.d("AdManager", "getAppConfig   开始" + System.currentTimeMillis())
        var url = NetConfig.NOVEL_INIT_URL
        val cv = CpuUtils.getArchType(AppliContext.get())
        var md5 = AdPreference.getMd5()
        if (TextUtils.isEmpty(md5)) {
            md5 = ""
        }
        LogUtils.d("glc", "md5:" + md5)
        LogUtils.d("glc", "cv:" + cv)
        ApiClient.homeDataApi.initNovel(url, md5, cv).compose(
            RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<NovelInitEntity>() {
                override fun onSuccess(mNovelInitEntity: NovelInitEntity) {

                    LogUtils.d("AdManager", "getAppConfig  结束" + System.currentTimeMillis())

                    if (mNovelInitEntity != null) {
                        initConfig(mNovelInitEntity)
                    } else {
                        loadCacheConfig()
                    }


                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
                    loadCacheConfig()
                }
            })
    }


    private fun loadCacheConfig() {
        val fileName = "globalCfg.json"
        val configJson = JsonReadUtil.getJsonStr(AppliContext.get(), fileName).trim { it <= ' ' }
        val result = Utils.str2Obj(configJson, NovelInitEntity::class.java) as NovelInitEntity
        initConfig(result)
    }


    private fun initConfig(mNovelInitEntity: NovelInitEntity) {
        LogUtils.d("AdManager", "initConfig  开始" + System.currentTimeMillis())
        AdConfig.init(mActivity)//TODO  必须在获取权限之后初始化，不然会出现两个deviceID的问题


        CommentConfig.Other.HELP_AND_FEEDBACK_URL = mNovelInitEntity?.help
        CommentConfig.Other.PRIVACY_PROTOCOL_URL = mNovelInitEntity?.agreement
        CommentConfig.Other.FENLEI_URL = mNovelInitEntity?.cate
        CommentConfig.Other.big_award = mNovelInitEntity?.big_award

        CommentConfig.Param.bannerSlotId = mNovelInitEntity?.slotIds?.bannerSlotId
        CommentConfig.Param.manSlotId = mNovelInitEntity?.slotIds?.manSlotId
        CommentConfig.Param.womanSlotId = mNovelInitEntity?.slotIds?.womanSlotId
        CommentConfig.Param.baoPingSlotId = mNovelInitEntity?.slotIds?.baoPingSlotId
        CommentConfig.Param.collectSlotId = mNovelInitEntity?.slotIds?.collectSlotId
        CommentConfig.Param.welfareCenterUrl = mNovelInitEntity?.welfareCenterUrl
        CommentConfig.Param.detailSlotId = mNovelInitEntity?.slotIds?.detailSlotId
//        CommentConfig.Param.splashSlotId = mNovelInitEntity?.slotIds?.kaipinSlotId

        CommentConfig.Param.helpUrl = mNovelInitEntity?.help
        CommentConfig.Param.newHelpUS = mNovelInitEntity?.newHelpUS
        CommentConfig.price_draw_switch = mNovelInitEntity?.switch?.price_draw_switch ?: 0
        CommentConfig.home_today_data_switch = mNovelInitEntity?.switch?.home_today_data_switch ?: 0
        CommentConfig.task_tab_switch = mNovelInitEntity?.switch?.task_tab_switch ?: 0
//        CommentConfig.ishomepay = mNovelInitEntity?.switch?.ishomepay ?: 0
        CommentConfig.ishomepayNew = mNovelInitEntity?.switch?.ishomepay ?: 0
        CommentConfig.isFree = mNovelInitEntity?.switch?.isFree ?: 0
//        CommentConfig.isFree = mNovelInitEntity?.switch?.isFree ?: 0
//        MiPushClient.subscribe(AppliContext.get(), mNovelInitEntity.global_config?.pushUserAccount?:"", null)


        if (mNovelInitEntity.image_url != null) {
            CommentConfig.Param.new_user_popup = mNovelInitEntity.image_url?.new_user_pop
            CommentConfig.Param.couponTitle = mNovelInitEntity.image_url?.couponTitle
        }
        if (mNovelInitEntity.h5_url != null) {
            CommentConfig.Other.ABOUT_US_URL = mNovelInitEntity?.h5_url?.aboutUs
            CommentConfig.Param.coinUrl = mNovelInitEntity?.h5_url?.coinUrl
            CommentConfig.Param.inviteUrl = mNovelInitEntity?.h5_url?.inviteUrl
            CommentConfig.H5.WEB_URL_READ_HELP = mNovelInitEntity.h5_url?.read_help
            CommentConfig.H5.WEB_URL_GLOD_DETAIL = mNovelInitEntity.h5_url?.glod_detail
            CommentConfig.H5.WEB_URL_CHANGE_DETAIL = mNovelInitEntity.h5_url?.change_detail
            CommentConfig.H5.WEB_URL_WITHDRAW_MATTERS_NEED = mNovelInitEntity.h5_url?.matters_need
            CommentConfig.H5.MAKE_MONEY = mNovelInitEntity.h5_url?.awardHelpUrl
            CommentConfig.Param.achievementUrl = mNovelInitEntity.h5_url?.achievementUrl
            CommentConfig.Param.download = mNovelInitEntity.h5_url?.downloadUrl

            CommentConfig.H5.HEALTH_REPORT_HISTORY = mNovelInitEntity.h5_url?.health_history_report
            CommentConfig.H5.HEALTH_REPORT = mNovelInitEntity.h5_url?.health_report
            CommentConfig.Param.taskDetailsUrl = mNovelInitEntity.h5_url?.taskDetailsUrl
            CommentConfig.Param.CommonProblemsUrl = mNovelInitEntity.h5_url?.CommonProblemsUrl
            CommentConfig.Param.ActivityRulesUrl = mNovelInitEntity.h5_url?.ActivityRulesUrl
            CommentConfig.Param.MakeMoneyUrl = mNovelInitEntity.h5_url?.MakeMoneyUrl

            CommentConfig.team_url = mNovelInitEntity.h5_url?.super_team

            CommentConfig.Param.makingMoneyUrl = mNovelInitEntity.h5_url?.makingMoneyUrl

            CommentConfig.Param.payAgreementUrl = mNovelInitEntity.h5_url?.pay
            CommentConfig.Param.userAgreementUrl = mNovelInitEntity.h5_url?.user
            CommentConfig.Param.privacyAgreementUrl = mNovelInitEntity.h5_url?.privacy
            CommentConfig.Param.wx_share = mNovelInitEntity.h5_url?.wx_share
            CommentConfig.Param.invite = mNovelInitEntity.h5_url?.invite
            CommentConfig.Param.tutorial = mNovelInitEntity.h5_url?.tutorial
            CommentConfig.Param.onlineService = mNovelInitEntity.h5_url?.onlineService
            CommentConfig.Param.tipsUrl = mNovelInitEntity.h5_url?.tipsUrl
            CommentConfig.Param.Refundurl = mNovelInitEntity.h5_url?.Refundurl
            CommentConfig.Param.FeedBackuUrl = mNovelInitEntity.h5_url?.FeedBackuUrl
        }



        CommentConfig.first_open_navigate = mNovelInitEntity.switch?.first_open_navigate ?: 0
        CommentConfig.tourist_login = mNovelInitEntity.switch?.tourist_login ?: 0
        CommentConfig.copythat = mNovelInitEntity.switch?.copythat ?: 0
        CommentConfig.wd_agreement_selected = mNovelInitEntity.switch?.wd_agreement_selected ?: 0


        val str = mNovelInitEntity.config?.wx_config_text ?: ""
        val jsonStr = AESUtils.decrypt(str, "432rz97zsrnd6t02")
        val wxObj = Utils.str2Obj(jsonStr, WxKeyEntity::class.java) as WxKeyEntity?
        CommentConfig.WX_APPID = wxObj?.pay?.wx_appid
        CommentConfig.WX_APPKEY = wxObj?.pay?.wx_appkey
        CommentConfig.WX_SHARE_APPID = wxObj?.share?.wx_appid
        CommentConfig.WX_SHARE_APPKEY = wxObj?.share?.wx_appkey
        CommentConfig.wx_status = mNovelInitEntity.pay_config?.wx?.status ?: 0
        CommentConfig.ali_status = mNovelInitEntity.pay_config?.ali?.status ?: 0

        AdPreference.saveLua(mNovelInitEntity?.md5, mNovelInitEntity?.lua)
        LogUtils.d("AdManager", "initConfig  结束" + System.currentTimeMillis())
        deveiceLogin()
    }


    private fun deveiceLogin() {
        LogUtils.d("AdManager", "deveiceLogin  开始" + System.currentTimeMillis())
        ApiClient.userApi.deveiceLogin().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<UserInfoEntity>() {
                override fun onSuccess(result: UserInfoEntity) {

                    LogUtils.d("AdManager", "deveiceLogin  结束" + System.currentTimeMillis())

                    val token = result.token
                    if (!TextUtils.isEmpty(token)) {
                        SettingPreference.setToken(token)
                        getUserInfo()
                    }
                }

                override fun onFailure(e: Throwable, code: String, errorMsg: String) {
                    if (!TextUtils.equals(code, "200")) {
                        AdConstant.param.uid = ""
                        AdConstant.param.token = ""
                        SettingPreference.setUid("")
                        SettingPreference.setToken("")
                        SettingPreference.saveUserInfo(null)
                    } else {
                        mView.jumpPage()
                    }
                }
            })
    }

    fun getUserInfo() {
        LogUtils.d("AdManager", "getUserInfo  开始" + System.currentTimeMillis())

        ApiClient.userApi.getUserInfo().compose(
            RxSchedulers.observableIO2Main()
        )
            .subscribe(object : BaseObserver<UserInfoEntity>() {
                override fun onSuccess(result: UserInfoEntity) {

                    LogUtils.d("AdManager", "getUserInfo  结束" + System.currentTimeMillis())

                    val uid = result.uid
                    if (TextUtils.isEmpty(uid)) {
                    } else {
                        SettingPreference.saveUserInfo(result)
                        AdPreference.setTrackId(result.gaodeTrackId ?: 0L)
                        AdPreference.setTerminalId(result.gaodeTerminalId ?: 0L)
                        mView.jumpPage()
                    }
                }

                override fun onFailure(e: Throwable, code: String, errorMsg: String) {
                    mView.jumpPage()
                }
            })
    }
}