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

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.FragmentQyzcBinding
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.google.gson.JsonObject
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import okhttp3.RequestBody.Companion.toRequestBody
import java.util.concurrent.TimeUnit

class QYZCFragment : BaseFragment<FragmentQyzcBinding, QYZCViewModel>() {
    private var timestamp = ""

    private var city: AreaEntity? = null

    private val companyAdapter by lazy { QYZCCompanyAdapter(requireContext(), companyList) }
    private val companyList = mutableListOf<String>()

    private var scrollTask: Disposable? = null

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

        binding.mTitleBar.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                (binding.rvCompany.layoutParams as ConstraintLayout.LayoutParams).topMargin = binding.mTitleBar.height
                binding.mTitleBar.viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        })
    }

    override fun initData() {
        super.initData()
        companyList.addAll(QYZCCompanyAdapter.getList())
        binding.rvCompany.adapter = companyAdapter
    }

    override fun initListener() {
        super.initListener()

        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", "company_register")
            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 startScroll() {
        if (companyList.isEmpty() || scrollTask != null) return
        scrollTask = Observable.interval(300, 9, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                if (activity != null) {
                    binding.rvCompany.scrollBy(3, 0)
                }
            }
    }

    private fun stopScroll() {
        scrollTask?.dispose()
        scrollTask = null
    }

    override fun onStart() {
        startScroll()
        super.onStart()
    }

    override fun onStop() {
        stopScroll()
        super.onStop()
    }
}