package com.cheng.blzb.ui.fragment.home.zzdb.detail

import android.annotation.SuppressLint
import android.os.Build
import android.text.TextUtils
import androidx.constraintlayout.widget.ConstraintLayout
import com.cheng.blzb.R
import com.cheng.blzb.bean.AreaEntity
import com.cheng.blzb.bean.ZZDBInfoEntity
import com.cheng.blzb.common.Constants
import com.cheng.blzb.databinding.FragmentZzdbDetailBinding
import com.cheng.blzb.ui.dialog.SelectAreaDialog
import com.example.base.extensions.gone
import com.example.base.extensions.onClick
import com.example.base.extensions.toast
import com.example.base.extensions.visible
import com.example.base.ui.BaseFragment
import com.example.base.utils.BarUtils
import com.example.base.utils.DensityUtils
import com.google.gson.JsonObject
import com.gyf.immersionbar.ktx.actionBarHeight
import okhttp3.RequestBody.Companion.toRequestBody

class ZZDBDetailFragment : BaseFragment<FragmentZzdbDetailBinding, ZZDBDetailViewModel>() {
    private var info: ZZDBInfoEntity? = null
    private var childInfo: ZZDBInfoEntity? = null

    private val deviceAdapter by lazy { ZZDBDeviceAdapter() }

    private var isExpand = false

    private var timestamp = ""

    private var city: AreaEntity? = null

    override fun initView() {
        super.initView()
        binding.rb1.typeface = Constants.douyinsansB
        binding.rb2.typeface = Constants.douyinsansB
        binding.rb3.typeface = Constants.douyinsansB
        binding.tvNext.typeface = Constants.almmsht

        binding.rvDevice.adapter = deviceAdapter

        (binding.layoutBaseInfo.layoutParams as ConstraintLayout.LayoutParams).topMargin = BarUtils.getStatusBarHeight() + actionBarHeight + DensityUtils.dp2px(12f)
    }

    override fun initData() {
        super.initData()
        info = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arguments?.getSerializable("item", ZZDBInfoEntity::class.java)
        } else {
            arguments?.getSerializable("item") as? ZZDBInfoEntity
        }
        setBaseData()
    }

    override fun initListener() {
        super.initListener()
        binding.tvMore.onClick {
            isExpand = !isExpand
            if (childInfo != null) {
                setExpandStyle(childInfo!!)
            }
        }

        binding.rgLevel.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.rb1 -> {
                    childInfo = this.info!!.children.find { it.level == "1" }
                }

                R.id.rb2 -> {
                    childInfo = this.info!!.children.find { it.level == "2" }
                }

                R.id.rb3 -> {
                    childInfo = this.info!!.children.find { it.level == "3" }
                }
            }
            if (childInfo != null) {
                setDetailData(childInfo!!)
            }
        }

        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, "")
        }

        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()
            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", "agency_cert")
            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)
            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()
        }
    }

    private fun setBaseData() {
        if (info != null) {
            binding.tvName.text = info!!.name
            info!!.children.forEach {
                when (it.level) {
                    "1" -> {
                        binding.rb1.visible()
                        binding.rb1.isChecked = true
                    }

                    "2" -> {
                        binding.rb2.visible()
                        binding.rb2.isChecked = !binding.rb1.isChecked
                    }

                    "3" -> {
                        binding.rb3.visible()
                        binding.rb2.isChecked = !binding.rb1.isChecked && !binding.rb2.isChecked
                    }
                }
            }
        }
    }

    private fun setDetailData(info: ZZDBInfoEntity) {
        binding.tvRange.text = info.range
        binding.tvAsset.text = info.property
        binding.tvPerson.text = info.person
        binding.tvPerformance.text = info.performance

        if (!TextUtils.isEmpty(info.equitment)) {
            if (info.equitment.startsWith("具有下列机械设备：")) {
                val deviceArray = info.equitment.split("\r\n\r\n")
                val deviceList = mutableListOf<String>()
                deviceArray.forEach {
                    if (it.startsWith("（") && it.indexOf("）") != -1) {
                        deviceList.add(it.substring(it.indexOf("）") + 1, it.length - 1))
                    }
                }
                deviceAdapter.setList(deviceList)
            } else {
                deviceAdapter.setList(listOf(info.equitment))
            }
        }

        setExpandStyle(info)
    }

    private fun setExpandStyle(info: ZZDBInfoEntity) {
        if (isExpand) {
            binding.tvMore.text = "收起更多资质说明"
            binding.tvMore.setCompoundDrawablesWithIntrinsicBounds(0 , 0, R.mipmap.ic_more_arrow_up, 0)
            binding.layoutAsset.visible()
            binding.layoutPerson.visible()
            if (!TextUtils.isEmpty(info.performance)) {
                binding.layoutPerformance.visible()
            } else {
                binding.layoutPerformance.gone()
            }
            if (!TextUtils.isEmpty(info.equitment)) {
                binding.layoutDevice.visible()
            } else {
                binding.layoutDevice.gone()
            }
        } else {
            binding.tvMore.text = "展开更多资质说明"
            binding.tvMore.setCompoundDrawablesWithIntrinsicBounds(0 , 0, R.mipmap.ic_more_arrow_down, 0)
            binding.layoutAsset.gone()
            binding.layoutPerson.gone()
            binding.layoutPerformance.gone()
            binding.layoutDevice.gone()
        }
    }
}