package com.ym.library.net

import android.app.Activity
import android.os.Build
import android.text.TextUtils
import com.ym.xynt.UserInfoEntity
import com.ym.library.MyConstant
import com.ym.library.utils.*
import com.ym.library.utils.SettingPreference.saveUserInfo
import com.ym.modulecommon.AdConfig
import com.ym.modulecommon.AppliContext
import com.ym.modulecommon.utils.AdPreference
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(
            MyConstant.Permission.PERMISSION_STORAGE,
            MyConstant.Permission.PERMISSION_PHONE,
            MyConstant.Permission.PERMISSION_COARSE_LOCATION,
            MyConstant.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 = AdPreference.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) {
        AdConfig.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

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

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

        MyConstant.SdkKey.kdxf_app_id = mNovelInitEntity.global_config?.ad_sdk_cfg?.kdxf?.app_id
        MyConstant.PLAY_URL = mNovelInitEntity.h5_url?.PlayUrl
        MyConstant.ISENTERTAINMENT = mNovelInitEntity.switch?.isEntertainment ?: 1
        MyConstant.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
            MyConstant.SdkKey.gdt_app_id = gdt?.app_id
            MyConstant.SdkKey.gdt_feed = gdt?.slot_cfg?.feed?.key
            MyConstant.SdkKey.gdt_bookrack = gdt?.slot_cfg?.bookrack?.key
            MyConstant.SdkKey.gdt_news_content_3img =
                gdt?.slot_cfg?.news_content_3img?.key
            MyConstant.SdkKey.gdt_news_content_bigimg =
                gdt?.slot_cfg?.news_content_bigimg?.key
            MyConstant.SdkKey.gdt_date_coins =
                gdt?.slot_cfg?.novel_time_award?.key
                    ?: ""
            MyConstant.SdkKey.gdt_prize_draw_bottom =
                gdt?.slot_cfg?.prize_draw_bottom?.key
                    ?: ""
            MyConstant.SdkKey.gdt_prize_draw_result =
                gdt?.slot_cfg?.prize_draw_result?.key
                    ?: ""
            MyConstant.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

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

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

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

        if (mNovelInitEntity.image_url != null) {
            MyConstant.Param.new_user_popup = mNovelInitEntity.image_url?.new_user_pop
            MyConstant.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
            MyConstant.Param.coinUrl = mNovelInitEntity?.h5_url?.coinUrl
            MyConstant.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
            MyConstant.Param.achievementUrl = mNovelInitEntity.h5_url?.achievementUrl
            MyConstant.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
            MyConstant.Param.taskDetailsUrl = mNovelInitEntity.h5_url?.taskDetailsUrl
            MyConstant.Param.CommonProblemsUrl = mNovelInitEntity.h5_url?.CommonProblemsUrl
            MyConstant.Param.ActivityRulesUrl = mNovelInitEntity.h5_url?.ActivityRulesUrl
            MyConstant.Param.MakeMoneyUrl = mNovelInitEntity.h5_url?.MakeMoneyUrl
            MyConstant.Param.USER = mNovelInitEntity.h5_url?.user
            MyConstant.Param.ABOUTUS = mNovelInitEntity.h5_url?.aboutUs
            MyConstant.Param.PRIVACY = mNovelInitEntity.h5_url?.privacy

            MyConstant.team_url = mNovelInitEntity.h5_url?.super_team

            MyConstant.Param.makingMoneyUrl = mNovelInitEntity.h5_url?.makingMoneyUrl

            MyConstant.Param.payAgreementUrl = mNovelInitEntity.h5_url?.pay
            MyConstant.Param.userAgreementUrl = mNovelInitEntity.h5_url?.user
            MyConstant.Param.privacyAgreementUrl = mNovelInitEntity.h5_url?.privacy
            MyConstant.Param.wx_share = mNovelInitEntity.h5_url?.wx_share
            MyConstant.Param.invite = mNovelInitEntity.h5_url?.invite
            MyConstant.Param.tutorial = mNovelInitEntity.h5_url?.tutorial
            MyConstant.Param.onlineService = mNovelInitEntity.h5_url?.onlineService
            MyConstant.Param.tipsUrl = mNovelInitEntity.h5_url?.tipsUrl
            MyConstant.Param.Refundurl = mNovelInitEntity.h5_url?.Refundurl
            MyConstant.Param.FeedBackuUrl = mNovelInitEntity.h5_url?.FeedBackuUrl
            MyConstant.Param.WelfareCenter = mNovelInitEntity.h5_url?.welfareurl
            SettingPreference.setWelfareCenterUrl(mNovelInitEntity.h5_url?.welfareurl)
            MyConstant.Param.PunchRecord = mNovelInitEntity.h5_url?.clockInzurl
            MyConstant.Param.RankList = mNovelInitEntity.h5_url?.rankingurl
            MyConstant.Param.WithDraw = mNovelInitEntity.h5_url?.withdrawurl
            NetConfig.H5.CONFIRMURL = mNovelInitEntity.h5_url?.Confirmurl
            NetConfig.H5.guaguakaurl = mNovelInitEntity.h5_url?.guaguakaurl
            NetConfig.H5.InviteFriendsurl = mNovelInitEntity.h5_url?.InviteFriendsurl
        }



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

        MyConstant.force_login = mNovelInitEntity.global_config?.force_login ?: 0
        MyConstant.home_signin = mNovelInitEntity.global_config?.home_signin ?: 0
        MyConstant.to_kandian_withdraw = mNovelInitEntity.global_config?.to_kandian_withdraw ?: 0
        MyConstant.wxName = mNovelInitEntity.global_config?.wxName ?: ""
        MyConstant.novel_read_award_desc = mNovelInitEntity.global_config?.novel_read_award_desc ?: ""
        MyConstant.first_login_img = mNovelInitEntity.global_config?.first_login_img
        MyConstant.first_open_navigate = mNovelInitEntity.switch?.first_open_navigate ?: 0
        MyConstant.tourist_login = mNovelInitEntity.switch?.tourist_login ?: 0
        MyConstant.copythat = mNovelInitEntity.switch?.copythat ?: 0
        MyConstant.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?
        MyConstant.WX_APPID = wxObj?.pay?.wx_appid
        MyConstant.WX_APPKEY = wxObj?.pay?.wx_appkey
        MyConstant.WX_SHARE_APPID = wxObj?.share?.wx_appid
        MyConstant.WX_SHARE_APPKEY = wxObj?.share?.wx_appkey
        MyConstant.wx_status = mNovelInitEntity.pay_config?.wx?.status ?: 0
        MyConstant.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")
                        AdPreference.setToken(token)
                    } else {
                        EventUtils.onEvent("SplashPresenter_deviceLogin_fail")
                        AdPreference.setToken("")
                    }
                    getUserInfo()
                }

                override fun onFailure(e: Throwable, code: String, errorMsg: String?) {
                    EventUtils.onEvent("SplashPresenter_deviceLogin_fail")
                    if (!TextUtils.equals(code, "200")) {
                        MyConstant.Param.uid = ""
                        MyConstant.Param.token = ""
                        AdPreference.setUid("")
                        AdPreference.setToken("")
                        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")
                        SettingPreference.saveUserInfo(result)
                        SettingPreference.setTrackId(result.gaodeTrackId ?: 0L)
                        SettingPreference.setTerminalId(result.gaodeTerminalId ?: 0L)
                        AdPreference.setUid(uid)
                    }
                    mView.jumpPage()
                }

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