package com.za.common

import android.app.Application
import com.amap.api.location.AMapLocation
import com.blankj.utilcode.util.AppUtils
import com.tencent.mmkv.MMKV
import com.za.bean.db.order.OrderInfo
import com.za.common.log.LogUtil
import com.za.room.RoomHelper
import com.za.room.db.user.DriverInfoBean

object GlobalData {
	lateinit var application : Application
	private val mmkv : MMKV by lazy { MMKV.defaultMMKV() }
	var activityCount : Int = 0
	var isMaster = AppUtils.getAppPackageName() == "com.za.rescue.dealer"

	var token : String? = null
		get() {
			return mmkv.decodeString("ZD_TOKEN", null)
		}
		set(value) {
			mmkv.encode("ZD_TOKEN", value)
			field = value
		}

	var regid : String? = null
		get() {
			return mmkv.decodeString("regid", null)
		}
		set(value) {
			mmkv.encode("regid", value)
			field = value
		}

	var aesKey : String? = null
		get() {
			return mmkv.decodeString("AES_KEY", null)
		}
		set(value) {
			mmkv.encode("AES_KEY", value)
			field = value
		}

	//新订单是否已经被处理
	var isHandlerNewOrder : Boolean? = false

	private val lock = Any()
	var driverInfoBean : DriverInfoBean?
		get() {
			synchronized(lock) {
				val driverInfoBean =
					mmkv.decodeParcelable("driverInfoBean", DriverInfoBean::class.java)
				LogUtil.print("driverInfo get", "driverInfoBean = $driverInfoBean")
				return driverInfoBean
			}
		}
		set(value) {
			synchronized(lock) {
				mmkv.encode("driverInfoBean", value)
				if (value != null) {
					lastLoginBean = value
				}
				LogUtil.print("driverInfo set", "driverInfoBean = $value")
			}
		}

	var lastLoginBean : DriverInfoBean? = null
		get() {
			val driverInfoBean = mmkv.decodeParcelable("lastLoginBean", DriverInfoBean::class.java)
			field = driverInfoBean
			return driverInfoBean
		}
		set(value) {
			mmkv.encode("lastLoginBean", value)
		}

	var currentOrder : OrderInfo? = null
		get() {
			return mmkv.decodeParcelable("currentOrder", OrderInfo::class.java)
		}
		set(value) {
			mmkv.encode("currentOrder", value)
			if (RoomHelper.db?.orderDao()?.getCurrentOrder() == null && value != null) {
				RoomHelper.db?.orderDao()?.insertOrder(value)
			} else if (value != null) {
				RoomHelper.db?.orderDao()?.update(value)
			}
			field = value
		}

	var currentLocation : AMapLocation? = null
		get() {
			return field
		}
		set(value) {
			value?.time = System.currentTimeMillis()
			field = value
		}

	var loginTime : Long? = null
		get() {
			return mmkv.decodeLong("loginTime", System.currentTimeMillis())
		}
		set(value) {
			mmkv.encode("loginTime", value ?: System.currentTimeMillis())
			field = value
		}

	fun clearUserCache() {
		token = null
		aesKey = null
		currentLocation = null
		driverInfoBean = null
		loginTime = null
	}

	fun clearAllOrderCache() {
		currentOrder = null
		RoomHelper.clearAll()
	}

	fun clearOrderCache(taskId : Int) {
		RoomHelper.clearOrderFromTaskCode(taskId = taskId)
	}

}