package com.pan_american.android.ui.resource_management.guide_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.common.network.ResourceRequest
import com.pan_american.android.data.model.resource_management.guide_resource.entity.GuideResource
import com.pan_american.android.data.model.resource_management.guide_resource.network.GuideResourceResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentGuideResourceListBinding
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 GuideResourceListFragment : BaseFragment<FragmentGuideResourceListBinding>() {

    val apiService = ServiceCreator.create<APIService>()

    private var guideList = ArrayList<GuideResource>()

    private var listInit = false

    private lateinit var guideResourceRequest: ResourceRequest

    private var pageIndex = 1

    private var totalPage = 0

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

    override fun onStart() {
        super.onStart()

        requireArguments().apply {
            guideResourceRequest = ResourceRequest(
                getString("supplier_name").toString(),
                getString("supplier_location").toString(),
                getString("contacts_name").toString(),
                getString("contacts_phone").toString()
            )
        }

        guideResourceRequest.pageIndex = pageIndex
        guideResourceRequest.pageSize = 10

        initViews()
    }

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

    private fun initGuideResourceList(type: Int) {

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

        if (!listInit) {
            apiService.getGuideData(guideResourceRequest)
                .enqueue(object : Callback<GuideResourceResponse> {
                    override fun onResponse(
                        call: Call<GuideResourceResponse>, response: Response<GuideResourceResponse>
                    ) {
                        val guideResourceResponse = response.body()
                        if (guideResourceResponse != null) {
                            if (guideResourceResponse.code == 200) {
                                for (item in guideResourceResponse.data.pageSource) {
                                    guideList.add(item)
                                }

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

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

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

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

                    override fun onFailure(call: Call<GuideResourceResponse>, t: Throwable) {
                        showErrorInfo(R.string.guide_resource_list_get_failed)
                    }
                })
        } else {
            if (OASystem.needRefresh) {
                pageIndex = 1
                guideResourceRequest.pageIndex = pageIndex
                guideList.clear()
                listInit = false
                initGuideResourceList(2)
            }
        }
    }

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

        val adapter = CardAdapter.Builder<GuideResource>().apply {
            setLayoutId(R.layout.item_guide_and_car_list)
            setData(guideList)
            setCanDelete(OASystem.authorization(OASystem.GUIDE_RESOURCE, OASystem.DELETE))
            addBindView { itemView, data ->
                itemView.findViewById<TextView>(R.id.supplier_name).text = data.unitName.ifBlank {
                    resources.getString(R.string.no_info)
                }
                itemView.findViewById<TextView>(R.id.unit_area).text = data.unitArea.ifBlank {
                    resources.getString(R.string.no_info)
                }
                itemView.findViewById<TextView>(R.id.contacts_name).text = data.contact.ifBlank {
                    resources.getString(R.string.no_info)
                }
                itemView.findViewById<TextView>(R.id.contacts_phone).text = data.contactTel.ifBlank {
                    resources.getString(R.string.no_info)
                }
                itemView.findViewById<TextView>(R.id.service_score).text = data.score.toString().ifBlank {
                    resources.getString(R.string.no_info)
                }
                itemView.findViewById<TextView>(R.id.refresh_time).text = data.createTime.ifBlank {
                    resources.getString(R.string.no_info)
                }
            }
        }.create()

        binding.guideResourceList.adapter = adapter

        adapter.onRecyclerViewItemClick =
            object : CardAdapter.OnRecyclerViewItemClick<GuideResource> {
                override fun onItemClick(position: Int) {
                    val intent =
                        Intent(OASystem.context, AddGuideResourceActivity::class.java).apply {
                            putExtra("resource_id", guideList[position].id)
                            putExtra("fromList", true)
                        }

                    startActivity(intent)
                }

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

        binding.guideResourceContainer.setOnRefreshLoadMoreListener(object :
            OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex = 1
                guideResourceRequest.pageIndex = pageIndex
                guideList.clear()
                listInit = false
                initGuideResourceList(2)
            }

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

        })
    }

    private fun deleteGuideListItem(position: Int) {
        apiService.deleteGuideData(DeleteRequest(guideList[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) {
                            guideList.removeAt(position)
                            binding.guideResourceList.adapter!!.notifyItemRemoved(position)
                            binding.guideResourceList.adapter!!.notifyItemRangeChanged(
                                position, guideList.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)
                }
            })
    }
}