package com.zj365.health.act

import android.annotation.SuppressLint
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.xty.base.act.BaseVmAct
import com.xty.common.LogUtils
import com.xty.common.arouter.ARouterUrl
import com.xty.common.event.MyInfoEvent
import com.xty.common.event.NSuanOpenEvent
import com.xty.common.event.OpenOrRenewEvent
import com.xty.common.util.CommonToastUtils
import com.zj365.health.R
import com.zj365.health.adapter.NSuanMessagePerfectAdapter
import com.zj365.health.databinding.ActNsuanMessagePerfectBinding
import com.zj365.health.vm.NSuanVm
import com.xty.network.model.NSuanMessagePerfectBean
import org.greenrobot.eventbus.EventBus

/**
 * 完善尿酸信息页面，编辑尿酸填写信息
 */
@Route(path = ARouterUrl.NS_MESSAGE_PERFECT)
class NSuanMessagePerfectAct : BaseVmAct<NSuanVm>() {

    private var userId = ""
    private val binding by lazy { ActNsuanMessagePerfectBinding.inflate(layoutInflater) }
    private var isAlter = false
    private var activeCode: String = ""
    private var time:String?=null
    override fun setLayout(): View = binding.root

    //吸烟数据集合
    private val fumareListData: MutableList<NSuanMessagePerfectBean> = mutableListOf()
    private val fumareAdapter by lazy {
        NSuanMessagePerfectAdapter(
            R.layout.item_nsuan_message_perfect,
            fumareListData
        )
    }

    //饮酒数据集合
    private val drinkListData: MutableList<NSuanMessagePerfectBean> = mutableListOf()
    private val drinkAdapter by lazy {
        NSuanMessagePerfectAdapter(
            R.layout.item_nsuan_message_perfect,
            drinkListData
        )
    }

    private var fumareTypa = -1
    private var drinkTypa = -1
    private var isFirstOpen = false

    override fun initData() {
        super.initData()
        isDarkBar = true//设置状态栏字体为深色
        intent.extras?.let {
            userId = it.getString("id").toString()
            activeCode = it.getString("activeCode").toString()
            isAlter = it.getBoolean("alter")
            isFirstOpen = it.getBoolean("firstOpen", false)
            time = it.getString("time")
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)
        binding.title.mTvTitle.text = getString(R.string.ns_message_perfect)

        binding.title.mIvBack.apply {
            this.setOnClickListener {
                finish()
            }
        }

        binding.rvFumareList.layoutManager = LinearLayoutManager(this)
        binding.rvFumareList.adapter = fumareAdapter
        //条目点击事件
        fumareAdapter.setOnItemClickListener { _, _, position ->
            for (datum in fumareAdapter.data) {
                datum.isSelected = false
            }
            val nSuanMessagePerfectBean = fumareAdapter.data[position]
            nSuanMessagePerfectBean.isSelected = true
            fumareTypa = nSuanMessagePerfectBean.selected
            fumareAdapter.notifyDataSetChanged()

            setSubmitButtonEnabled()
        }
        binding.rvDrinkList.layoutManager = LinearLayoutManager(this)
        binding.rvDrinkList.adapter = drinkAdapter
        //条目点击事件
        drinkAdapter.setOnItemClickListener { _, _, position ->
            for (datum in drinkAdapter.data) {
                datum.isSelected = false
            }
            val nSuanMessagePerfectBean = drinkAdapter.data[position]
            nSuanMessagePerfectBean.isSelected = true
            drinkTypa = nSuanMessagePerfectBean.selected
            drinkAdapter.notifyDataSetChanged()

            setSubmitButtonEnabled()
        }
        //添加数据
        addListData()

        //设置点击事件
        binding.mSubmit.setOnClickListener(onClickListener)
        binding.mEtWeight.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                setSubmitButtonEnabled()
            }
        })
        binding.mEtHeight.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                setSubmitButtonEnabled()
            }
        })

        setSubmitButtonEnabled()

        mViewModel.getUserInfo(userId)

    }

    private fun setSubmitButtonEnabled() {
        //身高
        val etheight = binding.mEtHeight.text.toString()
        //体重
        val weight = binding.mEtWeight.text.toString()
        binding.mSubmit.isEnabled =
            !TextUtils.isEmpty(etheight) && !TextUtils.isEmpty(weight) && fumareTypa >= 0 && drinkTypa >= 0
        binding.mSubmit.isSelected =
            !TextUtils.isEmpty(etheight) && !TextUtils.isEmpty(weight) && fumareTypa >= 0 && drinkTypa >= 0
    }

    //添加数据
    private fun addListData() {
        //--------------------吸烟区-----------------
        fumareListData.add(
            NSuanMessagePerfectBean(
                "经常吸烟",
                "每天吸卷烟１支以上，连续或累计６个月",
                2,
                false
            )
        )
        fumareListData.add(
            NSuanMessagePerfectBean(
                "偶尔吸烟",
                "每周吸卷烟超过４次，但平均每天不足１支",
                1,
                false
            )
        )
        fumareListData.add(
            NSuanMessagePerfectBean(
                "不吸烟",
                "",
                0,
                false
            )
        )
        fumareAdapter.setNewInstance(fumareListData)
        //-------------------饮酒区-------------------
        drinkListData.add(
            NSuanMessagePerfectBean(
                "经常饮酒",
                "经常饮酒：每周饮酒饮酒频率大于等于3次",
                2,
                false
            )
        )
        drinkListData.add(
            NSuanMessagePerfectBean(
                "偶尔饮酒",
                "每周大于等于1次，小于等于3次",
                1,
                false
            )
        )
        drinkListData.add(
            NSuanMessagePerfectBean(
                "不饮酒",
                "饮酒频率每30天小于等于1次",
                0,
                false
            )
        )
        drinkAdapter.setNewInstance(drinkListData)
    }

    private val onClickListener = View.OnClickListener {
        when (it.id) {
            //获取兑换码
            R.id.mSubmit -> {
                //身高
                val etheight = binding.mEtHeight.text.toString()
                //体重
                val weight = binding.mEtWeight.text.toString()
                if (TextUtils.isEmpty(etheight)) {
                    CommonToastUtils.showToast("请输入身高")
                    return@OnClickListener
                }
                if (TextUtils.isEmpty(weight)) {
                    CommonToastUtils.showToast("请输入体重")
                    return@OnClickListener
                }
                if (fumareTypa < 0) {
                    CommonToastUtils.showToast("请选择是否吸烟")
                    return@OnClickListener
                }
                if (drinkTypa < 0) {
                    CommonToastUtils.showToast("请选择是否饮酒")
                    return@OnClickListener
                }
                mViewModel.nsUpdataMes(
                    userId,
                    fumareTypa.toString(),
                    drinkTypa.toString(),
                    etheight,
                    weight
                )
            }
        }
    }

    override fun liveObserver() {
        mViewModel.nsUpdataData.observe(
            this
        ) {
            if (it.code == 0) {
                if (isAlter){
                    finish()
                    CommonToastUtils.showSucceedToast("修改成功")
                    EventBus.getDefault().post(NSuanOpenEvent())
                }else{
//                    mViewModel.nsOpen(userId, activeCode)
                    if (!isFirstOpen) {
                        mViewModel.renewOpenRequest(userId, 4, "EXCHANGE_CODE", activeCode)
                    } else {
                        EventBus.getDefault().post(NSuanOpenEvent())
                        finish()
                    }
                }
            }
        }

        //新开通尿酸接口返回方法
        mViewModel.renewOpenData.observe(this) {
            if (null == it.data) {
                LogUtils.e("操作异常！")
                return@observe
            }
            val code = it.code
            if (code != 0) {
                CommonToastUtils.showToast("开通失败")
            } else {
                CommonToastUtils.showSucceedToast("开通成功")
            }

            EventBus.getDefault().post(NSuanOpenEvent())
            EventBus.getDefault().post(OpenOrRenewEvent())
            EventBus.getDefault().post(MyInfoEvent())
            finish()
        }

        mViewModel.nsuanOpen.observe(this) {
            if (null == it.data) {
                LogUtils.e("操作异常！")
                return@observe
            }
            val code = it.code
            if (code != 0) {
                CommonToastUtils.showToast("开通失败")
            } else {
                CommonToastUtils.showSucceedToast("开通成功")
            }

            finish()
            EventBus.getDefault().post(NSuanOpenEvent())
        }

        mViewModel.userInfo.observe(this) {

            binding.mEtHeight.setText(it.data.height)
            binding.mEtWeight.setText(it.data.weight)

            if (!time.isNullOrEmpty()){ //如果不是第一次开通,补全是否抽烟喝酒的数据
                fumareAdapter.data[2 - it.data.smokeState.toInt()].isSelected = true
                drinkAdapter.data[2 - it.data.drinkState.toInt()].isSelected = true

                fumareAdapter.notifyDataSetChanged()
                drinkAdapter.notifyDataSetChanged()

                fumareTypa = it.data.smokeState.toInt()
                drinkTypa = it.data.drinkState.toInt()
                setSubmitButtonEnabled()
            }
        }
    }
}