package com.pan_american.android.ui.resource_management.car_resource

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
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.car_resource.entity.CarResource
import com.pan_american.android.data.model.resource_management.car_resource.network.CarResourceResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentCarResourceListBinding
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 CarResourceListFragment : BaseFragment<FragmentCarResourceListBinding>() {

    val apiService = ServiceCreator.create<APIService>()

    private var carList = ArrayList<CarResource>()

    private lateinit var carResourceRequest: ResourceRequest

    private var pageIndex = 1

    private var totalPage = 0

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


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

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

        carResourceRequest.pageIndex = pageIndex
        carResourceRequest.pageSize = 10

        initViews()
    }

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

    override fun onStart() {
        super.onStart()

        if (OASystem.needRefresh) {
            pageIndex = 1
            carResourceRequest.pageIndex = pageIndex
            carList.clear()
            OASystem.needRefresh = false
            initCarResourceList(2)
        }
    }

    private fun initCarResourceList(type: Int) {

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

        apiService.getCarData(carResourceRequest)
            .enqueue(object : Callback<CarResourceResponse> {
                override fun onResponse(
                    call: Call<CarResourceResponse>, response: Response<CarResourceResponse>
                ) {
                    val carResourceResponse = response.body()
                    if (carResourceResponse != null) {
                        if (carResourceResponse.code == 200) {
                            for (item in carResourceResponse.data.pageSource) {
                                carList.add(item)
                            }

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

                            when (type) {
                                1 -> {
                                    totalPage = carResourceResponse.data.totalPage
                                    binding.carResourceContainer.setEnableLoadMore(pageIndex < totalPage)
                                    initList()
                                }

                                2 -> {
                                    binding.carResourceContainer.finishRefresh()
                                    totalPage = carResourceResponse.data.totalPage
                                    binding.carResourceContainer.setEnableLoadMore(pageIndex < totalPage)
                                    initList()
                                }

                                3 -> {
                                    binding.carResourceContainer.finishLoadMore()
                                    binding.carResourceContainer.setEnableLoadMore(pageIndex < totalPage)
                                    binding.carResourceList.adapter!!.notifyItemInserted(carList.size)
                                }
                            }
                        } else {
                            showMessage(carResourceResponse.msg)
                        }
                    }
                }

                override fun onFailure(call: Call<CarResourceResponse>, t: Throwable) {
                    showErrorInfo(R.string.car_resource_list_get_failed)
                }
            })
    }

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

        val adapter = CardAdapter.Builder<CarResource>().apply {
            setLayoutId(R.layout.item_guide_and_car_list)
            setData(carList)
            setCanDelete(OASystem.authorization(OASystem.CAR_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.carResourceList.adapter = adapter

        adapter.onRecyclerViewItemClick =
            object : CardAdapter.OnRecyclerViewItemClick<CarResource> {
                override fun onItemClick(position: Int) {
                    val intent =
                        Intent(OASystem.context, AddCarResourceActivity::class.java).apply {
                            putExtra("resource_id", carList[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),
                                carList[position].unitName
                            )
                        )
                        setNegativeButtonAndListener(resources.getString(R.string.cancel)) { dialog, _ ->
                            dialog.dismiss()
                        }
                        setPositiveButtonAndListener(resources.getString(R.string.confirm)) { _, _ ->
                            deleteCarListItem(position)
                        }
                        show()
                    }
                }
            }

        binding.carResourceContainer.setOnRefreshLoadMoreListener(object :
            OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex = 1
                carResourceRequest.pageIndex = pageIndex
                binding.carResourceList.adapter!!.notifyItemRangeRemoved(0, carList.size)
                carList.clear()
                initCarResourceList(2)
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                if (pageIndex < totalPage) {
                    pageIndex += 1
                    carResourceRequest.pageIndex = pageIndex
                    initCarResourceList(3)
                }
            }

        })
    }

    private fun deleteCarListItem(position: Int) {
        apiService.deleteCarData(DeleteRequest(carList[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) {
                            carList.removeAt(position)
                            binding.carResourceList.adapter!!.notifyItemRemoved(position)
                            binding.carResourceList.adapter!!.notifyItemRangeChanged(position, carList.size - position)
                            showMessage(resources.getString(R.string.delete_success))
                        } else {
                            showMessage(baseResponse.msg)
                        }
                    }
                }

                override fun onFailure(call: Call<BaseResponse>, t: Throwable) {
                    showErrorInfo(R.string.delete_error)
                }
            })
    }
}