package com.zj365.health.fragment

import android.annotation.SuppressLint
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.Typeface
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.bigkoo.pickerview.adapter.ArrayWheelAdapter
import com.contrarywind.view.WheelView
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.xty.base.fragment.BaseVmFrag
import com.zj365.health.weight.vp2.MyAdapter
import com.xty.common.*
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.audioUtils.RecordAudio
import com.xty.common.weight.tablayout.TabEntity
import com.xty.common.weight.tablayout.listener.CustomTabEntity
import com.xty.common.weight.tablayout.listener.OnTabSelectListener
import com.zj365.health.R
import com.zj365.health.act.HealthMainAct
import com.zj365.health.databinding.FragSleepNewBinding
import com.zj365.health.databinding.SleepMusicInfoBinding
import com.zj365.health.vm.SleepVm
import com.zj365.health.weight.HealthDialog
import java.io.File
import java.io.FileOutputStream
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*

/**
 * 睡眠
 */
class SleepFrag : BaseVmFrag<SleepVm>() {

    val binding by lazy { FragSleepNewBinding.inflate(layoutInflater) }
    override fun setLayout(): View = binding.root
    override fun setViewModel() = SleepVm()

    var isDemonstrate: Boolean = false
    var type = 2
    var initFrag = false

    private val musicInfoBinding by lazy { SleepMusicInfoBinding.bind(binding.root)}
    val timeDaySelect by lazy{TimeSelect(requireContext()){
        var time=binding.tvShowDate.text.toString()
        getData(time)

    }}
    val timeMonthSelect by lazy{TimeSelect(requireContext()){
        var time=binding.tvShowDate.text.toString()
        getData(time)

    }}
    val timeYearSelect by lazy{TimeSelect(requireContext()){
        var time=binding.tvShowDate.text.toString()
        getData(time)

    }}

    private fun getData(time: String) {
        val frag = getCurrentFragment()
            if (frag is SleepStaticDayFrag) {
                frag.getData(time, isDemonstrate)
            } else if (frag is BaseSleepStatisticFrag<*>) {
                frag.getData(time, isDemonstrate)
            }
    }
    fun getCurrentFragment() :Fragment{
        val currentItem = binding.mVp2.currentItem
        val frag = listFrag.get(currentItem)
        return frag
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initFrag = true
    }

    var tip =
        "睡眠判断的依据是相关体征数据的特征比对。部分用户新陈代谢较慢，脑供血不足时，在静坐平躺状态下，血压心率下降，虽然没有睡着，但是体征符合正常人睡眠状态，这个时候系统可能会误判为睡眠。同理如身体患有基础慢病，如炎症、甲亢等疾病，新陈代谢较快，即使处于睡眠过程中，系统可能会误判用户此时为浅睡或清醒。如出现app内显示睡眠时间与实际不符，请注意调整身体状态"
    val tipDialog by lazy {
        HealthDialog(requireContext(), true, tip) {
        }
    }

    var id = ""
    var listFrag = mutableListOf<Fragment>()

    val tabs = arrayOf("日", "周", "月","年")
    private val activeColor: Int = Color.parseColor("#02C191")
    private val normalColor: Int = Color.parseColor("#7C7C7C")
    private val activeSize = 15F
    private val normalSize = 15F

    private val mTabEntities: ArrayList<CustomTabEntity> = ArrayList()
    private val mTitles = arrayOf(
        "日", "周", "月", "年"
    )


    private fun initTab() {
        mTabEntities.clear()
        listFrag.clear()
        if (id.isNullOrEmpty()) {
            listFrag.add(SleepStaticDayFrag())
            listFrag.add(SleepStatisticWeekFrag())
            listFrag.add(SleepStatisticMonthFrag())
            listFrag.add(SleepStatisticYearFrag())
        } else {
            listFrag.add(setArgumentFrag(SleepStaticDayFrag(), id))
            listFrag.add(setArgumentFrag(SleepStatisticWeekFrag(), id))
            listFrag.add(setArgumentFrag(SleepStatisticMonthFrag(), id))
            listFrag.add(setArgumentFrag(SleepStatisticYearFrag(), id))
        }
        binding.mVp2.adapter = MyAdapter(this,listFrag,requireActivity(),childFragmentManager)
        binding.mVp2.isUserInputEnabled =false

        mTitles.forEach {
            mTabEntities.add(
                TabEntity(
                    it, android.R.drawable.ic_delete, android.R.drawable.ic_delete
                )
            )
        }
        binding.commonTabLayout.setTabData(mTabEntities)
        binding.commonTabLayout.setOnTabSelectListener(object : OnTabSelectListener {
            @SuppressLint("SetTextI18n")
            override fun onTabSelect(position: Int) {
                binding.commonTabLayout.currentTab = position
                binding.mVp2.setCurrentItem(position, false)

                showSelectTime()
                //这个view是的fragment。
                if (initFrag){
                    initFrag = false
                    return
                }
                val view = listFrag[position].view
                view?.let {
                    updatePagerHeightForChild(view)
                }
               /* when (position) {
                    0 -> {
                  //      binding.tvShowDate.text = dayDate
                        showSelectTime()
                    }

                    1 -> {
                    //    binding.tvShowDate.text = weekDate
                        showSelectTime()
                    }

                    2 -> {
                    //    binding.tvShowDate.text = mouthDate
                        showSelectTime()
                    }

                    3 -> {
                     //   binding.tvShowDate.text = yearDate
                        showSelectTime()
                    }
                }*/
            }

            override fun onTabReselect(position: Int) {
            }

        })

        /*binding.mVp2.post {
            binding.commonTabLayout.
        }*/

    }
    private fun initTabVp2() {
        var  mediator = TabLayoutMediator(
            binding.tabLayout, binding.mVp2
        ) { tab, position -> //这里可以自定义TabView
            LogUtils.d("TabLayoutMediator position:$position")
            val tabView = TextView(activity)
            val states = arrayOfNulls<IntArray>(2)
            states[0] = intArrayOf(android.R.attr.state_selected)
            states[1] = intArrayOf()
            val colors = intArrayOf(activeColor, normalColor)
            val colorStateList = ColorStateList(states, colors)
            if (position>=tabs.size){
                tabView.setText(tabs[tabs.size-1])
            }else{
                tabView.setText(tabs[position])
            }
         //   tabView.setTextSize(normalSize)
            tabView.setTextColor(colorStateList)
            tab.setCustomView(tabView)
        }
        if (id.isNullOrEmpty()) {
            listFrag.add(SleepStaticDayFrag())
            listFrag.add(SleepStatisticWeekFrag())
            listFrag.add(SleepStatisticMonthFrag())
            listFrag.add(SleepStatisticYearFrag())
        } else {
            listFrag.add(setArgumentFrag(SleepStaticDayFrag(), id))
            listFrag.add(setArgumentFrag(SleepStatisticWeekFrag(), id))
            listFrag.add(setArgumentFrag(SleepStatisticMonthFrag(), id))
            listFrag.add(setArgumentFrag(SleepStatisticYearFrag(), id))
        }
        binding.mVp2.adapter = MyAdapter(this,listFrag,requireActivity(),childFragmentManager)
        binding.mVp2.isUserInputEnabled =false
//        binding.mVp2.setOffscreenPageLimit(listFrag.size);
        binding.mVp2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                LogUtils.d("pageSelected position:$position")
                val tabCount: Int = binding.tabLayout.getTabCount()
                for (i in 0 until tabCount) {
                    val tab: TabLayout.Tab = binding.tabLayout.getTabAt(i)!!
                    val tabView = tab.customView as TextView?
                    if (tab.position == position) {
                        //tabView!!.textSize = activeSize.toFloat()
                        tabView!!.setTypeface(Typeface.DEFAULT_BOLD)
                    } else {
                       // tabView!!.textSize = normalSize
                        tabView!!.setTypeface(Typeface.DEFAULT)
                    }
                }
                showSelectTime()
                //这个view是的fragment。
                if (initFrag){
                    initFrag = false
                  return
                }
                val view = listFrag[position].view
                view?.let {
                    updatePagerHeightForChild(view)
                }
            }
        })
        //要执行这一句才是真正将两者绑定起来
        binding.mVp2.post {
        mediator.attach()
        }
    }
    //解决viewpager2高度问题
     fun updatePagerHeightForChild(view: View) {
        var pager = binding.mVp2
        view.post {
            val wMeasureSpec =
                View.MeasureSpec.makeMeasureSpec(view.width, View.MeasureSpec.EXACTLY)
            val hMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            view.measure(wMeasureSpec, hMeasureSpec)

            if (pager.layoutParams.height != view.measuredHeight) {
                pager.layoutParams = (pager.layoutParams)
                    .also { lp ->
                        lp.height = view.measuredHeight
                    }
            }
        }
    }
    override fun initData() {
        super.initData()
        id = arguments?.getString("id").toString()
    }

    val audioUtils by lazy { RecordAudio() }
    var isAudioPlay = false

    @RequiresApi(Build.VERSION_CODES.O)
    override fun initView() {
        super.initView()
        isDemonstrate = (requireActivity() as HealthMainAct).isDemonstrate
//        mViewModel.getSetting(Const.SLEEP_SETTING)
     //   initTabVp2()
        initTab()
        initTimeSelect()
        val assets = context?.assets?.open("forest.mp3")
        //保存到手机的路劲
        val appDir = File(context?.let { FileUtils.getCacheFile(it) } + "/asset")
        if (!appDir.exists()) {
            appDir.mkdir()
        }
        val file = File(appDir, "forest.mp3")
        val fos = FileOutputStream(file)
        var bytes = ByteArray(1024)
        var byteCount: Int = assets!!.read(bytes)
        while (byteCount !== -1) {
            fos.write(bytes, 0, byteCount)
            byteCount = assets.read(bytes)
        }
        fos.flush()
        assets.close()
        fos.close()
        binding.compareTv.setOnClickListener {
            if (isDemonstrate){
                (requireActivity() as HealthMainAct).dialogBind.show()
                return@setOnClickListener
            }
            bundle.clear()
            bundle.putString("id", id)
            bundle.putString("type", "5")//4 睡眠
            RouteManager.goAct(ARouterUrl.COMPARE_DATA_ACT, bundle)
        }

        musicInfoBinding.mImagePlay.setOnClickListener {

            if (isAudioPlay){
                isAudioPlay = false
                musicInfoBinding.mImagePlay.setImageResource(R.mipmap.ic_play)
                musicInfoBinding.mName.setTextColor(resources.getColor(R.color.black))
                musicInfoBinding.mPosition.setTextColor(resources.getColor(R.color.black))
                musicInfoBinding.mName.setTypeface(null, Typeface.NORMAL)
                musicInfoBinding.mPosition.setTypeface(null, Typeface.NORMAL)
                audioUtils.stopPlay()
            }else{
                isAudioPlay = true
                musicInfoBinding.mImagePlay.setImageResource(R.mipmap.ic_pause)
                musicInfoBinding.mName.setTextColor(resources.getColor(R.color.col_02c))
                musicInfoBinding.mName.setTypeface(null, Typeface.BOLD)
                musicInfoBinding.mPosition.setTypeface(null, Typeface.BOLD)
                musicInfoBinding.mPosition.setTextColor(resources.getColor(R.color.col_02c))


                file.path?.let { it1 ->
                    audioUtils.audioPlay(
                        it1,
                        object : RecordAudio.AudioPlayStateListener {
                            override fun onStart() {

                            }

                            override fun onComplet() {
                                isAudioPlay = false
                            }

                            override fun onError() {
                                isAudioPlay = false
                            }

                        })
                }
            }
        }
    }

    private fun initTimeSelect() {
        //日筛选
        val calendar = Calendar.getInstance()
        timeDaySelect.endDate.set(
            calendar[Calendar.YEAR], calendar[Calendar.MONTH],
            if (calendar[Calendar.HOUR] >= 11) {
                calendar[Calendar.DATE]
            } else {
                calendar[Calendar.DATE]
            }
        )
        showSelectTime()
        binding.tvShowDate.setOnClickListener {
            val currentFragment = getCurrentFragment()
            if (currentFragment is SleepStaticDayFrag){
                timeDaySelect.selectTime(it,"yyyy-MM-dd")
            }  else if (currentFragment is SleepStatisticWeekFrag) {
                bottomSheetDialog?.show()
            }  else if (currentFragment is SleepStatisticMonthFrag) {
                timeMonthSelect.selectTimeWithYearMonth(it,"yyyy-MM")
            }  else if (currentFragment is SleepStatisticYearFrag) {
                timeYearSelect.selectTimeWithYear(it,"yyyy")
            }
        }

 /*       binding.ivPosition.setOnClickListener {
            val currentFragment = getCurrentFragment()
            if (currentFragment is SleepStaticDayFrag){
                timeDaySelect.selectTime(it,"yyyy-MM-dd")
            }  else if (currentFragment is SleepStatisticWeekFrag) {
                bottomSheetDialog?.show()
            }  else if (currentFragment is SleepStatisticMonthFrag) {
                timeMonthSelect.selectTimeWithYearMonth(it,"yyyy-MM")
            }  else if (currentFragment is SleepStatisticYearFrag) {
                timeYearSelect.selectTimeWithYear(it,"yyyy")
            }
        }*/

        initBottomDialog()
    }

    fun showSelectTime(){
        val currentFragment = getCurrentFragment()
        var showTime =  TimeUtils.getCurrentTime()
        if (currentFragment is SleepStaticDayFrag){
            showTime =  if (TextUtils.isEmpty(timeDaySelect.selectTime)){
                TimeUtils.getCurrentTime()
            } else {
                timeDaySelect.selectTime
            }
        }  else if (currentFragment is SleepStatisticWeekFrag) {
            showTime =  if (weekSelect.isEmpty()){
                TimeUtils.getWeekTime()
            } else {
                weekSelect
            }

        }  else if (currentFragment is SleepStatisticMonthFrag) {
            showTime =  if (TextUtils.isEmpty(timeMonthSelect.selectTime)){
                TimeUtils.getMonthTime()
            } else {
                timeMonthSelect.selectTime
            }
        }  else if (currentFragment is SleepStatisticYearFrag) {
            showTime =  if (TextUtils.isEmpty(timeYearSelect.selectTime)){
                TimeUtils.getYearTime()
            } else {
                timeYearSelect.selectTime
            }
        }
     //   binding.mTime.text = showTime

        binding.tvShowDate.text = showTime
    }

    override fun onDestroy() {
        audioUtils.stopPlay()
        super.onDestroy()
    }



    override fun observer() {

    }


    private fun setArgumentFrag(frag: Fragment, id: String = ""): Fragment {
        bundle.clear()
        bundle.putString("id", id)
        frag.arguments = bundle
        return frag
    }
    var bottomSheetDialog:BottomSheetDialog?=null
    var weekSelect :String = ""
    fun initBottomDialog(){
        if (bottomSheetDialog == null){
            bottomSheetDialog = BottomSheetDialog(this.requireContext())
            bottomSheetDialog?.let{ dialog ->
                val view = LayoutInflater.from(context).inflate(R.layout.bottom_sheet_layout, null)
                dialog.setContentView(view)
                val wheelView = view.findViewById<WheelView>(R.id.wheelView)
                wheelView.setCyclic(false)
                wheelView.adapter  = ArrayWheelAdapter(buildWeekLower26())
                val windowHeight = (resources.displayMetrics.heightPixels * 0.6).toInt()
                dialog.behavior.peekHeight =windowHeight

                dialog.behavior.isHideable = false
                dialog.behavior.state = BottomSheetBehavior.STATE_EXPANDED

                val cancelButton = view.findViewById<TextView>(R.id.cancel_button)
                val confirmButton = view.findViewById<TextView>(R.id.confirm_button)

                cancelButton.setOnClickListener {
                    // 点击取消按钮的操作
                    dialog.dismiss()
                }

                confirmButton.setOnClickListener {
                    val item = wheelView.adapter.getItem(wheelView.currentItem)
                    binding.mTime.text = item.toString()
                    weekSelect = item.toString()
                    getData( item.toString())
                    // 点击确定按钮的操作
                    dialog.dismiss()
                }
            }
        }
    }

    fun buildWeekLower26(): MutableList<String>{
        val startDate = Calendar.getInstance()
        startDate.firstDayOfWeek = Calendar.MONDAY
        startDate.add(Calendar.YEAR, -1)
        val endDate = Calendar.getInstance()

        val dateRanges: MutableList<String> = ArrayList()
        var currentMonday = startDate.clone() as Calendar
        currentMonday.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY)

        while (currentMonday.before(endDate)) {
            val currentSunday = currentMonday.clone() as Calendar
            currentSunday.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY)

            val formattedDateRange = SimpleDateFormat("yyyy-MM-dd").format(currentMonday.time) +
                    "至" + SimpleDateFormat("yyyy-MM-dd").format(currentSunday.time)
            dateRanges.add(formattedDateRange)

            currentMonday.add(Calendar.WEEK_OF_YEAR, 1)
        }

        dateRanges.reverse()
        return dateRanges
    }
    private fun getNextOrSameDayOfWeek(cal: Calendar, dayOfWeek: Int): Calendar {
        var cal = cal
        while (cal.get(Calendar.DAY_OF_WEEK) != dayOfWeek) {
            cal.add(Calendar.DAY_OF_WEEK, 1)
        }
        return cal
    }

    private fun formatDate(date: Date): String {
        val dateFormat: DateFormat = SimpleDateFormat("yyyy-MM-dd")
        return dateFormat.format(date)
    }

}