package com.yidian.common.services

import android.os.Handler
import android.os.Message
import com.yidian.common.widget.CommonHintDialog
import com.yidian.xarc.xbase.net.CheckUpdateCallback
import com.yidian.xarc.xrouter.ResultResolver
import com.yidian.xpage.observer.DStackActivityManager
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 java.io.File
import java.lang.StringBuilder

/**
 * author: yinjiacheng
 * date: 6/30/21 3:29 PM
 * description: App升级服务
 */
class AppUpgradeService : ZapService(), CommonHintDialog.OnHintOptionCallback, Handler.Callback {

  companion object {
    private const val TAG = "AppUpgradeService"
    const val SERVICE_NAME = "AppUpgradeService"

    // 外部调用服务action 检查app升级
    const val ACTION_CHECK_APP_UPGRADE = "checkAppUpgrade"

    // 外部调用服务action 下载apk
    const val ACTION_DOWNLOAD_APK = "downloadApk"

    // app需要升级
    private const val MSG_APP_NEED_UPGRADE = 101

    // app无需升级
    private const val MSG_APP_UP_TO_DATE = 102

    // app检测更新失败
    private const val MSG_APP_CHECK_UPGRADE_ERROR = 103
  }

  /**
   * app升级信息
   */
  private lateinit var appUpdateInfo: AppUpdateInfo<AppUpdateEchoData>
  private lateinit var resolver: ResultResolver
  private lateinit var handler: Handler

  override fun onAction(path: String, action: String, params: Any, options: Any, resolver: ResultResolver) {
    this.resolver = resolver
    when (action) {
      ACTION_CHECK_APP_UPGRADE -> {
        checkAppUpgrade()
      }
      ACTION_DOWNLOAD_APK -> {
        downloadApk()
      }
    }
  }

  override fun onExit() {

  }

  override fun onInit() {
    handler = Handler(this)
  }

  /**
   * 检查App升级
   */
  private fun checkAppUpgrade() {
    YDAppUpdateManager.checkAppUpdate(object : CheckUpdateCallback() {
      override fun onSucess(updateInfo: UpdateInfo<Any>?) {
        appUpdateInfo = updateInfo as AppUpdateInfo<AppUpdateEchoData>
        if (!appUpdateInfo.hasUpdate) {
          // 无需升级
          handler.sendEmptyMessage(MSG_APP_UP_TO_DATE) // 切换到主线程
        } else {
          handler.sendEmptyMessage(MSG_APP_NEED_UPGRADE)
        }
      }

      override fun onFail(msg: String) {
        handler.sendEmptyMessage(MSG_APP_CHECK_UPGRADE_ERROR)

      }
    })
  }

  /**
   * 下载安装包
   */
  private fun downloadApk() {
    YDAppUpdateManager.download(appUpdateInfo, object : AppUpdateCallback() {
      override fun onProgress(total: Long, current: Long, percentage: Int) {
//        Log.d(TAG, "progress, total: $total, current: $current, percentage: $percentage")
      }

      override fun onDownloadSuccess(apkFile: File, isCache: Boolean) {
        //参数1.安装包的地址 2. 是否是已缓存的安装包
//        Log.d(TAG, "apkFile: $apkFile, isCache: $isCache")
      }

      override fun onDownloadFailed() {
      }

      override fun onDownloadPaused() {

      }

      override fun onInstallFailed() {

      }

      override fun onSignatureVerifiyFailed() {

      }
    }, true)
  }

  /**
   * 展示升级弹窗
   */
  private fun showAppUpgradeDialog(data: AppUpdateInfo<AppUpdateEchoData>) {
    // 版本更新信息
    val content = StringBuilder().append("检测到版本更新").append("\n").append(data.result?.get(0)?.package_version).append("\n")
      .append(data.result?.get(0)?.update_time).append("\n").append(data.result?.get(0)?.note).toString()
    if (data.echo_data?.force_update == true) {
      // 强制升级
      CommonHintDialog(DStackActivityManager.getInstance().topActivity, content, arrayListOf("立即升级"), this).show()
    } else {
      // 非强制升级
      CommonHintDialog(DStackActivityManager.getInstance().topActivity, content, arrayListOf("取消", "立即升级"), this).show()
    }
  }

  override fun onLeftOption() {
    // 取消
  }

  override fun onRightOption() {
    // 立即升级
    downloadApk()
  }

  override fun handleMessage(msg: Message): Boolean {
    when (msg.what) {
      MSG_APP_NEED_UPGRADE -> {
        // 展示升级弹窗
        showAppUpgradeDialog(appUpdateInfo)
      }
      MSG_APP_UP_TO_DATE -> {
        resolver.fail(-1, null, "已是最新版本")
      }
      MSG_APP_CHECK_UPGRADE_ERROR -> {
        resolver.fail(-2, null, "检测更新失败，请稍后重试")
      }
    }
    return true
  }
}
