package com.pan_american.android.ui.group_simple_info

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.common.entity.SimpleGroupData
import com.pan_american.android.data.model.common.network.GroupSimpleInfoRequest
import com.pan_american.android.data.model.common.network.GroupSimpleInfoResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentSimpleGroupBinding
import com.pan_american.android.ui.financial_module.payment_refund.PaymentRefundListFragment
import com.pan_american.android.ui.group_airplane_ticket.airplane_payment_insert.AirplaneTicketListFragment
import com.pan_american.android.ui.group_hotel.hotel_predetermine.HotelPredetermineListFragment
import com.pan_american.android.ui.group_invite_official.invite_official_payment_insert.GroupInvitePaymentListFragment
import com.pan_american.android.ui.group_op.ground_convey_payment_insert.GroundConveyPaymentListFragment
import com.pan_american.android.ui.group_visa.insurance_payment_insert.InsuranceListFragment
import com.pan_american.android.ui.group_visa.visa_payment_insert.VisaPaymentListFragment
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 GroupSimpleInfoFragment : BaseFragment<FragmentSimpleGroupBinding>() {

    private var id = 0

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

    private var groupSimpleInfoList = ArrayList<SimpleGroupData>()

    private lateinit var groupSimpleInfoRequest: GroupSimpleInfoRequest

    private var pageIndex = 1

    private var totalPage = 0

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

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

        requireArguments().apply {
            id = getInt("id")
        }

        groupSimpleInfoRequest = GroupSimpleInfoRequest(OASystem.userInfo.userId, id)

        groupSimpleInfoRequest.pageIndex = pageIndex
        groupSimpleInfoRequest.pageSize = 10

        initViews()
        initEvents()
    }

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

        initSimpleGroupDataList(1)
    }

    override fun initEvents() {

        binding.searchText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun afterTextChanged(p0: Editable?) {
                groupSimpleInfoRequest.pageIndex = 1

                if (binding.searchText.text.isNullOrBlank()) {
                    groupSimpleInfoRequest.teamName = ""
                } else {
                    groupSimpleInfoRequest.teamName = p0.toString()
                }

                pageIndex = 1

                binding.groupInfoList.adapter!!.notifyItemRangeRemoved(0, groupSimpleInfoList.size)
                groupSimpleInfoList.clear()
                initSimpleGroupDataList(1)
            }
        })

    }

    private fun initSimpleGroupDataList(type: Int) {

        if (!isAdded) {
            return
        }

        apiService.getGroupSimpleInfo(groupSimpleInfoRequest)
            .enqueue(object : Callback<GroupSimpleInfoResponse> {
                override fun onResponse(
                    call: Call<GroupSimpleInfoResponse>,
                    response: Response<GroupSimpleInfoResponse>
                ) {
                    val simpleGroupDataResponse = response.body()
                    if (simpleGroupDataResponse != null) {
                        if (simpleGroupDataResponse.code == 200) {

                            for (item in simpleGroupDataResponse.data) {
                                groupSimpleInfoList.add(item)
                            }

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

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

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

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

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

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

    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<SimpleGroupData>().apply {
            setLayoutId(R.layout.item_simple_group_info)
            setData(groupSimpleInfoList)
            addBindView { itemView, data ->
                itemView.findViewById<TextView>(R.id.group_name).text = data.teamName
                itemView.findViewById<TextView>(R.id.group_customer).text = data.clientName
                itemView.findViewById<TextView>(R.id.visit_country).text = data.visitCountry
                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.during_time).text = String.format(
                    resources.getString(
                        R.string.during_format
                    ), data.visitStartDate.substring(0, 10), data.visitEndDate.subSequence(0, 10)
                )
            }
        }.create()

        binding.groupInfoList.adapter = adapter

        adapter.onRecyclerViewItemClick =
            object : ListAdapter.OnRecyclerViewItemClick<SimpleGroupData> {
                override fun onItemClick(position: Int) {

                    val simpleGroupData = groupSimpleInfoList[position]

                    val bundle = Bundle().apply {
                        putInt("groupId", simpleGroupData.id)
                        putString("teamName", simpleGroupData.teamName)
                        putString("tourCode", simpleGroupData.tourCode)
                        putString("clientName", simpleGroupData.clientName)
                        putString("visitCountry", simpleGroupData.visitCountry)
                        putString("visitDays", simpleGroupData.visitDays.toString())
                        putString("visitPNumber", simpleGroupData.visitPNumber.toString())
                        putString(
                            "duringTime", String.format(
                                resources.getString(R.string.during_format),
                                simpleGroupData.visitStartDate.substring(0, 10),
                                simpleGroupData.visitEndDate.subSequence(0, 10)
                            )
                        )
                    }

                    when (id) {

                        //酒店预定详情界面
                        OASystem.C_TABLE_HOTEL_PREDETERMINE -> {
                            val hotelPredetermineListFragment = HotelPredetermineListFragment()
                            hotelPredetermineListFragment.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.hotel_predetermine_container, hotelPredetermineListFragment)
                                .commit()
                        }

                        //OP费用团组详情界面
                        OASystem.C_TABLE_GROUND_CONVEY -> {
                            val groundConveyPaymentListFragment = GroundConveyPaymentListFragment()
                            groundConveyPaymentListFragment.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.group_op_fragment_container, groundConveyPaymentListFragment)
                                .commit()
                        }

                        //签证费用录入详情界面
                        OASystem.C_TABLE_VISA -> {
                            val visaPaymentListFragment = VisaPaymentListFragment()
                            visaPaymentListFragment.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.visa_payment_fragment_container, visaPaymentListFragment)
                                .commit()
                        }

                        //商邀费用团组详情界面
                        OASystem.C_TABLE_INVITE_OFFICIAL -> {
                            val groupInvitePaymentListFragment = GroupInvitePaymentListFragment()
                            groupInvitePaymentListFragment.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.invite_official_fragment_container, groupInvitePaymentListFragment)
                                .commit()
                        }

                        //保险费用录入详情界面
                        OASystem.C_TABLE_INSURANCE -> {
                            val insuranceListFragment = InsuranceListFragment()
                            insuranceListFragment.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.insurance_insert_container, insuranceListFragment)
                                .commit()
                        }

                        //机票费用团组详情界面
                        OASystem.C_TABLE_AIRPLANE_TICKET -> {
                            val airplaneTicketListFragment = AirplaneTicketListFragment()
                            airplaneTicketListFragment.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.airplane_ticket_fragment_container, airplaneTicketListFragment)
                                .commit()
                        }

                        //收款退还详情界面
                        OASystem.C_TABLE_PAYMENT_REFUND -> {
                            val paymentRefundListFragment = PaymentRefundListFragment()
                            paymentRefundListFragment.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.payment_refund_fragment_container, paymentRefundListFragment)
                                .commit()
                        }
                    }
                }
            }

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

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

}