package com.casic.br.view

import android.os.Handler
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.casic.br.R
import com.casic.br.adapter.AddressListAdapter
import com.casic.br.model.AddressListModel
import com.casic.br.utils.DeserializeModel
import com.casic.br.utils.LoadingDialogHub
import com.casic.br.vm.AddressViewModel
import com.gyf.immersionbar.ImmersionBar
import com.pengxh.kt.lite.base.KotlinBaseActivity
import com.pengxh.kt.lite.extensions.convertColor
import com.pengxh.kt.lite.extensions.navigatePageTo
import com.pengxh.kt.lite.extensions.show
import com.pengxh.kt.lite.utils.ImmerseStatusBarUtil
import com.pengxh.kt.lite.utils.WeakReferenceHandler
import com.pengxh.kt.lite.vm.LoadState
import com.pengxh.kt.lite.widget.dialog.AlertControlDialog
import com.qmuiteam.qmui.recyclerView.QMUIRVItemSwipeAction
import com.qmuiteam.qmui.recyclerView.QMUISwipeAction
import kotlinx.android.synthetic.main.activity_manage_address.*
import kotlinx.android.synthetic.main.include_base_title.*
import kotlinx.android.synthetic.main.include_empty_view.*


class AddressManagerActivity : KotlinBaseActivity() {

    private val kTag = "AddressManagerActivity"
    private lateinit var weakReferenceHandler: WeakReferenceHandler
    private lateinit var addressViewModel: AddressViewModel
    private lateinit var addressAdapter: AddressListAdapter
    private var dataBeans: MutableList<AddressListModel.DataModel.RowsModel> = ArrayList()
    private var pageIndex = 1
    private var isRefresh = false
    private var isLoadMore = false
    private var clickedPosition = 0

    override fun initLayoutView(): Int = R.layout.activity_manage_address

    override fun setupTopBarLayout() {
        ImmersionBar.with(this).statusBarDarkFont(true).init()
        ImmerseStatusBarUtil.setColor(this, R.color.white.convertColor(this))

        leftBackView.setOnClickListener { finish() }
        titleView.text = "地址管理"
    }

    override fun initData() {
        weakReferenceHandler = WeakReferenceHandler(callback)
        addressViewModel = ViewModelProvider(this)[AddressViewModel::class.java]
        addressViewModel.listModel.observe(this, {
            if (it.code == 200) {
                val dataRows = it.data?.rows
                when {
                    isRefresh -> {
                        dataBeans.clear()
                        dataBeans = dataRows!!
                        addressLayout.finishRefresh()
                        isRefresh = false
                    }
                    isLoadMore -> {
                        if (dataRows?.size == 0) {
                            "到底了，别拉了".show(this)
                        }
                        dataBeans.addAll(dataRows!!)
                        addressLayout.finishLoadMore()
                        isLoadMore = false
                    }
                    else -> {
                        dataBeans = dataRows!!
                    }
                }
                weakReferenceHandler.sendEmptyMessage(2022100901)
            }
        })
    }

    override fun initEvent() {
        addressLayout.setOnRefreshListener {
            isRefresh = true
            //刷新之后页码重置
            pageIndex = 1
            obtainAddressListByPage()
        }
        addressLayout.setOnLoadMoreListener {
            isLoadMore = true
            pageIndex++
            obtainAddressListByPage()
        }

        addressViewModel.deleteResult.observe(this, {
            if (it.code == 200) {
                dataBeans.removeAt(clickedPosition)
                addressAdapter.notifyItemRemoved(clickedPosition)
                addressAdapter.notifyItemRangeChanged(
                    clickedPosition, dataBeans.size - clickedPosition
                )
            }
        })

        addAddressButton.setOnClickListener {
            if (DeserializeModel.isLogin()) {
                navigatePageTo<AddressActivity>()
            } else {
                navigatePageTo<LoginActivity>()
            }
        }
    }

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

    private fun obtainAddressListByPage() {
        addressViewModel.obtainAddressListByPage("", "", "", "", pageIndex)
    }

    private val callback = Handler.Callback {
        if (it.what == 2022100901) {
            if (isRefresh || isLoadMore) {
                addressAdapter.notifyDataSetChanged()
            } else {
                addressAdapter = AddressListAdapter(this, dataBeans)
                //绑定侧滑事件
                swipeAction.attachToRecyclerView(addressRecyclerView)
                val linearLayoutManager = object : LinearLayoutManager(this) {
                    override fun generateDefaultLayoutParams(): RecyclerView.LayoutParams {
                        return RecyclerView.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT
                        )
                    }
                }
                addressRecyclerView.layoutManager = linearLayoutManager
                addressRecyclerView.adapter = addressAdapter
                addressAdapter.setOnItemClickListener(object :
                    AddressListAdapter.OnItemClickListener {
                    override fun onEditButtonClicked(position: Int) {
                        navigatePageTo<AddressActivity>(dataBeans[clickedPosition].id)
                    }
                })
            }
        }
        true
    }

    private val swipeAction =
        QMUIRVItemSwipeAction(true, object : QMUIRVItemSwipeAction.Callback() {

            //滑动拉出菜单删除
            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                clickedPosition = viewHolder.bindingAdapterPosition
                //删除数据库里对应的数据
                addressViewModel.deleteAddressById(dataBeans[clickedPosition].id)
            }

            override fun getSwipeDirection(
                recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder
            ): Int {
                return QMUIRVItemSwipeAction.SWIPE_LEFT
            }

            //滑动拉出菜单，点击删除
            override fun onClickAction(
                swipeAction: QMUIRVItemSwipeAction?,
                selected: RecyclerView.ViewHolder?,
                action: QMUISwipeAction?
            ) {
                super.onClickAction(swipeAction, selected, action)
                deleteItem(selected!!.bindingAdapterPosition)
            }
        })

    private fun deleteItem(adapterPosition: Int) {
        AlertControlDialog.Builder()
            .setContext(this)
            .setTitle("提示")
            .setMessage("删除后将无法恢复，是否继续？")
            .setNegativeButton("容我想想")
            .setPositiveButton("已经想好")
            .setOnDialogButtonClickListener(object :
                AlertControlDialog.OnDialogButtonClickListener {
                override fun onCancelClick() {

                }

                override fun onConfirmClick() {
                    clickedPosition = adapterPosition
                    //删除数据库里对应的数据
                    addressViewModel.deleteAddressById(dataBeans[clickedPosition].id)
                }
            }).build().show()
    }

    override fun observeRequestState() {
        addressViewModel.loadState.observe(this, {
            when (it) {
                LoadState.Loading -> {
                    //刷新不显示Loading
                    if (isRefresh || isLoadMore) {
                        return@observe
                    }
                    LoadingDialogHub.show(this, "数据加载中...")
                }
                else -> LoadingDialogHub.dismiss()
            }
        })
    }
}