package com.pan_american.android.ui.financial_module.expense_approval

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
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.ListAdapter
import com.pan_american.android.data.model.financial_module.expense_approval.entity.ExpenseApprovalGroupItem
import com.pan_american.android.data.model.financial_module.expense_approval.network.ExpenseApprovalGroupListRequest
import com.pan_american.android.data.model.financial_module.expense_approval.network.ExpenseApprovalGroupListResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentExpenseApprovalGroupListBinding
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 ExpenseApprovalGroupListFragment : BaseFragment<FragmentExpenseApprovalGroupListBinding>() {

    private val expenseApprovalGroupListRequest = ExpenseApprovalGroupListRequest()

    private var pageIndex = 1

    private var totalPage = 0

    private val apiService = ServiceCreator.create<APIService>()

    private val groupList = ArrayList<ExpenseApprovalGroupItem>()

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

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

        expenseApprovalGroupListRequest.pageIndex = pageIndex
        expenseApprovalGroupListRequest.pageSize = 10

        initViews()
    }

    override fun initViews() {
        binding.groupInfoContainer.setRefreshHeader(ClassicsHeader(OASystem.context))
        binding.groupInfoContainer.setRefreshFooter(ClassicsFooter(OASystem.context))

        getExpenseApprovalGroupList(1)
    }

    override fun initEvents() {
        binding.searchText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable?) {
                expenseApprovalGroupListRequest.searchCriteria = binding.searchText.text.toString()

                pageIndex = 1
                expenseApprovalGroupListRequest.pageIndex = pageIndex
                binding.groupInfoList.adapter!!.notifyItemRangeRemoved(0, groupList.size)
                groupList.clear()
                getExpenseApprovalGroupList(2)
            }
        })
    }

    private fun getExpenseApprovalGroupList(type: Int) {
        apiService.getExpenseApprovalGroupList(expenseApprovalGroupListRequest)
            .enqueue(object : Callback<ExpenseApprovalGroupListResponse> {
                override fun onResponse(
                    call: Call<ExpenseApprovalGroupListResponse>,
                    response: Response<ExpenseApprovalGroupListResponse>
                ) {
                    val listResponse = response.body()

                    if (listResponse != null) {
                        if (listResponse.code == 200) {

                            for (item in listResponse.data.data) {
                                groupList.add(item)
                            }

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

                            when (type) {
                                1 -> {
                                    totalPage = getTotalPage(listResponse.count)
                                    binding.groupInfoContainer.setEnableLoadMore(pageIndex < totalPage)
                                    initList()
                                    initEvents()
                                }

                                2 -> {
                                    binding.groupInfoContainer.finishRefresh()
                                    totalPage = getTotalPage(listResponse.count)
                                    binding.groupInfoContainer.setEnableLoadMore(pageIndex < totalPage)
                                    initList()
                                }

                                3 -> {
                                    binding.groupInfoContainer.finishLoadMore()
                                    binding.groupInfoContainer.setEnableLoadMore(pageIndex < totalPage)
                                    binding.groupInfoList.adapter!!.notifyItemInserted(groupList.size)
                                }
                            }

                        } else {
                            showMessage(listResponse.msg)
                        }
                    }
                }

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

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

        return totalPage
    }

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

        val adapter = ListAdapter.Builder<ExpenseApprovalGroupItem>().apply {
            setLayoutId(R.layout.item_expense_approval_group)
            setData(groupList)
            addBindView { itemView, data ->
                itemView.findViewById<TextView>(R.id.group_name).text = data.teamName
                itemView.findViewById<TextView>(R.id.group_number).text = data.salesQuoteNo
                itemView.findViewById<TextView>(R.id.group_classification).text = data.teamLev
                itemView.findViewById<TextView>(R.id.client_name).text = data.clientName
                itemView.findViewById<TextView>(R.id.client_company).text = data.clientUnit
                itemView.findViewById<TextView>(R.id.visit_date).text = data.visitDateStr
                itemView.findViewById<TextView>(R.id.visit_days).text = data.visitDays.toString()
                itemView.findViewById<TextView>(R.id.visit_members).text =
                    data.visitPNumber.toString()
                itemView.findViewById<TextView>(R.id.group_operator).text = data.jietuanOperator
            }
        }.create()

        binding.groupInfoList.adapter = adapter

        adapter.onRecyclerViewItemClick =
            object : ListAdapter.OnRecyclerViewItemClick<ExpenseApprovalGroupItem> {
                override fun onItemClick(position: Int) {
                    val bundle = Bundle().apply {
                        putInt("id", groupList[position].id)
                    }

                    val expenseApprovalFragment = ExpenseApprovalFragment()
                    expenseApprovalFragment.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)
                        .add(R.id.expense_approval_container, expenseApprovalFragment).commit()
                }
            }

        binding.groupInfoContainer.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex = 1
                expenseApprovalGroupListRequest.pageIndex = pageIndex
                binding.groupInfoList.adapter!!.notifyItemRangeRemoved(0, groupList.size)
                groupList.clear()
                getExpenseApprovalGroupList(2)
            }

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