package com.cheng.blzb.ui.dialog

import android.annotation.SuppressLint
import android.app.Dialog
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.DialogFragment
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.example.base.extensions.getColor
import com.example.base.extensions.getYYYYMMDD2
import com.example.base.extensions.gone
import com.example.base.extensions.onClick
import com.example.base.extensions.visible
import com.example.base.utils.ScreenUtils
import com.example.base.utils.SpanUtils
import com.example.base.widget.EmptyView
import com.example.base.widget.PageStatus
import com.cheng.blzb.R
import com.cheng.blzb.common.Constants
import com.cheng.blzb.databinding.DialogSelectCouponBinding
import com.cheng.blzb.ui.fragment.mine.vip.VipFragment
import java.text.DecimalFormat

class SelectCouponDialog : DialogFragment() {
    private val id by lazy { arguments?.getString("id") ?: "" }
    private val price by lazy { arguments?.getString("price") ?: "" }

    private val mAdapter by lazy { CouponAdapter(price) }
    private val mEmptyView by lazy { EmptyView(requireContext()) }
    private var mOnBackListener: ((com.cheng.blzb.bean.CouponEntity?) -> Unit)? = null
    private var selectedCoupon: com.cheng.blzb.bean.CouponEntity? = null

    lateinit var binding: DialogSelectCouponBinding

    override fun onStart() {
        super.onStart()
        val window = dialog?.window
        val windowParams = window?.attributes
        windowParams?.dimAmount = 0.7f
        windowParams?.width = ScreenUtils.getWindowSize().x
        windowParams?.gravity = Gravity.BOTTOM
        windowParams?.windowAnimations = R.style.dialog_bottom
        dialog?.window?.attributes = windowParams
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val view = layoutInflater.inflate(R.layout.dialog_select_coupon, null)

        binding = DialogSelectCouponBinding.bind(view)

        binding.mRecyclerView.adapter = mAdapter
        mEmptyView.setBtnVisible(false)
        mAdapter.setEmptyView(mEmptyView)

        mAdapter.setOnItemClickListener { _, _, i ->
            val item = mAdapter.getItem(i)
            if (TextUtils.isEmpty(item.threshold) || item.threshold.toFloat() / 100 <= price.toFloat()) {
                mAdapter.data.forEach {
                    if (it.id == item.id) {
                        it.isChecked = !it.isChecked
                    } else {
                        it.isChecked = false
                    }
                }
                selectedCoupon = if (item.isChecked) item else null
                mAdapter.notifyDataSetChanged()
            }
        }

        binding.ivClose.onClick {
            dismiss()
        }
        binding.btnNext.onClick {
            mOnBackListener?.invoke(selectedCoupon)
            dismiss()
        }

        initData()

        val dialog = Dialog(requireContext())
        dialog.setContentView(view)
        return dialog
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun initData() {
        val fragment = requireParentFragment()
        if (fragment is VipFragment) {
            fragment.mViewModel.couponListLiveData.observe(this) { list ->
                mAdapter.setList(list)
                mAdapter.data.forEach {
                    if (it.id == id) {
                        it.isChecked = true
                        selectedCoupon = it
                    }
                }
                mAdapter.notifyDataSetChanged()
                if (mAdapter.data.isEmpty()) {
                    mEmptyView.setStatus(PageStatus.NO_DATA)
                    binding.layoutBottom.gone()
                } else {
                    mEmptyView.setStatus(PageStatus.GONG)
                    binding.layoutBottom.visible()
                }
            }
            fragment.mViewModel.couponList()
        }
    }

    fun setOnBackListener(listener: (com.cheng.blzb.bean.CouponEntity?) -> Unit) {
        mOnBackListener = listener
    }

    companion object {
        fun newInstance(id: String?, price: String): SelectCouponDialog {
            val args = Bundle()
            args.putString("id", id)
            args.putString("price", price)
            val fragment = SelectCouponDialog()
            fragment.arguments = args
            return fragment
        }
    }

    internal class CouponAdapter(private val price: String) : BaseQuickAdapter<com.cheng.blzb.bean.CouponEntity, BaseViewHolder>(R.layout.listitem_coupon_dialog) {

        override fun convert(holder: BaseViewHolder, item: com.cheng.blzb.bean.CouponEntity) {
            holder.setText(
                R.id.tv_name,
                if (!TextUtils.isEmpty(item.coupon_name)) item.coupon_name else "${item.coupon_value_name}${item.coupon_type_name}"
            )
            holder.setText(R.id.tv_expire_time, "有效期至 ${(item.expire_timestamp.toLong() * 1000).getYYYYMMDD2()}")
            holder.setText(R.id.tv_type, item.coupon_type_name)
            holder.getView<TextView>(R.id.tv_discount_amount).typeface = Constants.dDIN_PRO_M
            when (item.coupon_type) {
                com.cheng.blzb.bean.CouponEntity.TYPE_CASH -> {
                    SpanUtils.with(holder.getView(R.id.tv_discount_amount))
                        .append("￥")
                        .setFontSize(12, true)
                        .append(DecimalFormat("0.##").format(item.coupon_value.toFloat() / 100))
                        .create()
                    if (!TextUtils.isEmpty(item.threshold)) {
                        holder.setText(R.id.tv_threshold_amount, "满${DecimalFormat("0.##").format(item.threshold.toFloat() / 100)}可用")
                    } else {
                        holder.setText(R.id.tv_threshold_amount, "无门槛")
                    }
                }

                com.cheng.blzb.bean.CouponEntity.TYPE_DISCOUNT -> {
                    SpanUtils.with(holder.getView(R.id.tv_discount_amount))
                        .append(DecimalFormat("0.##").format(item.coupon_value.toFloat() * 10))
                        .append("折")
                        .setFontSize(12, true)
                        .create()
                    if (!TextUtils.isEmpty(item.threshold)) {
                        holder.setText(R.id.tv_threshold_amount, "满${DecimalFormat("0.##").format(item.threshold.toFloat() / 100)}可用")
                    } else {
                        holder.setText(R.id.tv_threshold_amount, "无门槛")
                    }
                }
            }

            if (TextUtils.isEmpty(item.threshold) || item.threshold.toFloat() / 100 <= price.toFloat()) {
                holder.setTextColor(R.id.tv_discount_amount, getColor(R.color.color_ff5846))
                holder.setTextColor(R.id.tv_threshold_amount, getColor(R.color.color_ff5846))
                holder.setBackgroundResource(R.id.layout_amount, R.drawable.shape_fdf4f2_cor6)
                holder.setImageResource(R.id.iv_check, if (item.isChecked) R.mipmap.ic_coupon_check_true else R.mipmap.ic_coupon_check_false)
            } else {
                holder.setTextColor(R.id.tv_discount_amount, getColor(R.color.color_d8d8d8))
                holder.setTextColor(R.id.tv_threshold_amount, getColor(R.color.color_d8d8d8))
                holder.setBackgroundResource(R.id.layout_amount, R.drawable.shape_f6f6f6_cor6)
                holder.setImageResource(R.id.iv_check, R.mipmap.ic_coupon_check_disable)
            }
        }
    }
}