package com.yidian.shenghuoquan.newscontent.ui

import android.Manifest
import android.content.Intent
import android.os.Bundle
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.orhanobut.hawk.Hawk
import com.tbruyelle.rxpermissions3.RxPermissions
import com.yidian.common.AppConfig
import com.yidian.common.HawkConfig
import com.yidian.common.XRouterPathConstants
import com.yidian.common.XRouterPathConstants.Companion.NEWS_MAIN
import com.yidian.common.YdBaseApplication
import com.yidian.common.base.BaseActivity
import com.yidian.shenghuoquan.newscontent.R
import com.yidian.shenghuoquan.newscontent.audio.AudioService
import com.yidian.shenghuoquan.newscontent.bean.FeedbackBean
import com.yidian.shenghuoquan.newscontent.databinding.ActivityMainBinding
import com.yidian.shenghuoquan.newscontent.http.ApiService
import com.yidian.shenghuoquan.newscontent.http.httpbean.PushTokenAndroidBean
import com.yidian.shenghuoquan.newscontent.service.DeepLinkService
import com.yidian.shenghuoquan.newscontent.service.UniversalService
import com.yidian.shenghuoquan.newscontent.ui.popwindow.FeedbackPopupWindow
import com.yidian.common.utils.ToolsUtil
import com.yidian.utils.ToastUtil
import com.yidian.xarc.xbase.utils.XLogger
import com.yidian.xarc.xevent.XBaseEvent
import com.yidian.xarc.xevent.XEventManager
import com.yidian.xpage.XPageManager
import com.yidian.yac.core.zap.ZapTicket
import com.yidian.yac.ftdevicefinger.core.FtDeviceFingerManager
import com.yidian.yac.pm.appupdate.AppUpdateEchoData
import com.yidian.yac.pm.appupdate.AppUpdateInfo
import com.yidian.yac.pm.appupdate.PmUpdateApp
import com.yidian.yac.pm.appupdate.YDAppUpdateManager
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject


class MainActivity : BaseActivity<ActivityMainBinding>() {
    override fun getXPageName(): String {
        return NEWS_MAIN
    }

    override fun createViewBinding(): ActivityMainBinding {
        return ActivityMainBinding.inflate(layoutInflater)
    }

    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)
        XEventManager.register(this)
        getIntentData(intent)
        getPermissions()
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        getIntentData(intent)
    }

    private fun getIntentData(intent: Intent?) {
        val paramsMap = intent?.getSerializableExtra(XRouterPathConstants.ParamsKey)
        if (paramsMap != null) {
            paramsMap as HashMap<String, Any?>
            when(paramsMap["jumpFrom"]){
                "DeepLink" -> {
                    val paramsJson = JSONObject(paramsMap["deepData"] as String)
                    ZapTicket(DeepLinkService.serviceName).withAction(DeepLinkService.serviceName).withServiceParams(paramsJson).onResult {

                    }.onLost {

                    }.ship()
                }
                "PushJump" -> {
                    XPageManager.push(XRouterPathConstants.NEWS_CONTENT, paramsMap)
                }
            }
        }
    }

    private fun getPermissions() {
        val rxPermissions = RxPermissions(this)
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE)
            .subscribe {
                if (it) {
                    initUpdateManage()
                    checkUpdate()
                    bindPushToken()
                } else {
                    ToastUtil.showToast(this, "请在设置里同意读取存储卡权限")
                }
            }
    }

    private fun initUpdateManage() {
        val logger = XLogger("apkupdate")
        logger.debugOn(true)
        YDAppUpdateManager.init(PmUpdateApp(YdBaseApplication.context) {
            online = false//线上true、线下false
            platformId = 27//平台Id需要申请
            platform = "Android"//ios/Androiid
            appId = "com.yidian.subway"//应用包名
            appVersion = AppConfig.cv//客户端版本号
            deviceFinger = FtDeviceFingerManager.getDeviceFinger()//设备指纹
            androidChannel = AppConfig.distribution//渠道
            this.logger = logger.subLogger("apkupdate")
        })
    }

    private fun checkUpdate() {
        val jsonObject = JSONObject()
        ZapTicket(UniversalService.serviceName).withAction("checkNewVersion").withServiceParams(jsonObject).withServiceOptions(jsonObject).onResult {
            val updateInfo = Gson().fromJson<AppUpdateInfo<AppUpdateEchoData>>(it.result.toString(), object : TypeToken<AppUpdateInfo<AppUpdateEchoData>>() {}.type)
            compareVersion(updateInfo)
        }.ship()
    }

    private fun compareVersion(updateInfo: AppUpdateInfo<AppUpdateEchoData>) {
        if (updateInfo.hasUpdate) {
            val forceUpdate = updateInfo.echo_data?.force_update
            if (forceUpdate == true) {
                val jsonObject = JSONObject()
                ZapTicket(UniversalService.serviceName).withAction("popNewVersion")
                    .withServiceParams(jsonObject).withServiceOptions(jsonObject).ship()
            }
        }
    }

    private fun bindPushToken() {
        val encryptionToken = ToolsUtil.getYDEncryptionToken()
        val pushLevel = AppConfig.PUSH_LEVEL+ToolsUtil.getDeviceBrandMask()
        if (null != Hawk.get<String>(HawkConfig.UmToken)) {
            val requestParams = HashMap<String, String?>()
            requestParams["old_token"] = ""
            requestParams["new_token"] = encryptionToken
            requestParams["personalRec"] = "1"
            requestParams["enable"] = "1"
            requestParams["push_key"] = Hawk.get(HawkConfig.UmToken)
            requestParams["push_level"] = pushLevel.toString()
            ApiService.pushTokenAndroid(requestParams)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        //音频的生命周期与MainActivity绑定,当activity销毁时停止播放音频
        stopService(Intent(this, AudioService::class.java))
        XEventManager.unRegister(this)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == 1) {
            ToastUtil.showToast(this, data?.getStringExtra("token"))
        }
    }

    @Subscribe(sticky = false, threadMode = ThreadMode.MAIN)
    fun onEvent(event: XBaseEvent?) {
        when (event?.name) {
            "loginStatus" -> Hawk.put(HawkConfig.LoginStatus, true)
        }
    }
}