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.UpdateHotelResource
import com.pan_american.android.data.model.resource_management.hotel_resource.network.HotelResourceListRequest
import com.pan_american.android.data.model.resource_management.hotel_resource.network.HotelResourceListResponse
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<UpdateHotelResource>()

    private var listInit = false

    private lateinit var hotelResourceListRequest: HotelResourceListRequest

    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 {
            hotelResourceListRequest = HotelResourceListRequest(
                getString("hotel_name").toString(),
                getString("hotel_location").toString(),
                getString("contacts_name").toString(),
                getString("contacts_phone").toString()
            )
        }

        hotelResourceListRequest.pageIndex = pageIndex
        hotelResourceListRequest.pageSize = 10

        initViews()
    }

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

    private fun initHotelResourceList(type: Int) {

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

        if (!listInit) {
            apiService.getHotelResourceList(hotelResourceListRequest)
                .enqueue(object : Callback<HotelResourceListResponse> {
                    override fun onResponse(
                        call: Call<HotelResourceListResponse>, response: Response<HotelResourceListResponse>
                    ) {
                        val guideResourceResponse = response.body()
                        if (guideResourceResponse != null) {
                            if (guideResourceResponse.code == 200) {
                                for (item in guideResourceResponse.data) {
                                    hotelList.add(item)
                                }

                                if (hotelList.size == 0) {
                                    showMessage(resources.getString(R.string.no_data))
                                    return
                                }

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

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

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

                    override fun onFailure(call: Call<HotelResourceListResponse>, t: Throwable) {
                        showErrorInfo(R.string.hotel_resource_list_get_failed)
                    }
                })
        } else {
            if (OASystem.needRefresh) {
                pageIndex = 1
                hotelResourceListRequest.pageIndex = pageIndex
                hotelList.clear()
                listInit = false
                initHotelResourceList(2)
            }
        }
    }

    private fun initList() {

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

        val adapter = CardAdapter.Builder<UpdateHotelResource>().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.ifBlank {
                    resources.getString(R.string.no_info)
                }
                itemView.findViewById<TextView>(R.id.hotel_phone).text = data.tel.ifBlank {
                    resources.getString(R.string.no_info)
                }
                itemView.findViewById<TextView>(R.id.hotel_fax).text = data.fax.ifBlank {
                    resources.getString(R.string.no_info)
                }
                itemView.findViewById<TextView>(R.id.contacts).text = data.contact.ifBlank {
                    resources.getString(R.string.no_info)
                }
                itemView.findViewById<TextView>(R.id.contacts_phone).text = data.contactPhone.ifBlank {
                    resources.getString(R.string.no_info)
                }
            }
        }.create()
        binding.hotelResourceList.adapter = adapter

        adapter.onRecyclerViewItemClick =
            object : CardAdapter.OnRecyclerViewItemClick<UpdateHotelResource> {
                override fun onItemClick(position: Int) {
                    val intent =
                        Intent(OASystem.context, AddHotelResourceActivity::class.java).apply {
                            putExtra("id", hotelList[position].id)
                            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.hotelResourceListContainer.setOnRefreshLoadMoreListener(object :
            OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex = 1
                hotelResourceListRequest.pageIndex = pageIndex
                hotelList.clear()
                listInit = false
                initHotelResourceList(2)
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                if (pageIndex < totalPage) {
                    pageIndex += 1
                    hotelResourceListRequest.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) {
                    showErrorInfo(R.string.delete_error)
                }

            })
    }

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

        return totalPage
    }
}