package com.pan_american.android.ui.group_management.entry_and_exit_fee_detail

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.pan_american.android.OASystem
import com.pan_american.android.R
import com.pan_american.android.base.BaseFragment
import com.pan_american.android.data.model.group_management.entry_and_exit_fee_detail.network.EntryAndExitPaymentTypeRequest
import com.pan_american.android.data.model.group_management.entry_and_exit_fee_detail.network.EntryAndExitTipsRequest
import com.pan_american.android.data.model.group_management.entry_and_exit_fee_detail.network.InBoardDetailResponse
import com.pan_american.android.data.model.group_management.entry_and_exit_fee_detail.network.NewestVisaPaymentResponse
import com.pan_american.android.data.model.group_management.entry_and_exit_fee_detail.network.UpdateInBoardPaymentRequest
import com.pan_american.android.data.model.group_management.entry_and_exit_fee_detail.network.UpdateInBoardPaymentResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentInBoardFeeBinding
import com.pan_american.android.util.MoneyInputFilter
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class InBoardFeeFragment : BaseFragment<FragmentInBoardFeeBinding>() {

    private var groupId = 0

    private var paymentId = 0

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

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

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

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

        initViews()

        initEvents()
    }

    override fun initViews() {
        binding.visaPrice.filters = arrayOf(MoneyInputFilter(2))
        binding.vaccinePrice.filters = arrayOf(MoneyInputFilter(2))
        binding.nucleicAcidTestingPrice.filters = arrayOf(MoneyInputFilter(2))
        binding.servicePrice.filters = arrayOf(MoneyInputFilter(2))
        binding.insurancePrice.filters = arrayOf(MoneyInputFilter(2))
        binding.ticketPrice.filters = arrayOf(MoneyInputFilter(2))

        getInBoardFeeDetail()
    }

    private fun getInBoardFeeDetail() {

        if (!isAdded) {
            return
        }

        apiService.getInBoardPaymentDetail(EntryAndExitPaymentTypeRequest(diId = groupId, subType = 1)).enqueue(object : Callback<InBoardDetailResponse> {
            override fun onResponse(
                call: Call<InBoardDetailResponse>,
                response: Response<InBoardDetailResponse>
            ) {

                val detailResponse = response.body()

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

                        detailResponse.data.apply {
                            paymentId = id

                            binding.isSelected.isChecked = choiceOne == 1
                            binding.visaPrice.setText(visa.toString())
                            binding.visaDescription.setText(visaRemark)
                            binding.vaccinePrice.setText(yiMiao.toString())
                            binding.nucleicAcidTestingPrice.setText(heSuan.toString())
                            binding.servicePrice.setText(service.toString())
                            binding.insurancePrice.setText(safe.toString())
                            binding.ticketPrice.setText(ticket.toString())
                        }

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

            override fun onFailure(p0: Call<InBoardDetailResponse>, p1: Throwable) {
                showErrorInfo(R.string.in_board_payment_detail_get_error)
            }
        })
    }

    override fun initEvents() {
        binding.getNewestVisaPayment.setOnClickListener {
            getNewestVisaPayment()
        }

        binding.commit.setOnClickListener {
            if (binding.visaPrice.text.isBlank() || binding.visaPrice.text.endsWith('.')) {
                showMessage(resources.getString(R.string.visa_price_input_hint))
                return@setOnClickListener
            }

            if (binding.vaccinePrice.text.isBlank() || binding.vaccinePrice.text.endsWith('.')) {
                showMessage(resources.getString(R.string.vaccine_price_input_hint))
                return@setOnClickListener
            }

            if (binding.nucleicAcidTestingPrice.text.isBlank() || binding.nucleicAcidTestingPrice.text.endsWith('.')) {
                showMessage(resources.getString(R.string.nucleic_acid_testing_payment_input_hint))
                return@setOnClickListener
            }

            if (binding.servicePrice.text.isBlank() || binding.servicePrice.text.endsWith('.')) {
                showMessage(resources.getString(R.string.service_price_input_hint))
                return@setOnClickListener
            }

            if (binding.insurancePrice.text.isBlank() || binding.insurancePrice.text.endsWith('.')) {
                showMessage(resources.getString(R.string.insurance_price_input_hint))
                return@setOnClickListener
            }

            if (binding.ticketPrice.text.isBlank() || binding.ticketPrice.text.endsWith('.')) {
                showMessage(resources.getString(R.string.ticket_price_input_hint))
                return@setOnClickListener
            }

            val updateInBoardPaymentRequest = UpdateInBoardPaymentRequest(
                id = paymentId,
                diId = groupId,
                choiceOne = if (binding.isSelected.isChecked) {
                    1
                } else {
                    0
                },
                visa = binding.visaPrice.text.toString().toDouble(),
                visaRemark = binding.visaDescription.getText(),
                yiMiao = binding.vaccinePrice.text.toString().toDouble(),
                heSuan = binding.nucleicAcidTestingPrice.text.toString().toDouble(),
                service = binding.servicePrice.text.toString().toDouble(),
                ticket = binding.ticketPrice.text.toString().toDouble(),
                safe = binding.insurancePrice.text.toString().toDouble()
            )

            updateInBoardPayment(updateInBoardPaymentRequest)
        }
    }

    private fun getNewestVisaPayment() {

        if (!isAdded) {
            return
        }

        apiService.getNewestVisaPayment(EntryAndExitTipsRequest(groupId = groupId, tipsType = 2)).enqueue(object : Callback<NewestVisaPaymentResponse> {
            override fun onResponse(
                call: Call<NewestVisaPaymentResponse>,
                response: Response<NewestVisaPaymentResponse>
            ) {
                val detailResponse = response.body()

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

                        detailResponse.data.apply {
                            binding.visaPrice.setText(feeTotal.toString())

                            binding.visaDescription.setText(remark)

                            showMessage(resources.getString(R.string.update_success))
                        }

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

            override fun onFailure(p0: Call<NewestVisaPaymentResponse>, p1: Throwable) {
                showErrorInfo(R.string.newest_visa_payment_get_error)
            }
        })
    }

    private fun updateInBoardPayment(updateInBoardPaymentRequest: UpdateInBoardPaymentRequest) {

        if (!isAdded) {
            return
        }

        apiService.updateInBoardPayment(updateInBoardPaymentRequest).enqueue(object : Callback<UpdateInBoardPaymentResponse> {
            override fun onResponse(
                call: Call<UpdateInBoardPaymentResponse>,
                response: Response<UpdateInBoardPaymentResponse>
            ) {
                val updateResponse = response.body()

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

                        OASystem.entryAndExitDetailResponse.choiceOneTotalCost = updateResponse.data.itemTotal

                        OASystem.entryAndExitDetailResponse.choiceOne = updateInBoardPaymentRequest.choiceOne

                        OASystem.entryAndExitDetailResponse.diId = updateResponse.data.parentId

                        showMessage(resources.getString(R.string.update_success))

                        parentFragmentManager.popBackStack()

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

            override fun onFailure(p0: Call<UpdateInBoardPaymentResponse>, p1: Throwable) {
                showErrorInfo(R.string.update_error)
            }
        })
    }
}