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 androidx.fragment.app.DialogFragment
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cheng.blzb.R
import com.cheng.blzb.bean.ContactsEntity
import com.cheng.blzb.databinding.DialogSelectContactsBinding
import com.cheng.blzb.event.ContactsEvent
import com.cheng.blzb.manager.ContactsManager
import com.cheng.blzb.ui.activity.PublicActivity
import com.cheng.blzb.ui.fragment.bid.publish.contacts.AddContactsFragment
import com.example.base.common.RxBus
import com.example.base.extensions.onClick
import com.example.base.extensions.toast
import com.example.base.utils.ScreenUtils
import com.example.base.widget.EmptyView
import com.example.base.widget.PageStatus
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import io.reactivex.disposables.Disposable

class SelectContactsDialog : DialogFragment() {
    private val mAdapter by lazy { ContactsAdapter() }

    private val mEmptyView by lazy { EmptyView(requireContext()) }

    private var contactsEvent: Disposable? = null

    private var mOnBackListener: ((List<ContactsEntity>) -> Unit)? = null     //回调事件

    private lateinit var binding: DialogSelectContactsBinding

    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_contacts, null)

        binding = DialogSelectContactsBinding.bind(view)

        binding.mRecyclerView.adapter = mAdapter
        mEmptyView.setNoDataLogo(R.mipmap.ic_empty_contacts)
        mEmptyView.setNoDataText("暂无联系人信息")
        mAdapter.setEmptyView(mEmptyView)

        mAdapter.setOnItemClickListener { _, _, i ->
            val item = mAdapter.getItem(i)
            item.isChecked = !item.isChecked
            mAdapter.notifyDataSetChanged()

            binding.tvTitle.text = "已选择${mAdapter.data.filter { it.isChecked }.size}人"
        }

        mAdapter.setOnItemChildClickListener { _, _, i ->
            PublicActivity.start(requireContext(), AddContactsFragment::class.java, Pair("item", mAdapter.getItem(i)))
        }

        binding.btnAdd.onClick {
            PublicActivity.start(requireContext(), AddContactsFragment::class.java)
        }

        binding.btnNext.onClick {
            val selectList = mAdapter.data.filter { it.isChecked }
            if (selectList.isEmpty()) {
                toast("请选择联系人")
                return@onClick
            }
            mOnBackListener?.invoke(selectList)
            dismiss()
        }

        binding.ivClose.onClick { dismiss() }

        contactsEvent = RxBus.defaultInstance.toObservable(ContactsEvent::class.java).subscribe {
            if (it.type == ContactsEvent.TYPE_ADD) {
                setData(false, it.contacts.id)
            } else {
                setData(false)
            }
        }

        setData(true)

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

    private fun setData(init: Boolean, checkedId: String = "") {
        val selectList = if (init) {
            val listStr = arguments?.getString("list") ?: ""
            if (!TextUtils.isEmpty(listStr)) {
                Gson().fromJson(listStr, object : TypeToken<MutableList<ContactsEntity>>() {}.type)
            } else mutableListOf()
        } else {
            mAdapter.data.filter { it.isChecked }
        }

        val contactsList = ContactsManager.all()
        contactsList.forEach { contacts ->
            if (selectList.find { it.id == contacts.id } != null || contacts.id == checkedId) {
                contacts.isChecked = true
            }
        }
        mAdapter.setList(contactsList)
        if (mAdapter.data.isNotEmpty()) {
            mEmptyView.setStatus(PageStatus.GONG)
        } else {
            mEmptyView.setStatus(PageStatus.NO_DATA)
        }
        binding.tvTitle.text = "已选择${mAdapter.data.filter { it.isChecked }.size}人"
    }

    override fun onDestroyView() {
        contactsEvent?.dispose()
        super.onDestroyView()
    }

    fun setOnSelectListener(listener: ((List<ContactsEntity>) -> Unit)) {
        mOnBackListener = listener
    }

    companion object {
        fun newInstance(list: List<ContactsEntity>): SelectContactsDialog {
            val arg = Bundle()
            arg.putString("list", Gson().toJson(list))
            val fragment = SelectContactsDialog()
            fragment.arguments = arg
            return fragment
        }
    }

    class ContactsAdapter : BaseQuickAdapter<ContactsEntity, BaseViewHolder>(R.layout.listitem_contacts) {

        init {
            addChildClickViewIds(R.id.iv_edit)
        }

        override fun convert(holder: BaseViewHolder, item: ContactsEntity) {
            holder.setText(R.id.tv_phone, item.phone)
            holder.setText(R.id.tv_name, "${item.name} | ${item.job}")
            holder.setImageResource(R.id.iv_check, if (item.isChecked) R.mipmap.ic_rb_checked else R.mipmap.ic_rb_default)
        }

    }
}