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

import android.content.Intent
import android.net.Uri
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.base.BaseResponse
import com.pan_american.android.base.CustomAlertDialog
import com.pan_american.android.data.model.group_management.entry_and_exit_fee_detail.network.DownloadCustomerListRequest
import com.pan_american.android.data.model.group_management.entry_and_exit_fee_detail.network.DownloadCustomerListResponse
import com.pan_american.android.data.model.group_management.entry_and_exit_fee_detail.network.EntryAndExitDetailResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentEntryAndExitFeeTotalBinding
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class EntryAndExitFeeTotalFragment : BaseFragment<FragmentEntryAndExitFeeTotalBinding>() {

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

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

    override fun onStart() {
        super.onStart()

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
    }

    override fun onStop() {
        super.onStop()

        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }

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

        initViews()

        initEvents()
    }

    override fun initViews() {
        OASystem.entryAndExitDetailResponse.apply {

            economyTotalPayment = 0.0
            bussinessTotalPayment = 0.0
            firstClassTotalPayment = 0.0

            binding.checkInBoard.isChecked = choiceOne == 1

            binding.inBoardTotal.text = String.format(
                resources.getString(R.string.total_per_fee_format),
                choiceOneTotalCost
            )

            if (choiceOne == 1) {
                economyTotalPayment += choiceOneTotalCost
                bussinessTotalPayment += choiceOneTotalCost
                firstClassTotalPayment += choiceOneTotalCost
            }

            binding.checkEconomyClass.isChecked = choiceTwoJJ == 1

            if (choiceTwoJJ == 1) {
                binding.economyClass.text = String.format(resources.getString(R.string.economy_class_price), outsideJJPay)
                economyTotalPayment += outsideJJPay
            } else {
                binding.economyClass.text = String.format(resources.getString(R.string.economy_class_price), 0.0)
            }

            binding.checkBusinessClass.isChecked = choiceTwoGW == 1

            if (choiceTwoGW == 1) {
                binding.businessClass.text = String.format(resources.getString(R.string.business_class_price), outsideGWPay)
                bussinessTotalPayment += outsideGWPay
            } else {
                binding.businessClass.text = String.format(resources.getString(R.string.business_class_price), 0.0)
            }

            binding.checkFirstClass.isChecked = choiceTwoTD == 1

            if (choiceTwoTD == 1) {
                binding.firstClass.text = String.format(resources.getString(R.string.first_class_price), outsideTDPay)
                firstClassTotalPayment += outsideTDPay
            } else {
                binding.firstClass.text = String.format(resources.getString(R.string.first_class_price), 0.0)
            }

            binding.checkAccommodationFee.isChecked = choiceThree == 1

            binding.accommodationTotal.text = String.format(
                resources.getString(R.string.total_per_fee_format),
                choiceThreeTotalCost
            )

            if (choiceThree == 1) {
                economyTotalPayment += choiceThreeTotalCost
                bussinessTotalPayment += choiceThreeTotalCost
                firstClassTotalPayment += choiceThreeTotalCost
            }

            binding.checkMealFee.isChecked = choiceFour == 1

            binding.mealTotal.text = String.format(
                resources.getString(R.string.total_per_fee_format),
                choiceFourTotalCost
            )

            if (choiceFour == 1) {
                economyTotalPayment += choiceFourTotalCost
                bussinessTotalPayment += choiceFourTotalCost
                firstClassTotalPayment += choiceFourTotalCost
            }

            binding.checkPublicAndMiscellaneous.isChecked = choiceFive == 1

            binding.publicAndMiscellaneousTotal.text = String.format(
                resources.getString(R.string.total_per_fee_format),
                choiceFiveTotalCost
            )

            if (choiceFive == 1) {
                economyTotalPayment += choiceFiveTotalCost
                bussinessTotalPayment += choiceFiveTotalCost
                firstClassTotalPayment += choiceFiveTotalCost
            }

            binding.checkTraining.isChecked = choiceSix == 1

            binding.trainingTotal.text = String.format(
                resources.getString(R.string.total_per_fee_format),
                choiceSixTotalCost
            )

            if (choiceSix == 1) {
                economyTotalPayment += choiceSixTotalCost
                bussinessTotalPayment += choiceSixTotalCost
                firstClassTotalPayment += choiceSixTotalCost
            }

            binding.checkOther.isChecked = otherExpenses_Checked == 1

            binding.otherTotal.text = String.format(
                resources.getString(R.string.total_per_fee_format),
                otherExpensesTotalCost
            )

            if (otherExpenses_Checked == 1) {
                economyTotalPayment += otherExpensesTotalCost
                bussinessTotalPayment += otherExpensesTotalCost
                firstClassTotalPayment += otherExpensesTotalCost
            }

            binding.economyClassTotal.text = if (choiceTwoJJ == 1) {
                String.format(
                    resources.getString(R.string.economy_class_price),
                    economyTotalPayment
                )
            } else {
                String.format(resources.getString(R.string.economy_class_price), 0.0)
            }
            binding.businessClassTotal.text = if (choiceTwoGW == 1) {
                String.format(
                    resources.getString(R.string.business_class_price),
                    bussinessTotalPayment
                )
            } else {
                String.format(resources.getString(R.string.business_class_price), 0.0)
            }
            binding.firstClassTotal.text = if (choiceTwoTD == 1) {
                String.format(
                    resources.getString(R.string.first_class_price),
                    firstClassTotalPayment
                )
            } else {
                String.format(resources.getString(R.string.first_class_price), 0.0)
            }
        }
    }

    override fun initEvents() {
        binding.inBoardFee.setOnClickListener {

            val bundle = Bundle().apply {
                putInt("groupId", OASystem.entryAndExitDetailResponse.diId)
            }

            val inBoardFeeFragment = InBoardFeeFragment().apply {
                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.entry_and_exit_detail_container, inBoardFeeFragment).commit()
        }

        binding.internationalTravelFee.setOnClickListener {
            val bundle = Bundle().apply {
                putInt("groupId", OASystem.entryAndExitDetailResponse.diId)
            }

            val internationalTravelFeeFragment = InternationalTravelFeeFragment().apply {
                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.entry_and_exit_detail_container, internationalTravelFeeFragment).commit()
        }

        binding.accommodationFee.setOnClickListener {
            val bundle = Bundle().apply {
                putInt("groupId", OASystem.entryAndExitDetailResponse.diId)
                putInt("type", 3)
            }

            val paymentListFragment = EntryAndExitPaymentListFragment().apply {
                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.entry_and_exit_detail_container, paymentListFragment).commit()
        }

        binding.mealFee.setOnClickListener {
            val bundle = Bundle().apply {
                putInt("groupId", OASystem.entryAndExitDetailResponse.diId)
                putInt("type", 4)
            }

            val paymentListFragment = EntryAndExitPaymentListFragment().apply {
                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.entry_and_exit_detail_container, paymentListFragment).commit()
        }

        binding.publicAndMiscellaneousFee.setOnClickListener {
            val bundle = Bundle().apply {
                putInt("groupId", OASystem.entryAndExitDetailResponse.diId)
                putInt("type", 5)
            }

            val paymentListFragment = EntryAndExitPaymentListFragment().apply {
                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.entry_and_exit_detail_container, paymentListFragment).commit()
        }

        binding.trainingFee.setOnClickListener {
            val bundle = Bundle().apply {
                putInt("groupId", OASystem.entryAndExitDetailResponse.diId)
                putInt("type", 6)
            }

            val paymentListFragment = EntryAndExitPaymentListFragment().apply {
                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.entry_and_exit_detail_container, paymentListFragment).commit()
        }

        binding.otherFee.setOnClickListener {
            val bundle = Bundle().apply {
                putInt("groupId", OASystem.entryAndExitDetailResponse.diId)
                putInt("paymentId", OASystem.entryAndExitDetailResponse.id)
            }

            val otherPaymentFragment = OtherPaymentFragment().apply {
                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.entry_and_exit_detail_container, otherPaymentFragment).commit()
        }

        binding.exportToCollectionBill.setOnClickListener {
            CustomAlertDialog.Builder(OASystem.context).apply {
                setTitle(resources.getString(R.string.hint))
                setMessage(resources.getString(R.string.export_to_collection_bil_confirm))
                setNegativeButtonAndListener(resources.getString(R.string.cancel)) { dialog, _ ->
                    dialog.dismiss()
                }
                setPositiveButtonAndListener(resources.getString(R.string.confirm)) { dialog, _ ->

                    exportPaymentToCollectionBill()

                    dialog.dismiss()
                }
            }
        }

        binding.downloadGroupMembersList.setOnClickListener {
            downloadCustomerList()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateView(response: EntryAndExitDetailResponse) {
        initViews()
    }

    private fun exportPaymentToCollectionBill() {

        if (!isAdded) {
            return
        }

        apiService.exportPaymentToCollectionBill(groupId = OASystem.entryAndExitDetailResponse.diId)
            .enqueue(object :
                Callback<BaseResponse> {
                override fun onResponse(call: Call<BaseResponse>, response: Response<BaseResponse>) {
                    val addResponse = response.body()

                    if (addResponse != null) {
                        if (addResponse.code == 200) {
                            showMessage(resources.getString(R.string.operate_success))
                        } else {
                            showMessage(addResponse.msg)
                        }
                    }
                }

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

    private fun downloadCustomerList() {

        if (!isAdded) {
            return
        }

        apiService.downloadCustomerList(DownloadCustomerListRequest(diId = OASystem.entryAndExitDetailResponse.diId)).enqueue(object : Callback<DownloadCustomerListResponse> {
            override fun onResponse(
                call: Call<DownloadCustomerListResponse>,
                response: Response<DownloadCustomerListResponse>
            ) {
                val dataResponse = response.body()
                if (dataResponse != null) {
                    if (dataResponse.code == 200) {

                        CustomAlertDialog.Builder(OASystem.context).apply {
                            setTitle(resources.getString(R.string.hint))
                            setMessage(resources.getString(R.string.group_members_list_generated))
                            setNegativeButtonAndListener(resources.getString(R.string.cancel)) { dialog, _ ->
                                dialog.dismiss()
                            }
                            setPositiveButtonAndListener(resources.getString(R.string.confirm)) { dialog, _ ->
                                val uri = Uri.parse(dataResponse.data)
                                startActivity(Intent(Intent.ACTION_VIEW, uri))

                                dialog.dismiss()
                            }
                        }

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

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