package com.pan_american.android.ui.resource_management.airplane_three_code

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.airplane_three_code.entity.AirplaneThreeCode
import com.pan_american.android.data.model.resource_management.airplane_three_code.network.AirplaneThreeCodeRequest
import com.pan_american.android.data.model.resource_management.airplane_three_code.network.AirplaneThreeCodeResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentAirplaneThreeCodeListBinding
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 AirplaneThreeCodeListFragment : BaseFragment<FragmentAirplaneThreeCodeListBinding>() {

    val apiService = ServiceCreator.create<APIService>()

    private var airplaneList = ArrayList<AirplaneThreeCode>()

    private var listInit = false

    private lateinit var airplaneThreeCodeRequest: AirplaneThreeCodeRequest

    private var pageIndex = 1

    private var totalPage = 0

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

    override fun onStart() {
        super.onStart()

        airplaneThreeCodeRequest = AirplaneThreeCodeRequest(
            requireArguments().getString("airplane_city").toString(),
            requireArguments().getString("three_code").toString()
        )

        airplaneThreeCodeRequest.pageIndex = pageIndex
        airplaneThreeCodeRequest.pageSize = 10

        initViews()
    }

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

    private fun initAirplaneThreeCodeList(type: Int) {

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

        if (!listInit) {
            apiService.getAirplaneThreeCodeData(airplaneThreeCodeRequest)
                .enqueue(object : Callback<AirplaneThreeCodeResponse> {
                    override fun onResponse(
                        call: Call<AirplaneThreeCodeResponse>,
                        response: Response<AirplaneThreeCodeResponse>
                    ) {
                        val airplaneThreeCodeResponse = response.body()
                        if (airplaneThreeCodeResponse != null) {
                            if (airplaneThreeCodeResponse.code == 200) {
                                for (item in airplaneThreeCodeResponse.data.pageSource) {
                                    airplaneList.add(item)
                                }
                                when (type) {
                                    1 -> {
                                        totalPage = airplaneThreeCodeResponse.data.totalPage
                                        binding.airplaneThreeCodeContainer.setEnableLoadMore(
                                            pageIndex < totalPage
                                        )
                                        initList()
                                        listInit = true
                                    }

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

                                    3 -> {
                                        binding.airplaneThreeCodeContainer.finishLoadMore()
                                        binding.airplaneThreeCodeContainer.setEnableLoadMore(
                                            pageIndex < totalPage
                                        )
                                        binding.airplaneResourceList.adapter!!.notifyItemInserted(
                                            airplaneList.size
                                        )
                                        listInit = true
                                    }
                                }
                            } else {
                                showMessage(airplaneThreeCodeResponse.msg)
                            }
                        }
                    }

                    override fun onFailure(call: Call<AirplaneThreeCodeResponse>, t: Throwable) {
                        showErrorInfo(R.string.airplane_three_code_list_get_failed)
                    }
                })
        } else {
            if (OASystem.needRefresh) {
                pageIndex = 1
                airplaneThreeCodeRequest.pageIndex = pageIndex
                airplaneList.clear()
                listInit = false
                initAirplaneThreeCodeList(2)
            }
        }
    }

    private fun initList() {

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

        val adapter = CardAdapter.Builder<AirplaneThreeCode>().apply {
            setLayoutId(R.layout.item_airplane_three_code_list)
            setData(airplaneList)
            setCanDelete(OASystem.authorization(OASystem.THREE_CODE_RESOURCE, OASystem.DELETE))
            addBindView { itemView, data ->
                itemView.findViewById<TextView>(R.id.airplane_name).text = data.airPort.ifBlank {
                    resources.getString(R.string.no_info)
                }
                itemView.findViewById<TextView>(R.id.airplane_country).text = data.country.ifBlank {
                    resources.getString(R.string.no_info)
                }
                itemView.findViewById<TextView>(R.id.airplane_city).text = data.city.ifBlank {
                    resources.getString(R.string.no_info)
                }
                itemView.findViewById<TextView>(R.id.airplane_three_code).text = data.three.ifBlank {
                    resources.getString(R.string.no_info)
                }
                itemView.findViewById<TextView>(R.id.create_time).text = data.createTime.ifBlank {
                    resources.getString(R.string.no_info)
                }
            }
        }.create()

        binding.airplaneResourceList.adapter = adapter

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

        binding.airplaneThreeCodeContainer.setOnRefreshLoadMoreListener(object :
            OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex = 1
                airplaneThreeCodeRequest.pageIndex = pageIndex
                airplaneList.clear()
                listInit = false
                initAirplaneThreeCodeList(2)
            }

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

        })
    }

    private fun deleteAirplaneListItem(position: Int) {
        apiService.deleteAirplaneCodeData(DeleteRequest(airplaneList[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) {
                            airplaneList.removeAt(position)
                            binding.airplaneResourceList.adapter!!.notifyItemRemoved(position)
                            binding.airplaneResourceList.adapter!!.notifyItemRangeChanged(
                                position, airplaneList.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)
                }
            })
    }
}