package com.yidian.shenghuoquan.newscontent.service

import android.util.Log
import android.widget.Toast
import androidx.core.app.NotificationManagerCompat
import com.google.gson.Gson
import com.orhanobut.hawk.Hawk
import com.yidian.common.AppConfig
import com.yidian.common.HawkConfig
import com.yidian.common.XEventConfig
import com.yidian.common.YdBaseApplication
import com.yidian.common.services.XEventService
import com.yidian.shenghuoquan.newscontent.R
import com.yidian.shenghuoquan.newscontent.bean.IUpdateDialogCallback
import com.yidian.shenghuoquan.newscontent.bean.ImageItemBean
import com.yidian.shenghuoquan.newscontent.bean.xbrid.ClientInfoBean
import com.yidian.shenghuoquan.newscontent.bean.xevent.XEventOpenGalleryBean
import com.yidian.shenghuoquan.newscontent.ui.dialog.UpdateVersionDialog
import com.yidian.shenghuoquan.newscontent.utils.DataCleanManager
import com.yidian.utils.ToastUtil
import com.yidian.xarc.xbase.net.CheckUpdateCallback
import com.yidian.xarc.xevent.XBaseEvent
import com.yidian.xarc.xrouter.ResultResolver
import com.yidian.yac.core.zap.ZapService
import com.yidian.yac.pm.appupdate.AppUpdateEchoData
import com.yidian.yac.pm.appupdate.AppUpdateInfo
import com.yidian.yac.pm.appupdate.YDAppUpdateManager
import com.yidian.yac.pm.appupdate.callback.AppUpdateCallback
import com.yidian.yac.pm.base.UpdateInfo
import org.json.JSONObject
import java.io.File

class UniversalService: ZapService(){
    companion object{
        const val serviceName: String = "UniversalService"
    }

    private lateinit var resolver: ResultResolver
    private lateinit var updateInfoTemp: AppUpdateInfo<AppUpdateEchoData>

    override fun onAction(name: String, action: String, params: Any, options: Any, resolver: ResultResolver) {
        this.resolver = resolver
        params as JSONObject
        when(action){
            "makeToast" -> showToast(params)
            "openGallery" -> openGallery(params)
            "getClientInfo" -> getClientInfo()
            "getAllCache" -> getAllCache()
            "clearAllCache" -> clearAllCache()
            "notificationStatus" -> getNotificationStatus()
            "notificationOnSetting" -> notificationOnSetting()
            "checkNewVersion" -> checkUpdate()
            "popNewVersion" -> popNewVersion(updateInfoTemp)
        }
    }

    override fun onExit() {

    }

    override fun onInit() {

    }

    private fun showToast(params: JSONObject){
        val message = params.optString("message", "")
        Toast.makeText(YdBaseApplication.context, message, Toast.LENGTH_SHORT).show()
    }

    private fun openGallery(params: JSONObject){
        val index = params.optInt("index")
        val imageArray = params.optJSONArray("imageList")
        val url = params.optString("url")
        val imageList = ArrayList<ImageItemBean>()
        repeat(imageArray.length()){
            imageList.add(ImageItemBean(imageArray.get(it).toString()))
        }
        val xbaseEvent = XBaseEvent(XEventConfig.OPEN_GALLERY, XEventOpenGalleryBean(index, imageList, url))
        XEventService.postEvent(xbaseEvent)
    }

    private fun getClientInfo(){
        val userId = Hawk.get(HawkConfig.Username, "")
        val nickname = Hawk.get(HawkConfig.Nickname, "")
        val portrait = Hawk.get(HawkConfig.ProfileUrl, "")
        val loginStatus = Hawk.get(HawkConfig.LoginStatus, false)
        val userInfo = ClientInfoBean.UserInfo(userId, nickname, portrait, loginStatus)
        val appInfo = ClientInfoBean.AppInfo(AppConfig.cv)
        val clientInfoBean = ClientInfoBean(userInfo, appInfo)
        val params = Gson().toJson(clientInfoBean)
        resolver.success(JSONObject(params))
    }

    private fun getAllCache(){
        val cacheSize = DataCleanManager.getTotalCacheSizeShow(YdBaseApplication.context)
        resolver.success(cacheSize)
    }

    private fun clearAllCache(){
        Thread {
            DataCleanManager.clearAllCache(YdBaseApplication.context)
        }.start()
        resolver.success("0K")
    }

    private fun getNotificationStatus(){
        if (YdBaseApplication.activityList.size <= 0) return
        val activity = YdBaseApplication.activityList[YdBaseApplication.activityList.size-1]
        val manage = NotificationManagerCompat.from(activity)
        val isOpen = manage.areNotificationsEnabled()
        resolver.success(isOpen)
    }

    private fun notificationOnSetting(){
        val xbaseEvent = XBaseEvent(XEventConfig.OPEN_PUSH, "")
        XEventService.postEvent(xbaseEvent)
    }

    private fun checkUpdate(){
        val activity = YdBaseApplication.activityList[YdBaseApplication.activityList.size - 1]
        YDAppUpdateManager.checkAppUpdate(object: CheckUpdateCallback() {
            override fun onSucess(updateInfo: UpdateInfo<Any>?) {
                updateInfoTemp = updateInfo as AppUpdateInfo<AppUpdateEchoData>
                val jsonString = Gson().toJson(updateInfoTemp)
                val jsonObject = JSONObject(jsonString)
                jsonObject.put("localVersion", AppConfig.cv)
                activity.runOnUiThread{
                    resolver.success(jsonObject)
                }
            }

            override fun onFail(msg: String) {
                activity.runOnUiThread {
                    ToastUtil.showToast(activity, msg)
                }
            }
        })
    }

    private val updateDialogCallback = object: IUpdateDialogCallback {
        override fun downloadCallback(updateInfo: AppUpdateInfo<AppUpdateEchoData>) {
            updateDownload(updateInfo)
        }
    }

    private fun popNewVersion(updateInfo: AppUpdateInfo<AppUpdateEchoData>){
        val activity = YdBaseApplication.activityList[YdBaseApplication.activityList.size - 1]
        activity.runOnUiThread {
            val updateDialog = UpdateVersionDialog(activity, R.style.update_dialog, updateDialogCallback)
            updateDialog.setData(updateInfo)
            updateDialog.show()
        }
    }

    private fun updateDownload(updateInfo: AppUpdateInfo<AppUpdateEchoData>){
        YDAppUpdateManager.download(updateInfo, object : AppUpdateCallback() {
            override fun onProgress(total: Long, current: Long, percentage: Int) {
                Log.e("zhb-yd", "进度：========$percentage")
            }

            override fun onDownloadSuccess(apkFile: File, isCache: Boolean) {
                YDAppUpdateManager.installApk(apkFile)
            }

            override fun onDownloadFailed() {
            }

            override fun onDownloadPaused() {
            }

            override fun onInstallFailed() {
            }

            override fun onSignatureVerifiyFailed() {
            }
        }, false)
    }

}