package com.pan_american.android.ui.customer_resource.related_invitee

import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.bin.david.form.core.SmartTable
import com.pan_american.android.OASystem
import com.pan_american.android.R
import com.pan_american.android.base.BaseFragment
import com.pan_american.android.base.ListAdapter
import com.pan_american.android.data.model.customer_resource.related_invitee.entity.RelatedInviteeGroupListItem
import com.pan_american.android.data.model.customer_resource.related_invitee.entity.RelatedInviteeListItem
import com.pan_american.android.data.model.customer_resource.related_invitee.network.RelatedInviteeListRequest
import com.pan_american.android.data.model.customer_resource.related_invitee.network.RelatedInviteeListResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentRelatedInviteeListBinding
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class RelatedInviteeListFragment : BaseFragment<FragmentRelatedInviteeListBinding>() {

    private val relatedInviteeListRequest = RelatedInviteeListRequest()

    private var pageIndex = 1

    private var totalPage = 0

    private val apiService = ServiceCreator.create<APIService>()

    private var listInit = false

    private var relatedInviteeGroupList = ArrayList<RelatedInviteeGroupListItem>()

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
        bundle: Bundle?
    ) = FragmentRelatedInviteeListBinding.inflate(layoutInflater, container, false)

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        requireArguments().apply {
            relatedInviteeListRequest.counrty = getString("country", "")
            relatedInviteeListRequest.area = getString("city", "")
            relatedInviteeListRequest.teamName = getString("group_name", "")
            relatedInviteeListRequest.unitName = getString("invitee_name", "")
        }

        relatedInviteeListRequest.pageIndex = pageIndex
        relatedInviteeListRequest.pageSize = 10

        initViews()
    }

    override fun initViews() {
        binding.relatedInviteeListContainer.setRefreshHeader(ClassicsHeader(OASystem.context))
        binding.relatedInviteeListContainer.setRefreshFooter(ClassicsFooter(OASystem.context))

        initRelatedInviteeGroupList(1)
    }

    private fun initRelatedInviteeGroupList(type: Int) {

        if (!isAdded) {
            return
        }

        apiService.getRelatedInviteeGroupList(relatedInviteeListRequest).enqueue(object :
            Callback<RelatedInviteeListResponse> {
            override fun onResponse(
                p0: Call<RelatedInviteeListResponse>,
                response: Response<RelatedInviteeListResponse>
            ) {
                val listResponse = response.body()

                if (listResponse != null) {
                    if (listResponse.code == 200) {

                        for (item in listResponse.data) {
                            relatedInviteeGroupList.add(item)
                        }

                        when (type) {
                            1 -> {
                                totalPage = getTotalPage(listResponse.count)
                                binding.relatedInviteeListContainer.setEnableLoadMore(pageIndex < totalPage)
                                initList()
                                listInit = true
                            }

                            2 -> {
                                binding.relatedInviteeListContainer.finishRefresh()
                                totalPage = getTotalPage(listResponse.count)
                                binding.relatedInviteeListContainer.setEnableLoadMore(pageIndex < totalPage)
                                initList()
                                listInit = true
                            }

                            3 -> {
                                binding.relatedInviteeListContainer.finishLoadMore()
                                binding.relatedInviteeListContainer.setEnableLoadMore(pageIndex < totalPage)
                                binding.relatedInviteeList.adapter!!.notifyItemInserted(relatedInviteeGroupList.size)
                                listInit = true
                            }
                        }

                    } else {
                        showMessage(listResponse.msg)
                    }
                }
            }

            override fun onFailure(p0: Call<RelatedInviteeListResponse>, p1: Throwable) {
                showErrorInfo(R.string.group_list_get_failed)
            }
        })
    }

    private fun initList() {
        if (relatedInviteeGroupList.size == 0) {
            return
        }

        val layoutManager = LinearLayoutManager(OASystem.context)
        binding.relatedInviteeList.layoutManager = layoutManager

        val adapter = ListAdapter.Builder<RelatedInviteeGroupListItem>().apply {
            setData(relatedInviteeGroupList)
            setLayoutId(R.layout.item_related_invitee_group_list)
            addBindView { itemView, data ->
                itemView.findViewById<TextView>(R.id.group_name).text = data.teamName
                itemView.findViewById<TextView>(R.id.customer_company).text = data.clientUnit
                itemView.findViewById<TextView>(R.id.client_name).text = data.clientName
                itemView.findViewById<TextView>(R.id.start_time).text = data.visitStartDate.substring(0, 10)
                itemView.findViewById<TextView>(R.id.end_time).text = data.visitEndDate.substring(0, 10)
                itemView.findViewById<TextView>(R.id.days).text = data.visitDays.toString()
                itemView.findViewById<TextView>(R.id.members).text = data.visitPNumber.toString()
                itemView.findViewById<TextView>(R.id.country).text = data.visitCountry
                itemView.findViewById<TextView>(R.id.director).text = data.jietuanOperator
            }
        }.create()

        binding.relatedInviteeList.adapter = adapter

        adapter.onRecyclerViewItemClick = object : ListAdapter.OnRecyclerViewItemClick<RelatedInviteeGroupListItem> {
            override fun onItemClick(position: Int) {
                val relatedInviteePopView = View.inflate(OASystem.context, R.layout.popup_table, null)
                popupWindow = PopupWindow(relatedInviteePopView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)

                showPopupWindow {
                    val relatedInviteeTable = relatedInviteePopView.findViewById<SmartTable<RelatedInviteeListItem>>(R.id.table)
                    val title = relatedInviteePopView.findViewById<TextView>(R.id.title)

                    title.text = resources.getString(R.string.group_related_invitee)

                    relatedInviteeTable.config.apply {
                        isShowTableTitle = false
                        isShowXSequence = false
                        isShowYSequence = false
                        verticalPadding = resources.getDimensionPixelSize(R.dimen.common_padding)
                        minTableWidth = relatedInviteeTable.width
//                        columnTitleStyle = FontStyle(resources.getDimensionPixelSize(R.dimen.text_size_large), ResourcesCompat.getColor(resources, R.color.text_color, null))
//                        contentStyle = FontStyle(resources.getDimensionPixelSize(R.dimen.text_size_medium), ResourcesCompat.getColor(resources, R.color.text_color, null))
                    }

                    relatedInviteeTable.apply {
                        setZoom(false)
                        setData(relatedInviteeGroupList[position].invitingInfos)
                    }

                    popupWindow.showAtLocation(binding.root, Gravity.BOTTOM, 0, 0)
                }
            }
        }

        binding.relatedInviteeListContainer.setOnRefreshLoadMoreListener(object :
            OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex = 1
                relatedInviteeListRequest.pageIndex = pageIndex
                binding.relatedInviteeList.adapter!!.notifyItemRangeRemoved(0, relatedInviteeGroupList.size)
                relatedInviteeGroupList.clear()
                listInit = false
                initRelatedInviteeGroupList(2)
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                if (pageIndex < totalPage) {
                    pageIndex += 1
                    relatedInviteeListRequest.pageIndex = pageIndex
                    listInit = false
                    initRelatedInviteeGroupList(3)
                }
            }
        })
    }

    private fun getTotalPage(dataCount: Int): Int {
        var totalPage = dataCount / 10
        if (dataCount % 10 != 0) {
            totalPage++
        }

        return totalPage
    }
}