package com.pan_american.android.ui.resource_management.hotel_resource

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
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.BaseResponse
import com.pan_american.android.base.CardAdapter
import com.pan_american.android.base.CustomAlertDialog
import com.pan_american.android.data.model.common.network.DeleteRequest
import com.pan_american.android.data.model.resource_management.hotel_resource.entity.HotelResource
import com.pan_american.android.data.model.resource_management.hotel_resource.network.HotelResourceRequest
import com.pan_american.android.data.model.resource_management.hotel_resource.network.HotelResourceResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentHotelResourceListBinding
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 HotelResourceListFragment : BaseFragment<FragmentHotelResourceListBinding>() {

    val apiService = ServiceCreator.create<APIService>()

    private var hotelList = ArrayList<HotelResource>()

    private var listInit = false

    private lateinit var hotelResourceRequest: HotelResourceRequest

    private var pageIndex = 1

    private var totalPage = 0

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

    override fun onStart() {
        super.onStart()

        requireArguments().apply {
            hotelResourceRequest = HotelResourceRequest(
                getString("hotel_name").toString(),
                getString("hotel_location").toString(),
                getString("contacts_name").toString(),
                getString("contacts_phone").toString()
            )
        }

        hotelResourceRequest.pageIndex = pageIndex
        hotelResourceRequest.pageSize = 10

        initViews()
    }

    override fun initViews() {
        binding.hotelResourceContainer.setRefreshHeader(ClassicsHeader(OASystem.context))
        binding.hotelResourceContainer.setRefreshFooter(ClassicsFooter(OASystem.context))
        initHotelResourceList(1)
    }

    private fun initHotelResourceList(type: Int) {

        //避免Fragment not attached to a context.
        if (!isAdded) {
            return
        }

        if (!listInit) {
            apiService.getHotelData(hotelResourceRequest)
                .enqueue(object : Callback<HotelResourceResponse> {
                    override fun onResponse(
                        call: Call<HotelResourceResponse>, response: Response<HotelResourceResponse>
                    ) {
                        val guideResourceResponse = response.body()
                        if (guideResourceResponse != null) {
                            if (guideResourceResponse.code == 200) {
                                for (item in guideResourceResponse.data.pageSource) {
                                    hotelList.add(item)
                                }
                                when (type) {
                                    1 -> {
                                        totalPage = guideResourceResponse.data.totalPage
                                        binding.hotelResourceContainer.setEnableLoadMore(pageIndex < totalPage)
                                        listInit = true
                                        initList()
                                    }

                                    2 -> {
                                        binding.hotelResourceContainer.finishRefresh()
                                        totalPage = guideResourceResponse.data.totalPage
                                        binding.hotelResourceContainer.setEnableLoadMore(pageIndex < totalPage)
                                        initList()
                                        listInit = true
                                    }

                                    3 -> {
                                        binding.hotelResourceContainer.finishLoadMore()
                                        binding.hotelResourceContainer.setEnableLoadMore(pageIndex < totalPage)
                                        binding.hotelResourceList.adapter!!.notifyItemInserted(
                                            hotelList.size
                                        )
                                        listInit = true
                                    }
                                }
                            } else {
                                showMessage(guideResourceResponse.msg)
                            }
                        }
                    }

                    override fun onFailure(call: Call<HotelResourceResponse>, t: Throwable) {
                        showMessage(resources.getString(R.string.network_error))
                    }
                })
        } else {
            if (OASystem.needRefresh) {
                pageIndex = 1
                hotelResourceRequest.pageIndex = pageIndex
                hotelList.clear()
                listInit = false
                initHotelResourceList(2)
            }
        }
    }

    private fun initList() {
        val layoutManager = LinearLayoutManager(OASystem.context)
        binding.hotelResourceList.layoutManager = layoutManager

        val adapter = CardAdapter.Builder<HotelResource>().apply {
            setLayoutId(R.layout.item_hotel_list)
            setData(hotelList)
            setCanDelete(OASystem.authorization(OASystem.HOTEL_RESOURCE, OASystem.DELETE))
            addBindView { itemView, data ->
                itemView.findViewById<TextView>(R.id.hotel_name).text = data.name
                itemView.findViewById<TextView>(R.id.hotel_location).text = data.city
                itemView.findViewById<TextView>(R.id.hotel_phone).text = data.tel
                itemView.findViewById<TextView>(R.id.hotel_level).text = data.level
                itemView.findViewById<TextView>(R.id.create_time).text = data.createTime
            }
        }.create()
        binding.hotelResourceList.adapter = adapter

        adapter.onRecyclerViewItemClick =
            object : CardAdapter.OnRecyclerViewItemClick<HotelResource> {
                override fun onItemClick(position: Int) {
                    val intent =
                        Intent(OASystem.context, AddHotelResourceActivity::class.java).apply {
                            putExtra("hotelResource", hotelList[position])
                            putExtra("fromList", true)
                        }

                    startActivity(intent)
                }

                override fun onItemDelete(position: Int) {
                    CustomAlertDialog.Builder(requireContext()).apply {
                        setTitle(resources.getString(R.string.alert))
                        setMessage(
                            String.format(
                                resources.getString(R.string.delete_alert_text),
                                hotelList[position].name
                            )
                        )
                        setNegativeButtonAndListener(resources.getString(R.string.cancel)) { dialog, _ ->
                            dialog.dismiss()
                        }
                        setPositiveButtonAndListener(resources.getString(R.string.confirm)) { _, _ ->
                            deleteHotelListItem(position)
                        }
                        show()
                    }
                }
            }

        binding.hotelResourceContainer.setOnRefreshLoadMoreListener(object :
            OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex = 1
                hotelResourceRequest.pageIndex = pageIndex
                hotelList.clear()
                listInit = false
                initHotelResourceList(2)
            }

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

        })
    }

    private fun deleteHotelListItem(position: Int) {
        apiService.deleteHotelData(DeleteRequest(hotelList[position].id))
            .enqueue(object : Callback<BaseResponse> {
                override fun onResponse(
                    call: Call<BaseResponse>, response: Response<BaseResponse>
                ) {
                    val baseResponse = response.body()
                    if (baseResponse != null) {
                        if (baseResponse.code == 200) {
                            hotelList.removeAt(position)
                            binding.hotelResourceList.adapter!!.notifyItemRemoved(position)
                            binding.hotelResourceList.adapter!!.notifyItemRangeChanged(
                                position, hotelList.size
                            )
                            showMessage(resources.getString(R.string.delete_success))
                        } else {
                            showMessage(baseResponse.msg)
                        }
                    }
                }

                override fun onFailure(call: Call<BaseResponse>, t: Throwable) {
                    showMessage(resources.getString(R.string.network_error))
                }

            })
    }

}