package com.zj365.health.weight

import android.content.Context
import android.graphics.Color
import android.provider.CalendarContract.Colors
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.google.android.exoplayer2.util.ColorParser
import com.xty.common.LogUtils
import com.zj365.health.R
import kotlin.math.cos
import kotlin.math.roundToInt
import kotlin.math.sin

class HealthSurveyView(context: Context, attrs: AttributeSet?) : ViewGroup(context, attrs) {


    //圆形直径
    var mRadius = 0

    //该容器内child item 的默认尺寸
    val RADIO_DEFAULT_CHILD_DIMESION = 1 /4f

    // 该容器的内边距，无视padding属性 ， 如需边距请用该变量
    val RADIO_PADDING_LAYOUT = 1 / 12f
    var mPadding = 0f

    // 布局时的开始角度
    var mStartAngle = 270.0

    //文本
    var mSurveyText = ArrayList<String>()

    var colors = arrayOf("#20C387","#FD830B","#1ECAFC")


    //数
    var mCount = 12

    var mItemLayoutId: Int = R.layout.layout_health_survey_child

    var mOnClicklistener: onItemClicked? = null
    fun setMenuItemTexts( texts: ArrayList<String>) {
        require(!( texts == null)) { "菜单文本和图标至少设置其一" }
        mSurveyText = texts
        //初始化mMenucount
        mCount = texts.size
        //构建菜单项
        buildMenuItems()
    }


    private fun buildMenuItems() {
        //根据用户设置的参数，初始化menu item
        for (i in 0 until mCount) {
            val itemView = inflateMenuView(i)
            initMenuItem(itemView, i)
            addView(itemView)
        }
    }

    private fun inflateMenuView(index: Int): View {
        val mInflater = LayoutInflater.from(context)
        val itemView: View = mInflater.inflate(mItemLayoutId, this, false)
        itemView.setOnClickListener(object : OnClickListener {
            override fun onClick(p0: View?) {
                mOnClicklistener?.onPositionClicked(index)
            }

        })
        return itemView
    }

    private fun initMenuItem(itemView: View, index: Int) {
        val tv = itemView.findViewById<TextView>(R.id.tv_survey)
        tv.text = mSurveyText[index]
        when(index){
            0,2,4,6 ->{
                tv.setTextColor(Color.parseColor(colors[0]))
            }
            1,5,7->{
                tv.setTextColor(Color.parseColor(colors[1]))
            }
            else ->{
                tv.setTextColor(Color.parseColor(colors[2]))

            }
        }
    }

    fun setMenuItemLayoutId(mItemLayoutId: Int) {
        this.mItemLayoutId = mItemLayoutId
    }

    fun setOnClicklisteners(mOnClicklistener: onItemClicked) {
        this. mOnClicklistener = mOnClicklistener
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        // 测量自己
        measureSelf(widthMeasureSpec, heightMeasureSpec)
        // 测量菜单
        measureChildViews()
    }

    private fun measureSelf(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        var resWidth = 0
        var resHeight = 0
        val width = MeasureSpec.getSize(widthMeasureSpec)
        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        val heigh = MeasureSpec.getSize(heightMeasureSpec)
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)

        //如果宽或者高的测量模式非精确值
        /* if (widthMode != MeasureSpec.EXACTLY ||
             heightMode != MeasureSpec.EXACTLY
         ) {
             //设置为背景图的宽高
             resWidth = suggestedMinimumWidth
             //如果未设置背景图，则设置为屏幕宽高的默认值
             resWidth = if (resWidth == 0) getDefaultWidth() else resWidth
             resHeight = if (resHeight == 0) getDefaultWidth() else resHeight
         } else {*/
        resHeight = Math.min(width, heigh)
        resWidth = resHeight
//        }
        setMeasuredDimension(resWidth, resHeight)
    }

    private fun getDefaultWidth(): Int {
        return (mRadius * RADIO_DEFAULT_CHILD_DIMESION).toInt()
    }

    private fun measureChildViews() {
        //获得半径
        mRadius = Math.max(measuredWidth, measuredWidth)
        //menu item 数量
        val count = childCount
        //menu 尺寸
        val childSize = (mRadius * RADIO_DEFAULT_CHILD_DIMESION).toInt()
        // menu item 测量模式
        val childMode = MeasureSpec.EXACTLY
        //迭代测量
        for (i in 0 until count) {
            val child = getChildAt(i)
            if (child.visibility == GONE) {
                continue
            }
            // 计算menu item 的尺寸 ， 以及设置好的模式，去对item进行测量
            var makeMeasureSpec = -1
            makeMeasureSpec = MeasureSpec.makeMeasureSpec(childSize, childMode)
            child.measure(makeMeasureSpec, makeMeasureSpec)
        }
//        mPadding = RADIO_PADDING_LAYOUT * mRadius
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        val childCount = childCount
        var left: Int
        var top: Int
        // menu item 的尺寸
        val itemWidth = (mRadius * RADIO_DEFAULT_CHILD_DIMESION).toInt()
        // 根据menuitem 的个数 计算item的布局占用的角度
        if(childCount > 0){
            val angleDelay = (360 / childCount).toFloat()
            // 遍历所有菜单 设置它们的位置
            for (i in 0 until childCount) {
                val child = getChildAt(i)
                if (child.visibility == GONE) {
                    continue
                }
                //菜单的起始角度
                mStartAngle %= 360.0
                //计算 中心点到menuitem 中心的距离
                val distanceFromCenter = mRadius / 2f - itemWidth / 2
                left =
                    mRadius / 2 + (distanceFromCenter * cos(Math.toRadians(mStartAngle)) - 1 / 2f * itemWidth).roundToInt()

                top =
                    mRadius / 2 + (distanceFromCenter * sin(Math.toRadians(mStartAngle)) - 1 / 2f * itemWidth).roundToInt()

                LogUtils.e("HealthSurveyView","left:${left},top:${top},itemWidth${itemWidth},mRadius:${mRadius},distanceFromCenter:${distanceFromCenter}")

                child.layout(left, top, left + itemWidth, top + itemWidth)
                mStartAngle += angleDelay.toDouble()
            }
        }

    }

    interface onItemClicked{
        fun onPositionClicked(postion:Int)
    }
}