package com.ypsx.yppos.jobs

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import com.ypsx.base.base.appContext
import com.ypsx.yppos.R
import com.ypsx.yppos.http.repository.request.HttpRequestCoroutine
import com.ypsx.yppos.room.entity.PosConfig
import com.ypsx.yppos.room.repository.PosConfigRepository
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

/**
 * 同步商品的任务
 */
class SyncProductService: Service() {
    var posConfig: PosConfig? = null
    var job: Job? = null

    companion object {

        var starter: Intent? = null

        fun start(context: Context) {
            if (starter == null){
                starter = Intent(context, SyncProductService::class.java)
            }
            context.startService(starter)
        }

        fun stop(context: Context) {
            starter?.let {
                context.stopService(starter)
            }
        }
    }
    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        posConfig = PosConfigRepository.getInstance().loadConfig()
        job = GlobalScope.launch {
            val storeId = posConfig?.storeId!!
            HttpRequestCoroutine.syncProduct(storeId)
        }

    }


    override fun onDestroy() {
        super.onDestroy()
        job?.cancel()
        stopForeground(true)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        createEmptyNotification()
        return super.onStartCommand(intent, flags, startId)
    }

    private fun createEmptyNotification() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            var channel = NotificationChannel(
                "CHANNEL_ID", "CHANNEL_NAME",
                NotificationManager.IMPORTANCE_MIN
            )
            val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            manager.createNotificationChannel(channel)
            val notification =
                Notification.Builder(appContext, "CHANNEL_ID")
                    .setContentTitle("后台服务")
                    .setSmallIcon(R.drawable.icon_yp_logo)
                    .setOnlyAlertOnce(true)
                    .build()
            startForeground(1, notification)
//            startForeground(1, new Notification());
        }
    }
}