package com.xty.common.weight

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.core.content.ContextCompat
import com.tamsiree.rxkit.RxTimeTool
import com.xty.common.R
import com.xty.common.SizeUtil
import com.xty.network.model.SleepBean
import com.xty.network.model.SleepCompareBean
import java.text.SimpleDateFormat

class SleepInfoView(context: Context, attrs: AttributeSet?) : View(context, attrs) {

    val mapStatus by lazy{ mapOf(   0xF1 to "深睡",0xF2 to "浅睡",999 to "清醒")}
    val stringArray by lazy{ arrayOf( "深睡", "浅睡", "清醒") }
    private var textSizeNow=0f
    private var pressConfirm = false
    private var allNum = 0
    private var listValue = mutableListOf<SleepBean.Value>()
    private  var clickX = 0f
    init {
        val obtain = context.obtainStyledAttributes(attrs, R.styleable.SleepInfoView)
        textSizeNow = obtain.getDimensionPixelSize(R.styleable.SleepInfoView_sleep_text, 0).toFloat()
        obtain.recycle()
    }


    private val paintLoad by lazy {
        Paint().apply {
            this.isAntiAlias = true
            this.isDither = true
            this.strokeWidth = 10f
            this.color = ContextCompat.getColor(getContext(), R.color.transparent_50)

        }
    }
    private val paintLight by lazy {
        Paint().apply {
            this.isAntiAlias = true
            this.isDither = true
            this.strokeWidth = 10f
            this.color = ContextCompat.getColor(getContext(), R.color.end_col)

        }
    }

    private val paintSleep by lazy {
        Paint().apply {
            this.isAntiAlias = true
            this.isDither = true
            this.strokeWidth = 10f
            this.color = ContextCompat.getColor(getContext(), R.color.start_col)
        }
    }

    /**
     * 文字描述
     */
    private val paintText by lazy {
        Paint().apply {
            this.isAntiAlias = true
            this.isDither = true
            this.strokeWidth = 10f
            this.textSize=textSizeNow
            this.color = ContextCompat.getColor(getContext(), R.color.col_455)
        }
    }

    private val pointLin by lazy{
        Paint().apply {
            this.isAntiAlias = true
            this.isDither = true
            this.strokeWidth = 2f
            this.style=Paint.Style.STROKE
            this.pathEffect= DashPathEffect(floatArrayOf(5f,10f),0f )
            this.color = ContextCompat.getColor(getContext(), R.color.white)
        }
    }

    override fun onDraw(canvas: Canvas) {
        var allWidth = width
        var rect = RectF()
        var startWidth = 0f
        var eneWidth = 0f
        canvas.drawColor(Color.WHITE)

        var txtHeight=paintText.fontMetrics.descent-paintText.fontMetrics.ascent
        canvas.drawRect(rect, paintSleep)
        var measureText = 0f
        for (s in stringArray) {
            paintSleep.color= ContextCompat.getColor(context, R.color.col_C7C)
            paintSleep.textSize = SizeUtil.sp2pxF(context,11f); // 设置文字大小
            var top =0f
            when (s){
                "深睡" -> {top = 2*txtHeight

                }
                "浅睡" ->
                {top = (2*txtHeight+100f)
                }
                "清醒" -> {
                    top = (2*txtHeight+200f)
                }
            }
            measureText = paintSleep.measureText(s);
            canvas.drawText(s, 0f, top, paintSleep);
        }
        startWidth = (1.5f* measureText)
        allWidth -= startWidth.toInt()
        eneWidth =startWidth
        listValue.forEachIndexed {index, bean ->
            var precent = bean.sleepLen / allNum.toFloat()
            eneWidth += allWidth * precent
            when(bean.sleepType){
                0xF1->{//241 深睡
                    rect.set(startWidth, 2*txtHeight, eneWidth, height.toFloat())
                    paintSleep.color= ContextCompat.getColor(context, R.color.col_72d)
                    canvas.drawRect(rect, paintSleep)
                }
                0xF2->{//242 浅睡
                    paintSleep.color= ContextCompat.getColor(context, R.color.col_d2fbef)
                    rect.set(startWidth,  2*txtHeight + 100f, eneWidth, height.toFloat())
                    canvas.drawRect(rect, paintSleep)
                }
                999->{//清醒
                    paintSleep.color= ContextCompat.getColor(context, R.color.col_9BD)
                    rect.set(startWidth,  2*txtHeight + 200f, eneWidth, height.toFloat())
                    canvas.drawRect(rect, paintSleep)
                }
            }


            if(pressConfirm){
                if(clickX<eneWidth&&clickX>startWidth){
                    var endTime=getRealTime(bean.sleepStartTime)+bean.sleepLen*1000
                    var endTimeStr=RxTimeTool.milliseconds2String(endTime, SimpleDateFormat("HH:mm"))
                    var startStr=RxTimeTool.milliseconds2String(getRealTime(bean.sleepStartTime), SimpleDateFormat("HH:mm"))

                    var showTxt="$startStr-$endTimeStr ${mapStatus[bean.sleepType]}"
                    var textW=paintText.measureText(showTxt)
                    //因为顶部留了2个文字的高度所以中间值
                    var textBaseLine=txtHeight-(txtHeight/2-paintText.fontMetrics.descent)
                    canvas.drawText(showTxt, allWidth/2-textW/2,textBaseLine,paintText)

                    var rect1 = RectF(startWidth,2*txtHeight,eneWidth,height.toFloat())
                    canvas.drawRect(rect1,paintLoad)
                    canvas.drawLine(startWidth+(eneWidth-startWidth)/2,2*txtHeight,startWidth+(eneWidth-startWidth)/2,height.toFloat(),pointLin)
                }
            }
            startWidth = eneWidth
        }

    }

    override fun dispatchTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                pressConfirm=true
                clickX = event.x
                invalidate()
                parent.requestDisallowInterceptTouchEvent(true)
            }
            MotionEvent.ACTION_MOVE -> {
                pressConfirm = true
                clickX=event.x
                invalidate()
                parent.requestDisallowInterceptTouchEvent(true)
            }
            MotionEvent.ACTION_UP ->{
                pressConfirm = false
                invalidate()
                parent.requestDisallowInterceptTouchEvent(false)
            }
        }
        return super.dispatchTouchEvent(event)
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        return pressConfirm
    }

    fun setData(allNum: Int, listValue:MutableList<SleepBean.Value> ) {
        this.allNum = allNum
        this.listValue = listValue
        invalidate()
    }
    fun setData(allNum: Int, listValue:MutableList<SleepCompareBean.ModelDayItem> ,type:Int) {
        this.listValue.clear()
        this.allNum = allNum
//        this.listValue = listValue
        this.listValue.addAll(listValue.map { modelDayItem ->
            SleepBean.Value(
                sleepLen = modelDayItem.sleepLen,
                sleepStartTime = modelDayItem.sleepStartTime,
                sleepType = modelDayItem.sleepType
            )
        })
        invalidate()
    }


    /**
     * 修正数据 这里需要使用 毫秒数
     */
    private fun getRealTime(time:Long):Long {
        if(time>9999999999){
            return time
        }
        return  time*1000

    }

}