package com.cheng.blzb.ui.fragment.merchant.detail

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Build
import android.text.TextUtils
import android.view.ViewTreeObserver
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.net.toUri
import androidx.viewpager2.widget.ViewPager2
import com.cheng.blzb.R
import com.cheng.blzb.bean.MerchantGoodsEntity
import com.cheng.blzb.common.Constants
import com.cheng.blzb.common.EventConstants
import com.cheng.blzb.databinding.FragmentMerchantGoodsDetailBinding
import com.cheng.blzb.manager.EventReportManager
import com.cheng.blzb.ui.activity.PublicActivity
import com.cheng.blzb.ui.fragment.merchant.MerchantContactsAdapter
import com.cheng.blzb.ui.fragment.merchant.home.MerchantHomeFragment
import com.cheng.blzb.ui.fragment.photo.PhotoViewFragment
import com.example.base.decoration.SpacesItemDecoration
import com.example.base.extensions.gone
import com.example.base.extensions.onClick
import com.example.base.extensions.visible
import com.example.base.ui.BaseFragment
import com.example.base.utils.DensityUtils
import com.example.base.utils.SpanUtils
import java.text.DecimalFormat

class MerchantGoodsDetailFragment : BaseFragment<FragmentMerchantGoodsDetailBinding, MerchantGoodsDetailViewModel>() {
    private val id by lazy { arguments?.getString("id") ?: "" }
    private var goodsInfo: MerchantGoodsEntity? = null

    private val contactsAdapter by lazy { MerchantContactsAdapter() }
    private val imageAdapter by lazy { MerchantGoodsImageAdapter() }

    override fun initView() {
        super.initView()
        mTitleBar?.background = null
        binding.tvPrice.typeface = Constants.dDIN_PRO_M

        binding.viewPager.adapter = imageAdapter

        binding.rvContacts.adapter = contactsAdapter
        binding.rvContacts.addItemDecoration(SpacesItemDecoration(DensityUtils.dp2px(8f)))

        binding.ivTopBg.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                (binding.viewPager.layoutParams as ConstraintLayout.LayoutParams).topMargin = binding.mTitleBar.height + DensityUtils.dp2px(10f)
                (binding.layoutContent.layoutParams as ConstraintLayout.LayoutParams).topMargin = (binding.viewPager.height * 276f / 343f).toInt()
                binding.layoutContent.setupWith(binding.root).setFrameClearDrawable(binding.layoutContent.background).setBlurRadius(5f)
                binding.ivTopBg.viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        })
    }

    override fun initData() {
        super.initData()
        goodsInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arguments?.getSerializable("item", MerchantGoodsEntity::class.java)
        } else {
            arguments?.getSerializable("item") as? MerchantGoodsEntity
        }
        if (goodsInfo != null) {
            setData()
            EventReportManager.eventReport(EventConstants.JUMP_TO_GOODS_DETAIL, "", "{\"id\": ${goodsInfo!!.id}}")
        } else {
            mViewModel.getGoodsInfo(id)
            EventReportManager.eventReport(EventConstants.JUMP_TO_GOODS_DETAIL, "", "{\"id\": ${id}}")
        }
    }

    override fun initListener() {
        super.initListener()
        binding.btnNext.onClick {
            PublicActivity.start(requireActivity(), MerchantHomeFragment::class.java, Pair("item", goodsInfo))
        }

        binding.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            @SuppressLint("SetTextI18n")
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                binding.tvIndicator.text = "${position + 1}/${imageAdapter.data.size}"
            }
        })

        imageAdapter.setOnItemClickListener { _, _, position ->
            val urlList = imageAdapter.data.map { it.url }
            PublicActivity.start(requireContext(), PhotoViewFragment::class.java, Pair("photos", urlList), Pair("index", position))
        }

        contactsAdapter.setOnItemChildClickListener { _, view, i ->
            val item = contactsAdapter.getItem(i)
            when (view.id) {
                R.id.iv_call -> {
                    val intent = Intent(Intent.ACTION_DIAL, "tel:${item.phone}".toUri())
                    startActivity(intent)
                }
            }
        }
    }

    override fun initObserve() {
        super.initObserve()
        mViewModel.infoLiveData.observe(this) {
            goodsInfo = it
            setData()
        }
    }

    @SuppressLint("SetTextI18n")
    private fun setData() {
        if (goodsInfo != null) {
            if (!TextUtils.isEmpty(goodsInfo!!.company.company_name)) {
                if (goodsInfo!!.company.company_name!!.length >= 4) {
                    binding.tvCompanyAvatar.text = goodsInfo!!.company.company_name!!.substring(0, 2) + "\n" + goodsInfo!!.company.company_name!!.substring(2, 4)
                } else if (goodsInfo!!.company.company_name!!.length == 3) {
                    binding.tvCompanyAvatar.text = goodsInfo!!.company.company_name!!.substring(0, 2) + "\n" + goodsInfo!!.company.company_name!![2]
                } else {
                    binding.tvCompanyAvatar.text = goodsInfo!!.company.company_name
                }
                binding.tvCompanyName.text = goodsInfo!!.company.company_name
                binding.tvCompanyCity.text = goodsInfo!!.company.city_name
                binding.tvExtra.text = if (!TextUtils.isEmpty(goodsInfo!!.company.extra?.toString())) goodsInfo!!.company.extra.toString() else "无"
                binding.layoutCompanyInfo.visible()
            } else {
                binding.layoutCompanyInfo.gone()
            }
            contactsAdapter.setList(goodsInfo!!.contact)
            imageAdapter.setList(goodsInfo!!.file)
            binding.tvIndicator.text = "1/${imageAdapter.data.size}"

            binding.tvGoodsName.text = goodsInfo!!.goods_name

            try {
                if (goodsInfo!!.goods_price.toFloat() > 100000000) {
                    SpanUtils.with(binding.tvPrice)
                        .append(DecimalFormat("0.##").format(goodsInfo!!.goods_price.toFloat() / 100000000))
                        .appendSpace(DensityUtils.dp2px(4f))
                        .append("亿")
                        .setFontSize(12, true)
                        .create()
                } else if (goodsInfo!!.goods_price.toFloat() > 10000) {
                    SpanUtils.with(binding.tvPrice)
                        .append(DecimalFormat("0.##").format(goodsInfo!!.goods_price.toFloat() / 10000))
                        .appendSpace(DensityUtils.dp2px(4f))
                        .append("万")
                        .setFontSize(12, true)
                        .create()
                } else {
                    binding.tvPrice.text = DecimalFormat("0.##").format(goodsInfo!!.goods_price.toFloat())
                }
            } catch (e: Exception) {
                binding.tvPrice.text = goodsInfo!!.goods_price
            }

            binding.tvLocation.text = if (TextUtils.isEmpty(goodsInfo!!.city_name)) "全国" else goodsInfo!!.city_name
            binding.tvViewCount.text = "已浏览 ${if (!TextUtils.isEmpty(goodsInfo!!.view_count)) goodsInfo!!.view_count else 0}"

            mViewModel.sendAuth()
        }
    }
}