package com.za.offline


import android.annotation.SuppressLint
import android.content.Context
import android.graphics.PixelFormat
import android.os.Build
import android.view.GestureDetector
import android.view.GestureDetector.OnGestureListener
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.blankj.utilcode.util.ActivityUtils
import com.za.base.theme.headBgColor
import com.za.room.RoomHelper

@SuppressLint("StaticFieldLeak")
object OfflineService : IOfflineListener {
	private var viewcompose : View? = null
	private var lifecycleOwner : MyOfflineServiceViewLifecycleOwner? = null
	private var windowManager : WindowManager? = null
	private var layoutParams : WindowManager.LayoutParams? = null
	private var currentOfflineUpdateTaskBean = mutableStateOf<OfflineUpdateTaskBean?>(null)
	private var state = mutableIntStateOf(0) //0 初始化 1 准备上传  2 结束上传  3上传中 4 上传失败  5 上传完成

	private var onGestureListener =
		GestureDetector(ActivityUtils.getTopActivity().application, object : OnGestureListener {
			var xDown : Int = 0
			var yDown : Int = 0
			override fun onDown(motionEvent : MotionEvent) : Boolean {
				xDown = motionEvent.rawX.toInt()
				yDown = motionEvent.rawY.toInt()
				return false
			}

			override fun onShowPress(e : MotionEvent) {

			}

			override fun onSingleTapUp(e : MotionEvent) : Boolean {
				val context = ActivityUtils.getTopActivity()
				return true
			}

			override fun onScroll(e1 : MotionEvent?,
				motionEvent : MotionEvent,
				distanceX : Float,
				distanceY : Float) : Boolean {
				val nowX = motionEvent.rawX.toInt()
				val nowY = motionEvent.rawY.toInt()
				val movedX = nowX - xDown
				val movedY = nowY - yDown
				xDown = nowX
				yDown = nowY
				layoutParams?.apply {
					x += movedX
					y += movedY
				} //更新悬浮球控件位置
				updateView()
				return true
			}

			override fun onLongPress(e : MotionEvent) {

			}

			override fun onFling(e1 : MotionEvent?,
				e2 : MotionEvent,
				velocityX : Float,
				velocityY : Float) : Boolean {

				return true
			}
		})

	init {
		windowManager =
			ActivityUtils.getTopActivity().getSystemService(Context.WINDOW_SERVICE) as WindowManager
		layoutParams = WindowManager.LayoutParams()
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
			layoutParams?.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
		} else {
			layoutParams?.type = WindowManager.LayoutParams.TYPE_PHONE
		}
		layoutParams?.format = PixelFormat.RGBA_8888
		layoutParams?.width = ViewGroup.LayoutParams.WRAP_CONTENT
		layoutParams?.height = ViewGroup.LayoutParams.WRAP_CONTENT
		layoutParams?.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
	}

	fun addListener() {
		OfflineManager.addOfflineListener(this)
	}

	@SuppressLint("ClickableViewAccessibility")
	private fun showWindow() {
		destroyView()
		viewcompose = ComposeView(ActivityUtils.getTopActivity().application).apply {
			setContent {
				MyOfflineServiceView(currentOfflineUpdateTaskBean.value, state = state.intValue)
			}
		}.rootView

		viewcompose?.setOnTouchListener { _, event ->
			onGestureListener.onTouchEvent(event)
			if (event.action == MotionEvent.ACTION_UP) {
			}
			true
		}

		lifecycleOwner = MyOfflineServiceViewLifecycleOwner().also {
			it.onCreate() // 注意
			it.onStart()
			it.attachToDecorView(viewcompose)
		}
		windowManager?.addView(viewcompose, layoutParams)
	}

	private fun destroyView() {
		viewcompose?.let {
			windowManager?.removeViewImmediate(viewcompose)
		}
		viewcompose = null
		lifecycleOwner?.onDestroy()
		lifecycleOwner = null
	}

	private fun updateView() {
		windowManager?.updateViewLayout(viewcompose, layoutParams)
	}

	override fun start() {
		showWindow()
		state.intValue = 1
	}

	override fun stop() {
		destroyView()
	}

	override fun uploadSuccess() {
		state.intValue = 4
	}

	override fun uploadFailure(msg : String?) {
		state.intValue = 3
	}

	override fun currentTask(offlineUpdateTaskBean : OfflineUpdateTaskBean) {
		state.intValue = 2
		currentOfflineUpdateTaskBean.value = offlineUpdateTaskBean
	}
}


//0 初始化 1 准备上传  2 上传中  3 上传失败  4 上传完成
@Composable
fun MyOfflineServiceView(offlineUpdateTaskBean : OfflineUpdateTaskBean?, state : Int) {
	Column(modifier = Modifier
		.fillMaxWidth()
		.background(color = Color.White, shape = RoundedCornerShape(8.dp))
		.border(border = BorderStroke(width = 1.dp, color = Color.Red),
			shape = RoundedCornerShape(8.dp))
		.padding(10.dp)) {

		Row(verticalAlignment = Alignment.CenterVertically) {
			Text("离线订单:", color = Color.Gray, fontSize = 15.sp)
			Spacer(modifier = Modifier.width(5.dp))
			Text(offlineUpdateTaskBean?.taskCode ?: "",
				color = Color.Black,
				fontWeight = FontWeight.Bold)
		}

		Spacer(modifier = Modifier.height(10.dp))

		Row(verticalAlignment = Alignment.CenterVertically) {
			Text("剩余任务:", color = Color.Gray, fontSize = 15.sp)
			Spacer(modifier = Modifier.width(5.dp))
			Text("${
				RoomHelper.db?.offlineTaskDao()
					?.getOfflineTaskFromTaskId(offlineUpdateTaskBean?.taskId ?: 0)?.size
			}", color = Color.Black, fontWeight = FontWeight.Medium)
		}
		Spacer(modifier = Modifier.height(10.dp))

		Row(modifier = Modifier.fillMaxWidth(),
			verticalAlignment = Alignment.CenterVertically,
			horizontalArrangement = Arrangement.Start) {
			Text("当前节点:", color = Color.Gray, fontSize = 15.sp)
			Spacer(Modifier.width(5.dp))
			Text(offlineUpdateTaskBean?.offlineTitle ?: "",
				color = Color.Black,
				fontWeight = FontWeight.Bold,
				fontSize = 15.sp,
				maxLines = 1,
				overflow = TextOverflow.Ellipsis)

			when (state) {
				1 -> {
					Spacer(modifier = Modifier.weight(1f))
					Text("准备上传",
						color = headBgColor,
						fontSize = 12.sp,
						fontWeight = FontWeight.Bold)
					Spacer(modifier = Modifier.width(5.dp))
				}

				2 -> {
					Spacer(modifier = Modifier.weight(1f))
					Text("上传中",
						color = headBgColor,
						fontSize = 12.sp,
						fontWeight = FontWeight.Bold)
					Spacer(modifier = Modifier.width(3.dp))
					CircularProgressIndicator(modifier = Modifier.size(12.dp), color = headBgColor)
					Spacer(modifier = Modifier.width(5.dp))
				}

				3 -> {
					Spacer(modifier = Modifier.weight(1f))
					Text("上传失败",
						color = Color.Red,
						fontSize = 12.sp,
						fontWeight = FontWeight.Bold,
						maxLines = 1,
						overflow = TextOverflow.Ellipsis)
					Spacer(modifier = Modifier.width(5.dp))
				}

				4 -> {
					Spacer(modifier = Modifier.weight(1f))
					Text("上传完成",
						color = headBgColor,
						fontSize = 12.sp,
						fontWeight = FontWeight.Bold,
						maxLines = 1,
						overflow = TextOverflow.Ellipsis)
					Spacer(modifier = Modifier.width(5.dp))
				}
			}
		}
	}
}