package com.pan_american.android.ui.efficiency_tools.address_book

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.ListAdapter
import com.pan_american.android.data.model.address_book.entity.Department
import com.pan_american.android.data.model.address_book.network.DepartmentListRequest
import com.pan_american.android.data.model.address_book.network.DepartmentListResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentDepartmentListBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class DepartmentListFragment : BaseFragment<FragmentDepartmentListBinding>() {

    private val departmentList = ArrayList<Department>()

    private var listInit = false

    private var companyId = 0

    private var companyName = ""

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

    override fun onStart() {
        super.onStart()

        requireArguments().apply {
            companyId = getInt("companyId")
            companyName = getString("companyName").toString()
        }

        initViews()
    }

    override fun initViews() {
        binding.subtitle.text = companyName
        initDepartmentList()
    }

    private fun initDepartmentList() {

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

        if (!listInit) {
            ServiceCreator.create<APIService>().getDepartmentList(DepartmentListRequest(companyId))
                .enqueue(object : Callback<DepartmentListResponse> {
                    override fun onResponse(
                        call: Call<DepartmentListResponse>,
                        response: Response<DepartmentListResponse>
                    ) {
                        val departmentListResponse = response.body()
                        if (departmentListResponse != null) {
                            if (departmentListResponse.code == 200) {
                                for (item in departmentListResponse.data) {
                                    departmentList.add(item)
                                }
                                initList()
                                listInit = true
                                binding.totalText.text = String.format(
                                    resources.getString(
                                        R.string.department_total, departmentList.size
                                    )
                                )
                            } else {
                                showMessage(departmentListResponse.msg)
                            }
                        }
                    }

                    override fun onFailure(call: Call<DepartmentListResponse>, t: Throwable) {
                        showErrorInfo(R.string.department_get_failed)
                    }
                })
        } else {
            initList()
        }
    }

    private fun initList() {
        val adapter = ListAdapter.Builder<Department>().apply {
            setData(departmentList)
            setLayoutId(R.layout.item_department_list)
            addBindView { itemView, data ->
                itemView.findViewById<TextView>(R.id.selector_item_name).text = data.depName
            }
        }.create()

        val layoutManager = LinearLayoutManager(OASystem.context)

        binding.departmentListView.layoutManager = layoutManager

        binding.departmentListView.adapter = adapter

        adapter.onRecyclerViewItemClick = object : ListAdapter.OnRecyclerViewItemClick<Department> {
            override fun onItemClick(position: Int) {
                val depId = departmentList[position].id
                val depName = departmentList[position].depName

                val bundle = Bundle().apply {
                    putInt("depId", depId)
                    putString("depName", depName)
                    putInt("companyId", companyId)
                    putString("companyName", companyName)
                }

                val memberListFragment = MemberListFragment()
                memberListFragment.arguments = bundle

                parentFragmentManager.beginTransaction().setCustomAnimations(
                        R.anim.slide_right_in,
                        R.anim.slide_left_out,
                        R.anim.slide_left_in,
                        R.anim.slide_right_out
                    ).addToBackStack(null).replace(R.id.address_book_container, memberListFragment)
                    .commit()
            }
        }
    }
}