package com.cheng.blzb.ui.fragment.home.bszz

import android.annotation.SuppressLint
import android.text.TextUtils
import android.view.ViewTreeObserver
import androidx.constraintlayout.widget.ConstraintLayout
import com.cheng.blzb.R
import com.cheng.blzb.bean.AreaEntity
import com.cheng.blzb.databinding.FragmentBszzBinding
import com.cheng.blzb.impl.TextWatcherImpl
import com.cheng.blzb.ui.dialog.SelectAreaDialog
import com.example.base.extensions.onClick
import com.example.base.extensions.toast
import com.example.base.ui.BaseFragment
import com.example.base.utils.DensityUtils
import com.example.base.utils.ScreenUtils
import com.google.gson.JsonObject
import okhttp3.RequestBody.Companion.toRequestBody

class BSZZFragment: BaseFragment<FragmentBszzBinding, BSZZViewModel>() {
    private var timestamp = ""

    private var city: AreaEntity? = null

    private val textWatcher = object : TextWatcherImpl() {
        @SuppressLint("SetTextI18n")
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            super.onTextChanged(s, start, before, count)
            binding.tvTextCount.text = "${s?.length ?: 0}/300"
        }
    }

    override fun initView() {
        super.initView()
        mTitleBar?.background = null
        setBackColor(R.color.white)

        binding.layoutContent.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                val lp = binding.tvArea.layoutParams as ConstraintLayout.LayoutParams
                lp.topMargin = (ScreenUtils.getScreenWidth().toFloat() / DensityUtils.dp2px(375f) * DensityUtils.dp2px(410f)).toInt()
                binding.tvArea.layoutParams = lp
                binding.layoutContent.viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        })
    }

    override fun initData() {
        super.initData()
    }

    override fun initListener() {
        super.initListener()
        binding.etDesc.addTextChangedListener(textWatcher)

        binding.tvArea.onClick {
            val f = SelectAreaDialog.newInstance(if (city != null) listOf(city!!) else emptyList(), true)
            f.setOnSelectListener {
                city = it[0]
                binding.tvArea.text = city!!.name
            }
            f.show(childFragmentManager, SelectAreaDialog::class.java.simpleName)
        }

        binding.tvSendCode.onClick {
            val phone = binding.etPhone.text.toString()
            if (TextUtils.isEmpty(phone)) {
                toast("请输入手机号")
                return@onClick
            }
            mViewModel.sendCode(phone)
        }

        binding.btnNext.onClick {
            val name = binding.etName.text.toString().trim()
            val phone = binding.etPhone.text.toString().trim()
            val code = binding.etCode.text.toString().trim()
            val desc = binding.etDesc.text.toString().trim()
            if (city == null) {
                toast("请选择注册区域")
                return@onClick
            }
            if (TextUtils.isEmpty(name)) {
                toast("请输入姓名")
                return@onClick
            }
            if (TextUtils.isEmpty(phone)) {
                toast("请输入电话")
                return@onClick
            }
            if (TextUtils.isEmpty(code)) {
                toast("请输入验证码")
                return@onClick
            }
            val jsonObject = JsonObject()
            jsonObject.addProperty("source", "bid_book")
            jsonObject.addProperty("city", city!!.name)
            jsonObject.addProperty("cityId", "${city!!.id}")
            jsonObject.addProperty("name", name)
            jsonObject.addProperty("phone", phone)
            jsonObject.addProperty("code", code)
            jsonObject.addProperty("timestamp", timestamp)
            jsonObject.addProperty("remark", desc)
            mViewModel.addAgency(jsonObject.toString().toRequestBody())
        }
    }

    @SuppressLint("SetTextI18n")
    override fun initObserve() {
        super.initObserve()
        mViewModel.sendCodeLiveData.observe(this) { timestamp = it.timestamp }
        mViewModel.countTimeLiveEvent.observe(this) {
            if (it > 0) {
                binding.tvSendCode.text = "重新获取(${it}s)"
                binding.tvSendCode.isEnabled = false
                binding.tvSendCode.alpha = 0.5f
            } else {
                binding.tvSendCode.text = "重新获取"
                binding.tvSendCode.isEnabled = true
                binding.tvSendCode.alpha = 1f
            }
        }

        mViewModel.addLiveData.observe(this) {
            toast("提交成功")
            requireActivity().finish()
        }
    }

    override fun onDestroyView() {
        binding.etDesc.removeTextChangedListener(textWatcher)
        super.onDestroyView()
    }
}