package com.ym.library.net

import android.app.Activity
import android.os.Build
import android.text.TextUtils
import com.ym.library.Constant
import com.ym.library.utils.*
import com.ym.modulecommon.AppliContext
import com.ym.modulecommon.Config
import com.ym.modulecommon.module.UserInfoEntity
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(
            Constant.Permission.PERMISSION_STORAGE,
            Constant.Permission.PERMISSION_PHONE,
            Constant.Permission.PERMISSION_COARSE_LOCATION,
            Constant.Permission.PERMISSION_FINE_LOCATION
//                Constant.Permission.CAMERA
        )
    }

    private var mDisposablePermissions: Disposable? = null


    //*
    override fun checkPermissions() {
        EventUtils.onEvent("SplashPresenter_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) {
                        EventUtils.onEvent("SplashPresenter_jumpPermissionsPage")
                        mView.jumpPermissionsPage()
                    } else {
                        getAppConfig()
                    }
                }

                override fun onError(e: Throwable) {

                }

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

    override fun getAppConfig() {

        EventUtils.onEvent("SplashPresenter_getAppConfig")
        val url = NetConfig.Novel.NOVEL_INIT_URL
        val cv = CpuUtils.getArchType(AppliContext.get())
        var md5 = com.ym.modulecommon.utils.SettingPreference.getMd5()
        if (TextUtils.isEmpty(md5)) {
            md5 = ""
        }

        ApiClient.homeDataApi.initNovel(url, md5, cv).compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<NovelInitEntity>() {
                override fun onSuccess(mNovelInitEntity: NovelInitEntity) {
                    if (mNovelInitEntity != null) {
                        initConfig(mNovelInitEntity)
                    } else {
                        loadCacheConfig()
                    }
                }

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


    private fun loadCacheConfig() {
        EventUtils.onEvent("SplashPresenter_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) {
        Config.init(mActivity)
        EventUtils.onEvent("SplashPresenter_initConfig")
        NetConfig.Other.HELP_AND_FEEDBACK_URL = mNovelInitEntity?.help
        NetConfig.Other.PRIVACY_PROTOCOL_URL = mNovelInitEntity?.agreement
        NetConfig.Other.FENLEI_URL = mNovelInitEntity?.cate
        NetConfig.Other.big_award = mNovelInitEntity?.big_award

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

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

        Constant.SdkKey.kdxf_app_id = mNovelInitEntity.global_config?.ad_sdk_cfg?.kdxf?.app_id
        Constant.PLAY_URL = mNovelInitEntity.h5_url?.PlayUrl
        Constant.ISENTERTAINMENT = mNovelInitEntity.switch?.isEntertainment ?: 1
        Constant.qq = mNovelInitEntity?.switch?.qq ?: 0
        //广点通广告配置信息
        val gdtStr = Utils.obj2Str(mNovelInitEntity.global_config?.ad_sdk_cfg?.gdt)
        if (!TextUtils.isEmpty(gdtStr)) {
            SettingPreference.saveSlotGDT(gdtStr)
            val gdt = mNovelInitEntity.global_config?.ad_sdk_cfg?.gdt
            Constant.SdkKey.gdt_app_id = gdt?.app_id
            Constant.SdkKey.gdt_feed = gdt?.slot_cfg?.feed?.key
            Constant.SdkKey.gdt_bookrack = gdt?.slot_cfg?.bookrack?.key
            Constant.SdkKey.gdt_news_content_3img =
                gdt?.slot_cfg?.news_content_3img?.key
            Constant.SdkKey.gdt_news_content_bigimg =
                gdt?.slot_cfg?.news_content_bigimg?.key
            Constant.SdkKey.gdt_date_coins =
                gdt?.slot_cfg?.novel_time_award?.key
                    ?: ""
            Constant.SdkKey.gdt_prize_draw_bottom =
                gdt?.slot_cfg?.prize_draw_bottom?.key
                    ?: ""
            Constant.SdkKey.gdt_prize_draw_result =
                gdt?.slot_cfg?.prize_draw_result?.key
                    ?: ""
            Constant.SdkKey.gdt_sign = gdt?.slot_cfg?.signIn_result?.key
                ?: ""

        }
        //穿山甲广告配置
        val jrttStr = Utils.obj2Str(mNovelInitEntity.global_config?.ad_sdk_cfg?.jrtt)
        if (!TextUtils.isEmpty(jrttStr)) {
            SettingPreference.saveSlotJrtt(jrttStr)
            val jrtt = mNovelInitEntity.global_config?.ad_sdk_cfg?.jrtt

            Constant.SdkKey.byte_dance_feed = jrtt?.slot_cfg?.feed?.key
            Constant.SdkKey.byte_dance_bookrack = jrtt?.slot_cfg?.bookrack?.key
            Constant.SdkKey.byte_dance_mini_video =
                jrtt?.slot_cfg?.mini_video?.key
            Constant.SdkKey.byte_dance_news_content_3img =
                jrtt?.slot_cfg?.news_content_3img?.key
            Constant.SdkKey.byte_dance_news_content_bigimg =
                jrtt?.slot_cfg?.bubble_popup?.key
            Constant.SdkKey.byte_dance_novel_content_bottom =
                jrtt?.slot_cfg?.novel_content_bottom?.key
            Constant.SdkKey.byte_dance_novel_content_bigimg =
                jrtt?.slot_cfg?.novel_content_bigimg?.key
            Constant.SdkKey.byte_dance_novel_detail =
                jrtt?.slot_cfg?.novel_detail?.key
            Constant.SdkKey.byte_dance_exciting_video =
                jrtt?.slot_cfg?.exciting_video?.key
            Constant.SdkKey.byte_dance_date_coins =
                jrtt?.slot_cfg?.novel_time_award?.key
                    ?: ""
            Constant.SdkKey.signin_popup_bigimage =
                jrtt?.slot_cfg?.signin_popup_bigimage?.key
                    ?: ""
            Constant.SdkKey.chengjiu_popup_video =
                jrtt?.slot_cfg?.chengjiu_popup_video?.key
                    ?: ""
            Constant.SdkKey.chengjiu_popup_bigimage =
                jrtt?.slot_cfg?.chengjiu_popup_bigimage?.key
                    ?: ""
            Constant.SdkKey.new_user_award_bigimage =
                jrtt?.slot_cfg?.new_user_award_bigimage?.key
                    ?: ""
            Constant.SdkKey.byte_dance_video_feed =
                jrtt?.slot_cfg?.novel_short_video_feed?.key
                    ?: ""
            Constant.SdkKey.byte_dance_prize_draw_bottom =
                jrtt?.slot_cfg?.prize_draw_bottom?.key
                    ?: ""
            Constant.SdkKey.byte_dance_prize_draw_result =
                jrtt?.slot_cfg?.prize_draw_result?.key
                    ?: ""
            Constant.SdkKey.byte_dance_sign = jrtt?.slot_cfg?.signIn_result?.key
                ?: ""
            Constant.SdkKey.byte_dance_mini_video_list =
                jrtt?.slot_cfg?.mini_video_list?.key
                    ?: ""
            Constant.SdkKey.byte_dance_splash = jrtt?.slot_cfg?.splash?.key
                ?: ""
            Constant.SdkKey.byte_dance_prize_draw_video =
                jrtt?.slot_cfg?.prize_draw_video?.key
                    ?: ""
            Constant.SdkKey.transform_limit_Video =
                jrtt?.slot_cfg?.transform_limit_Video?.key
                    ?: ""
            Constant.SdkKey.daily_active_video =
                jrtt?.slot_cfg?.daily_active_video?.key
                    ?: ""
            Constant.SdkKey.daily_active_bigimage =
                jrtt?.slot_cfg?.daily_active_bigimage?.key
                    ?: ""
            Constant.superMasterTab = mNovelInitEntity.switch?.superMasterTab ?: 0

            Constant.SdkKey.novel_svideos_awardt_video =
                jrtt?.slot_cfg?.novel_svideos_awardt_video?.key
            Constant.SdkKey.novel_mini_award_video =
                jrtt?.slot_cfg?.novel_mini_award_video?.key
            Constant.SdkKey.novel_feed_award_video =
                jrtt?.slot_cfg?.novel_feed_award_video?.key

            Constant.SdkKey.signin_popup = jrtt?.slot_cfg?.signin_popup?.key
            Constant.SdkKey.bubble_popup = jrtt?.slot_cfg?.bubble_popup?.key
            Constant.SdkKey.signin_popup_video =
                jrtt?.slot_cfg?.signin_popup_video?.key
            Constant.SdkKey.bubble_popup_video =
                jrtt?.slot_cfg?.bubble_popup_video?.key
            Constant.SdkKey.exciting_video = jrtt?.slot_cfg?.exciting_video?.key
        }

        if (mNovelInitEntity.image_url != null) {
            Constant.Param.new_user_popup = mNovelInitEntity.image_url?.new_user_pop
            Constant.Param.couponTitle = mNovelInitEntity.image_url?.couponTitle
        }
        SettingPreference.setSlotId(mNovelInitEntity?.bannerSlotId)
        SettingPreference.saveInitInfo(mNovelInitEntity)
        if (mNovelInitEntity.h5_url != null) {
            NetConfig.Other.ABOUT_US_URL = mNovelInitEntity?.h5_url?.aboutUs
            Constant.Param.coinUrl = mNovelInitEntity?.h5_url?.coinUrl
            Constant.Param.inviteUrl = mNovelInitEntity?.h5_url?.inviteUrl

            NetConfig.H5.WEB_URL_READ_HELP = mNovelInitEntity.h5_url?.read_help
            NetConfig.H5.WEB_URL_GLOD_DETAIL = mNovelInitEntity.h5_url?.glod_detail
            NetConfig.H5.WEB_URL_CHANGE_DETAIL = mNovelInitEntity.h5_url?.change_detail
            NetConfig.H5.WEB_URL_WITHDRAW_MATTERS_NEED = mNovelInitEntity.h5_url?.matters_need
            NetConfig.H5.MAKE_MONEY = mNovelInitEntity.h5_url?.awardHelpUrl
            Constant.Param.achievementUrl = mNovelInitEntity.h5_url?.achievementUrl
            Constant.Param.download = mNovelInitEntity.h5_url?.downloadUrl

            NetConfig.H5.HEALTH_REPORT_HISTORY = mNovelInitEntity.h5_url?.health_history_report
            NetConfig.H5.HEALTH_REPORT = mNovelInitEntity.h5_url?.health_report
            Constant.Param.taskDetailsUrl = mNovelInitEntity.h5_url?.taskDetailsUrl
            Constant.Param.CommonProblemsUrl = mNovelInitEntity.h5_url?.CommonProblemsUrl
            Constant.Param.ActivityRulesUrl = mNovelInitEntity.h5_url?.ActivityRulesUrl
            Constant.Param.MakeMoneyUrl = mNovelInitEntity.h5_url?.MakeMoneyUrl
            Constant.Param.USER = mNovelInitEntity.h5_url?.user
            Constant.Param.ABOUTUS = mNovelInitEntity.h5_url?.aboutUs
            Constant.Param.PRIVACY = mNovelInitEntity.h5_url?.privacy

            Constant.team_url = mNovelInitEntity.h5_url?.super_team

            Constant.Param.makingMoneyUrl = mNovelInitEntity.h5_url?.makingMoneyUrl

            Constant.Param.payAgreementUrl = mNovelInitEntity.h5_url?.pay
            Constant.Param.userAgreementUrl = mNovelInitEntity.h5_url?.user
            Constant.Param.privacyAgreementUrl = mNovelInitEntity.h5_url?.privacy
            Constant.Param.wx_share = mNovelInitEntity.h5_url?.wx_share
            Constant.Param.invite = mNovelInitEntity.h5_url?.invite
            Constant.Param.tutorial = mNovelInitEntity.h5_url?.tutorial
            Constant.Param.onlineService = mNovelInitEntity.h5_url?.onlineService
            Constant.Param.tipsUrl = mNovelInitEntity.h5_url?.tipsUrl
            Constant.Param.Refundurl = mNovelInitEntity.h5_url?.Refundurl
            Constant.Param.FeedBackuUrl = mNovelInitEntity.h5_url?.FeedBackuUrl
            Constant.Param.WelfareCenter = mNovelInitEntity.h5_url?.welfareurl
            SettingPreference.setWelfareCenterUrl(mNovelInitEntity.h5_url?.welfareurl)
            Constant.Param.PunchRecord = mNovelInitEntity.h5_url?.clockInzurl
            Constant.Param.RankList = mNovelInitEntity.h5_url?.rankingurl
            Constant.Param.WithDraw = mNovelInitEntity.h5_url?.withdrawurl

        }



        Constant.DETAULT_TAB = mNovelInitEntity.global_config?.default_tab ?: "13"

        Constant.force_login = mNovelInitEntity.global_config?.force_login ?: 0
        Constant.home_signin = mNovelInitEntity.global_config?.home_signin ?: 0
        Constant.to_kandian_withdraw = mNovelInitEntity.global_config?.to_kandian_withdraw ?: 0
        Constant.wxName = mNovelInitEntity.global_config?.wxName ?: ""
        Constant.novel_read_award_desc = mNovelInitEntity.global_config?.novel_read_award_desc ?: ""
        Constant.first_login_img = mNovelInitEntity.global_config?.first_login_img
        Constant.first_open_navigate = mNovelInitEntity.switch?.first_open_navigate ?: 0
        Constant.tourist_login = mNovelInitEntity.switch?.tourist_login ?: 0
        Constant.copythat = mNovelInitEntity.switch?.copythat ?: 0
        Constant.wd_agreement_selected = mNovelInitEntity.switch?.wd_agreement_selected ?: 0
//        Constant.huangli_switch = mNovelInitEntity.switch?.huangli_switch?:0
        SettingPreference.setSplashInvreval(mNovelInitEntity.global_config?.splash_intreval ?: 10)


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

        val md5: String = mNovelInitEntity?.md5 ?: ""
        val lua: String = mNovelInitEntity?.lua ?: ""
//        if (lua != null && !TextUtils.isEmpty(lua)) {
//            Log.d("lua", "lua:---->" + lua)
//            if (!TextUtils.isEmpty(md5)) {
//                SettingPreference.saveMd5(md5)
//            }
//            SettingPreference.saveSecDesc(lua)
//
//            CesCore.getInstance().setData(lua)
//            Constant.Param.env = CesCore.getInstance().Ckwork(SettingPreference.getAndroidId())
//            Constant.Param.md5 = SettingPreference.getMd5()
//        } else {
//            val lua = SettingPreference.getSecDesc()
//            if (!TextUtils.isEmpty(lua)) {
//                CesCore.getInstance().setData(lua)
//                Constant.Param.env = CesCore.getInstance().Ckwork(SettingPreference.getAndroidId())
//            }
//        }
//        deviceLogin()
//        getUserInfo()
        mView.jumpPage()
    }

    private fun deviceLogin() {
        EventUtils.onEvent("SplashPresenter_deviceLogin")
        ApiClient.userApi.deveiceLogin().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<UserInfoEntity>() {
                override fun onSuccess(result: UserInfoEntity) {
                    val token = result.token
                    if (!TextUtils.isEmpty(token)) {
                        EventUtils.onEvent("SplashPresenter_deviceLogin_success")
                        com.ym.modulecommon.utils.SettingPreference.setToken(token)
                    } else {
                        EventUtils.onEvent("SplashPresenter_deviceLogin_fail")
                        com.ym.modulecommon.utils.SettingPreference.setToken("")
                    }
                    getUserInfo()
                }

                override fun onFailure(e: Throwable, code: String, errorMsg: String?) {
                    EventUtils.onEvent("SplashPresenter_deviceLogin_fail")
                    if (!TextUtils.equals(code, "200")) {
                        Constant.Param.uid = ""
                        Constant.Param.token = ""
                        com.ym.modulecommon.utils.SettingPreference.setUid("")
                        com.ym.modulecommon.utils.SettingPreference.setToken("")
                        com.ym.modulecommon.utils.SettingPreference.saveUserInfo(null)
                    }
                    getUserInfo()
                }
            })
    }

    fun getUserInfo() {
        EventUtils.onEvent("SplashPresenter_getUserInfo")
        ApiClient.userApi.getUserInfo().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<UserInfoEntity>() {
                override fun onSuccess(result: UserInfoEntity) {
                    val uid = result.uid
                    if (TextUtils.isEmpty(uid)) {
                        EventUtils.onEvent("SplashPresenter_getUserInfo_fail")
                    } else {
                        EventUtils.onEvent("SplashPresenter_getUserInfo_success")
                        com.ym.modulecommon.utils.SettingPreference.saveUserInfo(result)
                        SettingPreference.setTrackId(result.gaodeTrackId ?: 0L)
                        SettingPreference.setTerminalId(result.gaodeTerminalId ?: 0L)
                        com.ym.modulecommon.utils.SettingPreference.setUid(uid)
                    }
                    mView.jumpPage()
                }

                override fun onFailure(e: Throwable, code: String?, errorMsg: String?) {
                    EventUtils.onEvent("SplashPresenter_getUserInfo_fail")
                    mView.jumpPage()
                }
            })
    }
}