package com.zj365.health.act.binddevice

import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.view.View
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.lifesense.android.ble.core.valueobject.DeviceInfo
import com.xty.base.act.BaseVmAct
import com.xty.common.TimeSelect
import com.xty.common.TimeUtils
import com.xty.common.arouter.ARouterUrl
import com.xty.common.event.BindDevEvent
import com.xty.common.event.WorkManagerEvent
import com.xty.common.util.CommonToastUtils
import com.xty.common.util.CommonUtils
import com.zj365.health.R
import com.zj365.health.databinding.ActBindBaseInfoBinding
import com.zj365.health.vm.BindDeviceListVm
import com.xty.network.model.BodyFatUserBean
import org.greenrobot.eventbus.EventBus
import java.text.SimpleDateFormat
import java.util.Calendar

@Route(path = ARouterUrl.BODY_FAT_USER_INFO)
class BodyFatSimpleInfoAct : BaseVmAct<BindDeviceListVm>() {

    var deviceInfo: DeviceInfo? = null
    val binding by lazy { ActBindBaseInfoBinding.inflate(layoutInflater) }

    var isAlterUserInfo = false

    var userInfo: BodyFatUserBean? = null
    val timeSelect by lazy {
        TimeSelect(this) {}.apply {
            val dataStr = binding.mBirthday.text.toString()
            val dateCalendar = Calendar.getInstance()
            if (dataStr.isNotEmpty()) {
                val date = SimpleDateFormat("yyyy-MM-dd").parse(dataStr)
                dateCalendar.time = date
                selectedDate = dateCalendar
            }
        }
    }

    override fun liveObserver() {

        mViewModel.bindDev.observe(this) {
            if (it.code == 0) {
                userInfo?.apply {
                    mViewModel.saveUserInfo(birthday, birthdayType, sex, "", height)
                }
            }
        }

        mViewModel.saveSuccess.observe(this) {

            if (it.code == 0) {

                if (!isAlterUserInfo) {  //如果不是修改用户信息，进行数据更新
                    EventBus.getDefault().post(BindDevEvent())  //列表界面更新
                    EventBus.getDefault().post(WorkManagerEvent())  //首页更新
                }
                finish()
            }
        }

        mViewModel.userInfo.observe(this) {
            it.data.apply {
                binding.checkSex.isChecked = sex == 2
                binding.checkBirthday.isChecked = birthdayType == 2
                binding.mBirthday.text = birthday
                binding.mHeight.setText("$height")
            }
        }
    }

    override fun setLayout(): View = binding.root

    override fun initData() {
        super.initData()
        deviceInfo = intent.getSerializableExtra("deviceInfo") as DeviceInfo?
    }

    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)
        binding.title.mIvBack.visibility = View.INVISIBLE
        binding.title.mTvTitle.text = "基本信息确认"

        binding.llBirthdayLayout.setOnClickListener {
            timeSelect.selectTime(binding.mBirthday)
        }


        val builder = SpannableStringBuilder(binding.tvHint.text)
        val redSpan = ForegroundColorSpan(ContextCompat.getColor(this, R.color.col_2621))
        builder.setSpan(redSpan, 0, 5, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
        binding.tvHint.text = builder

        binding.mSubmit.setOnClickListener {

            val sex = if (binding.checkSex.isChecked) 2 else 1
            val birthdayType = if (binding.checkBirthday.isChecked) 2 else 1
            val birthday = binding.mBirthday.text.toString()
            val height = binding.mHeight.text.toString()

            if (birthday.isEmpty()) {
                CommonToastUtils.showToast("请输入出生日期")
                return@setOnClickListener
            }

            if (height.isEmpty()) {
                CommonToastUtils.showToast("请输入身高")
                return@setOnClickListener
            }

            if (height.toFloat() < 50 || height.toFloat() > 260) {
                CommonToastUtils.showToast("请输入正确身高")
                return@setOnClickListener
            }

            if (TimeUtils.getAgeByBirth(birthday) < 14) {
                CommonToastUtils.showToast("需要年满14岁才可使用")
                return@setOnClickListener
            }

            deviceInfo?.apply {
                mViewModel.bindDev(sn, mac)
            }
            userInfo = BodyFatUserBean(birthday, birthdayType, height, "", sex)

            if (deviceInfo == null) { //如果设备信息是空，表示只进行用户信息修改
                isAlterUserInfo = true
                mViewModel.saveUserInfo(birthday, birthdayType, sex, "", height)
            }
        }

        CommonUtils.getMySettingInfo()?.let {
            mViewModel.getUserInfo(it.user.id)
        }
    }

    override fun onBackPressed() {
        super.onBackPressed()
        deviceInfo?.apply {
            BlueUtil.getBlueManage().unBind(mac)
        }
    }
}