package com.rdiot.yx485.ui.home

import android.os.Bundle
import android.text.SpannableString
import android.text.style.AbsoluteSizeSpan
import android.text.style.SuperscriptSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.IdRes
import com.drake.brv.annotaion.DividerOrientation
import com.drake.brv.utils.bindingAdapter
import com.drake.brv.utils.divider
import com.drake.brv.utils.grid
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import com.drake.net.utils.scope
import com.drake.net.utils.scopeNetLife
import com.king.zxing.util.LogUtils
import com.rdiot.yx485.R
import com.rdiot.yx485.adapter.ScenesAdapter
import com.rdiot.yx485.base.BaseFragment
import com.rdiot.yx485.base.LocalData
import com.rdiot.yx485.bean.RoomData
import com.rdiot.yx485.bean.SceneBean
import com.rdiot.yx485.databinding.FraHomeBinding
import com.rdiot.yx485.databinding.ItemRoomBinding
import com.rdiot.yx485.net.getFamilyData
import com.rdiot.yx485.net.setPower
import com.rdiot.yx485.ui.bind.BindActivity
import com.rdiot.yx485.ui.ctrl.RoomCtrlMainActivity
import com.rdiot.yx485.ui.mine.UserInfoActivity
import com.rdiot.yx485.util.*
import dagger.hilt.android.AndroidEntryPoint
import java.text.Format
import java.text.SimpleDateFormat
import java.util.*


/**
 * 首页
 * @author mR2hao
 * @date 2022/11/9
 */
@AndroidEntryPoint
class HomeFragment : BaseFragment<FraHomeBinding>() {
    override fun getLayoutId() = R.layout.fra_home

    private lateinit var scenesAdapter: ScenesAdapter

    override fun initView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ) {
        // 用户头像
        LocalData.userData.observe(this) { userData ->
            binding.userData = userData
            val imgUrl = "${LocalData.apiHost.avatarHost}${userData?.photo}"
//            LogUtils.d("头像地址：$imgUrl")
            binding.ivAvatar.circleImg(imgUrl)
        }
        LocalData.weatherData.observe(this) { weatherData ->
            weatherData.now?.let {now->
                // 温度
                val ss = SpannableString("${now.temp}℃")
                val sizeSpan = AbsoluteSizeSpan(23, true)
                ss.setSpan(sizeSpan, 2, 3, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                val superScriptTextSpan = SuperscriptSpan()
                ss.setSpan(superScriptTextSpan, 2, 3, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                binding.tvTemp.text = ss
            }
            binding.weatherData = weatherData
        }
        LocalData.welcomeData.observe(this) { welcomeData ->
            binding.welcomeData = welcomeData
        }


        initScenes()
        initRooms()

        initUserInfo()

        binding.ivAvatar.setClickLimitListener {
            act.clearGoTo(UserInfoActivity::class.java)
        }

        binding.llAdd.setClickLimitListener {
            act.clearGoTo(BindActivity::class.java)
        }

        binding.tvDay.text = getDay()
        binding.tvWeek.text = getDayOfTheWeek()
    }

    /** 初始化用户信息 */
    private fun initUserInfo() {
        LocalData.userData.observe(this) { userdata ->
            binding.userData = userdata
        }
    }

    /** 初始化场景列表 */
    private fun initScenes() {
        val list = mutableListOf(
            SceneBean("回家模式"),
            SceneBean("一键全关"),
            SceneBean("离家模式"),
            SceneBean("睡眠模式"),
            SceneBean("电影")
        )
        scenesAdapter = ScenesAdapter(act, 20.dp, OnSceneItemClickListener)
        binding.pageView.setAdapter(scenesAdapter)
        scenesAdapter.updateAll(list.toList())

    }


    /** 初始化房间列表 */
    private fun initRooms() {
        binding.rv.grid(1).divider {
            setDrawable(R.drawable.divider_horizontal)
            orientation = DividerOrientation.GRID
            includeVisible = true
        }.setup {
            addType<RoomData>(R.layout.item_room)
            onBind {
                val binding = getBinding<ItemRoomBinding>()

                binding.clItem.setOnClickListener {
                    clickHandler(R.id.cl_item, this.modelPosition)
                }

                binding.ivSwitch.setClickLimitListener {
                    clickHandler(R.id.iv_switch, this.modelPosition)
                }
            }

        }

        LocalData.selFamilyId.observe(this) {
            if (!it.isNullOrBlank()) {
                binding.page.onRefresh {
                    scope {
//                        binding.rv.models = getFamilyData().await().room
                        getFamilyData().await().also {
                            LocalData.familyData.postValue(it)
                        }
                    }
                }.autoRefresh()
            }
        }

        val tempList = mutableListOf<RoomData>()
        LocalData.familyData.observe(this) { familyData ->
            binding.tvLocation.text =
                if (familyData?.city.isNullOrBlank()) {
                    getString(R.string.no_location)
                } else {
                    familyData?.city
                }

            familyData?.room?.let { roomData ->
                if (roomData.isEmpty()) {
                    binding.ivNoRoom.visibility = View.VISIBLE
                    binding.rv.visibility = View.GONE
                } else {
                    tempList.clear()
                    tempList.addAll(roomData)
                    tempList.forEach {
                        it.isOnline = familyData.isOnline
                    }
                    binding.rv.models = tempList

                    binding.ivNoRoom.visibility = View.GONE
                    binding.rv.visibility = View.VISIBLE
                }
            }
        }
    }

    /**
     * 列表Item点击时间
     * @param viewId Int
     */
    private fun clickHandler(@IdRes viewId: Int, position: Int) {
        LocalData.lastRefreshTime = curTime
        val roomData = LocalData.familyData.value?.room?.get(position) ?: return

        when (viewId) {
            R.id.cl_item -> {
                act.getClearTopIntent(RoomCtrlMainActivity::class.java).apply {
                    putExtra(RoomCtrlMainActivity.ROOM_DATA, roomData)
                    act.clearGoTo(this)
                }
                LogUtils.i("onItemClicked:  $roomData")
            }
            R.id.iv_switch -> {
                roomData.power = !roomData.power
                scopeNetLife {
                    setPower(
                        LocalData.familyData.value?.gateway ?: "",
                        roomData
                    ).await()
                }
                LocalData.familyData.postValue(LocalData.familyData.value)
            }
        }
    }

    /** 场景点击事件 */
    object OnSceneItemClickListener : ScenesAdapter.OnItemClickListener {
        override fun onClick(position: Int, sceneBean: SceneBean?) {
            LogUtils.i("onClick: $position,$sceneBean")
        }

    }

    private fun getDayOfTheWeek(): String {
        val list = arrayOf("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六")
        val calendar: Calendar = Calendar.getInstance()
        calendar.time = Date()
        var index: Int = calendar.get(Calendar.DAY_OF_WEEK) - 1
        if (index < 0) {
            index = 0
        }
        return list[index]
    }

    private fun getDay(): String {
        val sdf: Format = SimpleDateFormat("M.dd", Locale.getDefault())
        return sdf.format(Date())
    }
}