package com.rdiot.yx485.ui.family

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.widget.AppCompatEditText
import androidx.core.widget.doAfterTextChanged
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.drake.brv.annotaion.DividerOrientation
import com.drake.brv.utils.bindingAdapter
import com.drake.brv.utils.divider
import com.drake.brv.utils.setup
import com.drake.net.utils.TipUtils
import com.drake.net.utils.scopeDialog
import com.drake.net.utils.scopeNetLife
import com.google.android.flexbox.FlexboxLayoutManager
import com.king.zxing.util.LogUtils
import com.lindroy.iosdialog.IAlertDialog
import com.rdiot.yx485.R
import com.rdiot.yx485.base.BaseFragment
import com.rdiot.yx485.base.FamilyDataModelFactory
import com.rdiot.yx485.base.LocalData
import com.rdiot.yx485.bean.FamilyData
import com.rdiot.yx485.bean.MemberData
import com.rdiot.yx485.databinding.FraFamilyInfoBinding
import com.rdiot.yx485.databinding.ItemMemberBinding
import com.rdiot.yx485.net.*
import com.rdiot.yx485.ui.family.model.FamilyDataViewModel
import com.rdiot.yx485.util.setClickLimitListener
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 家庭信息维护
 * @author mR2hao
 * @date 2022/12/28
 */
class FamilyInfoFragment : BaseFragment<FraFamilyInfoBinding>() {
    override fun getLayoutId() = R.layout.fra_family_info

    companion object {
        private const val ADD_MEMBER = "icon_member_add"
    }

    private lateinit var familyData: FamilyData
    private var dialog: IAlertDialog? = null
    private val familyDataViewModel: FamilyDataViewModel by activityViewModels { FamilyDataModelFactory() }

    override fun initView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ) {

        binding.nb.let {
            it.setLeftClickListener { findNavController().popBackStack() }
            it.setRightClickListener { binding.rv.bindingAdapter.toggle() }
        }

        /** 删除家庭 */
        binding.btnDelFamily.setClickLimitListener {
            showDeleteFamilyDialog()
        }


        familyData = familyDataViewModel.selFamilyData!!
        binding.rv.layoutManager = FlexboxLayoutManager(act)
        binding.rv.divider {
            setDivider(5, true)
            orientation = DividerOrientation.GRID
            includeVisible = true
        }.setup {
            addType<MemberData>(R.layout.item_member)

            onBind {
                val model = this.getModel<MemberData>()
                val bind = getBinding<ItemMemberBinding>()


                //主用户一直不可点击状态
                if (model.userId == familyData.adminId) {
                    return@onBind
                } else if (model.photo == ADD_MEMBER) {    //添加按钮一直可点击
                    bind.clItem.setClickLimitListener {
                        itemClickHandler(this.getModel() as MemberData)
                    }
                } else if (binding.rv.bindingAdapter.toggleMode) {    //其余编辑状态可点击
                    bind.clItem.setClickLimitListener {
                        itemClickHandler(this.getModel() as MemberData)
                    }
                }

            }

            onToggle { position, toggleMode, _ ->
                // 刷新列表显示选择按钮
                val model = getModel<MemberData>(position)
                if (model.userId != familyData.adminId && model.photo != ADD_MEMBER) {
                    model.isEditMode = toggleMode
                }
                binding.rv.bindingAdapter.notifyItemChanged(position)
                setToggleModeDisplay(toggleMode)
            }

        }.models = makeData(familyData)
    }

    private fun makeData(familyData: FamilyData): MutableList<MemberData> {
        binding.familyData = familyData
        val memberList = mutableListOf<MemberData>()

        memberList.addAll(familyData.member)
        memberList.add(MemberData(photo = ADD_MEMBER))
        return memberList
    }


    private fun itemClickHandler(memberData: MemberData) {
        if (memberData.photo == ADD_MEMBER) {
            findNavController().navigate(R.id.action_familyInfoFragment_to_addMemberFragment)
        } else {
            if (binding.rv.bindingAdapter.toggleMode) {
                showDeleteMemberDialog(memberData)
            } else {
                LogUtils.d("当前用户：${memberData}")
            }
        }
    }


    /** 删除用户 */
    private fun doDeleteMember(memberData: MemberData) {
        scopeDialog {
            deleteMember(memberData).await()
            delay(500)
            refreshData()
            TipUtils.toast(getString(R.string.delete_success))
        }
    }

    /** 删除房间 */
    private fun doDeleteFamily() {
        scopeDialog {
            deleteFamily(familyData.recordId).await()
            LocalData.allFamily.value?.let { allFamily ->
                allFamily.remove(familyData)
                if (familyData.isDefault && allFamily.isNotEmpty()) {
                    val firstFamilyData = allFamily.first()
                    LocalData.selFamilyId.postValue(firstFamilyData.recordId)
                    val getFamily = getFamilyData(firstFamilyData.recordId)
                    getFamily.await().also {
                        LocalData.familyData.postValue(it)
                    }

                    setDefaultFamily(firstFamilyData.recordId).await()
                }
            }

            delay(500)
            TipUtils.toast(getString(R.string.delete_success))
            findNavController().popBackStack()
        }
    }

    private fun setToggleModeDisplay(toggleMode: Boolean) {
        binding.editMode = toggleMode
        if (toggleMode) {
            binding.nb.setRightBtnText(R.string.finish)
            binding.nb.setRightBtnTextColor(R.color.login_btn_color)
            binding.llFamilyName.setClickLimitListener {
                showEditNameDialog()
            }
        } else {
            binding.nb.setRightBtnText(R.string.edit)
            binding.nb.setRightBtnTextColor(R.color.main_text_color)
            binding.llFamilyName.setClickLimitListener(null)
        }
    }

    /** 删除家庭Dialog */
    private fun showDeleteFamilyDialog() {
        dialog?.dismiss()
        dialog = IAlertDialog
            .build(this)
            .setTitle(R.string.hint)
            .setMessage(R.string.delete_family_hint)
            .setNegButtonText(R.string.cancel)
            .setNegButtonTextColor(resources.getColor(R.color.main_text_color, null))
            .setAlpha(1.0F)
            .setPosButtonText(R.string.delete_family)
            .setPosButtonTextColor(resources.getColor(R.color.warning, null))
            .setPosClickListener {
                doDeleteFamily()
            }
        dialog?.show()
    }

    private fun showDeleteMemberDialog(memberData: MemberData) {
        dialog?.dismiss()
        dialog = IAlertDialog
            .build(this)
            .setTitle(R.string.delete_member)
            .setMessage(R.string.delete_member_hint)
            .setCancelOutside(false)
            .setNegButtonText(R.string.cancel)
            .setNegButtonTextColor(resources.getColor(R.color.main_text_color, null))
            .setNegClickListener { dialogInterface ->
                dialogInterface.dismiss()
            }
            .setPosButtonText(R.string.del)
            .setPosClickListener { dialogInterface ->
                dialogInterface.dismiss()
                doDeleteMember(memberData)
            }
            .setDismissible(false)
            .setAlpha(1.0F)
            .setPosButtonTextColor(this.resources.getColor(R.color.warning, null))
        dialog?.show()
    }

    private fun showEditNameDialog() {
        val title = getString(R.string.set_family_name)
        val text = familyData.name
        val hint = getString(R.string.family_name)
        var inputText = ""
        dialog?.dismiss()
        dialog = IAlertDialog
            .build(this)
            .setTitle(title)
            .setContentView(R.layout.dialog_simple_edit)
            .setCancelOutside(false)
            .setNegButtonText(R.string.cancel)
            .setNegButtonTextColor(resources.getColor(R.color.main_text_color, null))
            .setNegClickListener { dialogInterface ->
                dialogInterface.dismiss()
            }
            .setPosClickListener { dialogInterface ->
                dialogInterface.dismiss()
                if (inputText.isNotBlank()) {
                    familyData.name = inputText
                    scopeNetLife {
                        updateFamilyData(familyData).await()
                        binding.familyData = familyData
                    }
                }

            }
            .setDismissible(false)
            .setAlpha(1.0F)
            .setPosButtonTextColor(this.resources.getColor(R.color.btn_blue, null))
            .setOnViewHandler { holder, _ ->
                lifecycleScope.launch {
                    (holder.getView(R.id.et) as AppCompatEditText).apply {
                        setText(text)
                        setHint(hint)

                        //延时弹出键盘
                        delay(300)
                        setSelection(text.length)
                        requestFocus()
                        val inputManager = act.getSystemService(
                            Context.INPUT_METHOD_SERVICE
                        ) as InputMethodManager
                        inputManager.showSoftInput(this, 0);

                        doAfterTextChanged {
                            inputText = it.toString()
                        }
                    }

                }
            }
        dialog?.show()
    }

    override fun onResume() {
        super.onResume()
        refreshData()
    }

    private fun refreshData() {
        scopeDialog {
            delay(100)
            getFamilyData(familyData.recordId).await().apply {
                binding.rv.bindingAdapter.models = makeData(this)
            }
        }
    }
}