package com.zj365.mime.act

import android.view.LayoutInflater
import android.view.View
import android.widget.EditText
import android.widget.TextView
import androidx.core.view.get
import com.alibaba.android.arouter.facade.annotation.Route
import com.suke.widget.SwitchButton
import com.xty.base.act.BaseVmAct
import com.xty.common.TimeSelect
import com.xty.common.arouter.ARouterUrl
import com.xty.common.util.CommonToastUtils
import com.zj365.mime.R
import com.zj365.mime.databinding.ActMedicineRemindBinding
import com.zj365.mime.vm.WearManagerVm
import com.xty.network.model.WearManagerBean
import java.lang.StringBuilder

/**
 * 用药提醒
 */
@Route(path = ARouterUrl.MEDICATION_REMIND)
class MedicationRemindAct : BaseVmAct<WearManagerVm>() {
    val binding by lazy { ActMedicineRemindBinding.inflate(layoutInflater) }

    var bean: WearManagerBean? = null

    override fun setLayout() = binding.root
    override fun initData() {
        super.initData()
        isDarkBar = true
        val serializable = intent.extras!!.getSerializable("value")
        bean = if (null == serializable) null else serializable as WearManagerBean
    }

    override fun initView() {
        super.initView()

        statusBar(binding.title.mView)
        binding.title.mIvBack.setOnClickListener {
            submit()
        }
        binding.title.mTvTitle.text = getString(R.string.wear_manager_05)

        if (null == bean?.medicine || bean?.medicine?.size == 0) {
            binding.noData.visibility = View.VISIBLE
            binding.childLayout.visibility = View.GONE
        } else {
            binding.noData.visibility = View.GONE
            binding.childLayout.visibility = View.VISIBLE
            setChildViews(bean?.medicine!!)
        }

        binding.mAddMedicine.isSelected = true
        binding.mAddMedicine.setOnClickListener {
            binding.noData.visibility = View.GONE
            binding.childLayout.visibility = View.VISIBLE
            addChildViews()
        }
    }

    val timSelect by lazy {
        TimeSelect(this) {
        }.apply {
            chooseMany = true
            showYear = false
            showMonth = false
            showDay = false
            showHour = true
            showMin = true
            showSec = false
        }
    }

    private fun setChildViews(medicineList: List<WearManagerBean.Medicine>){
        medicineList.forEach {
            var childView = LayoutInflater.from(this).inflate(R.layout.act_medicine_remind_item, null)
            var viewIndex = binding.childLayout.childCount//view下标
            var viewNum = viewIndex + 1//页码 第几次
            childView.findViewById<TextView>(R.id.mTitle).text =
                "用药提醒设置"
            var switchBtn = childView.findViewById<SwitchButton>(R.id.mSwitchBtn)
            switchBtn.isChecked = it.state == 0
//            switchBtn.setOnCheckedChangeListener { _, isChecked ->
//                mViewModel.useMedicineSetting(medicineList)
//            }
            childView.findViewById<TextView>(R.id.mDelete).setOnClickListener {
                binding.childLayout.removeView(childView)
            }

            var textView = childView.findViewById<TextView>(R.id.mTvRemindTime)
            var str = StringBuilder()
            it.medicationRemindTime.forEach {
                if (str.isNotEmpty()){
                    str.append(",")
                }
                str.append(it)
            }
            textView.text = str
            textView.setOnClickListener {
                if (textView.text.contains("时间")){
                    textView.text = ""
                }
                timSelect.selectManyTime(it, "HH:mm")
            }

            var editText = childView.findViewById<EditText>(R.id.mTvName)
            editText.setText(it.medicationName)

            childView.setPadding(0,0,0, dp2px(10))

            binding.childLayout.addView(
                childView
            )
        }
    }

    private fun addChildViews() {
        var childView = LayoutInflater.from(this).inflate(R.layout.act_medicine_remind_item, null)
        var viewIndex = binding.childLayout.childCount//view下标
        var viewNum = viewIndex + 1//页码 第几次
        childView.findViewById<TextView>(R.id.mTitle).text =
            "用药提醒设置"
        var switchBtn = childView.findViewById<SwitchButton>(R.id.mSwitchBtn)
        switchBtn.isChecked = true

        var textView = childView.findViewById<TextView>(R.id.mTvRemindTime)
        textView.setOnClickListener {
            if (textView.text.contains("时间")){
                textView.text = ""
            }
            timSelect.selectManyTime(it, "HH:mm")
        }
        childView.findViewById<TextView>(R.id.mDelete).setOnClickListener {
            binding.childLayout.removeView(childView)
        }

        var editText = childView.findViewById<EditText>(R.id.mTvName)

        childView.setPadding(0,0,0, dp2px(10))

        binding.childLayout.addView(
            childView
        )
    }

    private fun getChildView(index: Int, childId: Int = 0): View {
        return if (childId == 0) binding.childLayout[index]
        else binding.childLayout[index].findViewById(childId)
    }

    private fun submit(){
        var list = mutableListOf<WearManagerBean.Medicine>()

        if (binding.childLayout.childCount >= 0){
            for (i in 0 until binding.childLayout.childCount) {
                val state = if ((getChildView(i, R.id.mSwitchBtn) as SwitchButton).isChecked) 0 else 1
                val name = (getChildView(i, R.id.mTvName) as EditText).text.toString()
                val time  = (getChildView(i, R.id.mTvRemindTime) as TextView).text
                if (time.isNullOrEmpty() || time.contains("时间")){
                    continue
                }
                list.add(WearManagerBean.Medicine(state, name, time.split(",")))
            }

            if (list.isNullOrEmpty()){//如果添加了view，但是没有时间信息则不提交
                bundle.clear()
                bundle.putSerializable("value", bean)
                intent.putExtras(bundle)
                setResult(RESULT_OK, intent)
                finish()
                return
            }
        }
        bean?.medicine = list
        mViewModel.useMedicineSetting(list)
    }

    override fun onBackPressed() {
        submit()
    }


    override fun liveObserver() {
        mViewModel.settingLive.observe(this) {
            CommonToastUtils.showSucceedToast("设置成功")
            bundle.clear()
            bundle.putSerializable("value", bean)
            intent.putExtras(bundle)
            setResult(RESULT_OK, intent)
            finish()
        }
    }

}