package com.xhly.manageapp.workmanager

import android.app.usage.UsageEvents
import android.app.usage.UsageStatsManager
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.xhly.corelib.Const
import com.xhly.corelib.eventbus.UIEvent
import com.xhly.corelib.network.RetrofitService
import com.xhly.corelib.utils.AppUtils
import com.xhly.corelib.utils.LogShow
import com.xhly.corelib.utils.SharedPreferencesUtils
import com.xhly.corelib.utils.SystemUtil
import com.xhly.corelib.utils.toFormat
import com.xhly.manageapp.ManageApplication
import com.xhly.manageapp.bean.PadLocationConst
import com.xhly.manageapp.bean.log.LogAppStartBean
import com.xhly.manageapp.bean.log.PadLocationBean
import com.xhly.manageapp.bean.user.UserBean
import com.xhly.manageapp.network.log.LogService
import com.xhly.manageapp.service.websocket.AppSocket
import com.xhly.manageapp.ui.login.netservice.LoginService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.util.Calendar

/**
 * 用来记录应用使用时长的定时任务
 */
class TimingWorker(context: Context, workerParams: WorkerParameters) :
    Worker(context, workerParams) {
    private val loginService by lazy { RetrofitService.create<LoginService>() }
    private val logService by lazy {  RetrofitService.create<LogService>() }
    private val serviceScope = CoroutineScope(MainScope().coroutineContext)
    private val spUtils by lazy {
        SharedPreferencesUtils.getInstance(context)
    }

    companion object{
        private var lastTime=0L
    }

    override fun doWork(): Result {
        val result: Result = Result.success()
        serviceScope.launch {
            LogShow("执行定时任务吧")
            var userBean:UserBean?=null
            try {
                val fromJson = spUtils.getFromJson(Const.USERINFO, UserBean().javaClass)
                userBean= fromJson as UserBean?
            }catch (e:Exception){

            }
            val appInfo = getAppInfo()
            if (appInfo.size > 0) {
                logService.postLogAppStartAdd(appInfo)
            }
/*
            try {
                val location = PadLocationConst.currentLocation
                val lastLocation = PadLocationConst.lastLocation
                if (location.lat!=null&&location.lon!=null&&(lastLocation.lon!=location.lon&&lastLocation.lat!=location.lat)){
                    lastLocation.lat=location.lat
                    lastLocation.lon=location.lon
                    ManageApplication.getDeviceInfo()?.let {
                        location.sn=it
                    }
                    userBean?.let {
                        location.userid=it.userid
                    }
                    logService.postPadLocation(location)
                    LogShow("真没有位置")
                }else{
                    LogShow("没有位置")
                }
            }catch (e:Exception){
                LogShow("没有位置问题"+e.toString())
            }
*/
            UIEvent(Const.STARTLOCATION).post()
            userBean?.let {
                val map=HashMap<String,Any>()
                map["sn"]=ManageApplication.getDeviceInfo()?:""
                val postCheckSn = loginService.postCheckSn(map)
                if (postCheckSn.code==0&&postCheckSn.obj){
                    UIEvent(Const.ACCOUNTLOGINOUTSUCESS).post()
                }
            }
            //创建socket
            userBean?.let {
                ManageApplication.instance?.let {
                    AppSocket.startSocket(it)
                }
            }
            //TODO 暂时注销登录校验
            //校验登录
          /*  userBean?.let {
                val map=HashMap<String,Any>()
                map["userid"]=userBean.userid
                map["loginpwd"]=userBean.loginpwd
                val postLoginCheck = loginService.postLoginCheck(map)
                if (postLoginCheck.code==0&&postLoginCheck.obj.needLogin){
                    UIEvent(Const.ACCOUNTLOGINOUT).post()
                }
            }*/
        }
        return result
    }

    private fun getAppInfo(): ArrayList<LogAppStartBean> {
        //统计使用时长
        val dataList = AppUtils.GetAppList(applicationContext)
        val instance = Calendar.getInstance()
        instance.set(Calendar.MILLISECOND, 0)
        val currentTime = instance.timeInMillis
        if (lastTime==0L){
            lastTime=currentTime
        }else{
            LogShow("上次时间"+ lastTime.toFormat()+"|||本次时间"+currentTime.toFormat())
            lastTime=currentTime
        }
        val timeInMillis = currentTime - 1000 * 60 * 5
        val usageManager =
            applicationContext.getSystemService(AppCompatActivity.USAGE_STATS_SERVICE) as UsageStatsManager
        val startList = arrayListOf<LogAppStartBean>()
        val sn = ManageApplication.getDeviceInfo()
        if (usageManager != null) {
            val endTime = System.currentTimeMillis()
            val startTime = timeInMillis
            //queryEvents查询使用时长，时间范围设置后，返回的数据时间范围和设置的一致，但需要自己判断时长
            val queryEvents = usageManager.queryEvents(startTime, endTime)
            val event = UsageEvents.Event()

            while (queryEvents.hasNextEvent()) {
                queryEvents.getNextEvent(event)
                when (event.eventType) {
                    UsageEvents.Event.ACTIVITY_RESUMED -> {
                        val appStartBean = LogAppStartBean()
                        val first =
                            dataList.firstOrNull { event.packageName.equals(it.packageName) }
                        first?.let {
                            sn?.let {
                                appStartBean.sn = sn
                            }
                            appStartBean.appName = first.name
                            appStartBean.appPackage = first.packageName
                            appStartBean.starttime = event.timeStamp.toFormat()
                            appStartBean.ltype = 1
                            appStartBean.versionName = first.versionName
                            appStartBean.versionNum = first.versionNum
                            startList.add(appStartBean)
                        }
                    }

                    UsageEvents.Event.ACTIVITY_PAUSED -> {
                        val appStartBean = LogAppStartBean()
                        var first =
                            dataList.firstOrNull { event.packageName.equals(it.packageName) }
                        first?.let {
                            sn?.let {
                                appStartBean.sn = sn
                            }
                            appStartBean.appName = first.name
                            appStartBean.appPackage = first.packageName
                            appStartBean.starttime = event.timeStamp.toFormat()
                            appStartBean.ltype = 2
                            appStartBean.versionName = first.versionName
                            appStartBean.versionNum = first.versionNum
                            startList.add(appStartBean)
                        }
                    }
                }
            }
        }
        return startList
    }

    override fun onStopped() {
        super.onStopped()
        try {
            serviceScope.cancel()
        } catch (e: Exception) {

        }
    }
}