package com.pan_american.android.ui.group_invite_official.invite_official_payment_insert

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.TextView
import androidx.core.content.res.ResourcesCompat
import com.pan_american.android.OASystem
import com.pan_american.android.R
import com.pan_american.android.base.BaseActivity
import com.pan_american.android.base.BaseResponse
import com.pan_american.android.base.ListAdapter
import com.pan_american.android.data.model.common.entity.Selector
import com.pan_american.android.data.model.common.network.GroupCurrencyRequest
import com.pan_american.android.data.model.common.network.GroupCurrencyResponse
import com.pan_american.android.data.model.group_invite_official.invite_official_payment_insert.network.InviteOfficialBaseDataResponse
import com.pan_american.android.data.model.group_invite_official.invite_official_payment_insert.network.InviteOfficialDetailRequest
import com.pan_american.android.data.model.group_invite_official.invite_official_payment_insert.network.InviteOfficialDetailResponse
import com.pan_american.android.data.model.group_invite_official.invite_official_payment_insert.network.UpdateInviteOfficialRequest
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.ActivityAddInvitePaymentBinding
import com.pan_american.android.databinding.LayoutTitleBinding
import com.pan_american.android.util.MoneyInputFilter
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.text.DecimalFormat

class AddInvitePaymentActivity : BaseActivity<ActivityAddInvitePaymentBinding>() {

    private lateinit var titleBinding: LayoutTitleBinding

    private var fromList = false

    private var groupId = 0

    private var paymentId = 0

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

    private val paymentWayList = ArrayList<Selector>()

    private val cardList = ArrayList<Selector>()

    private val currencyList = ArrayList<Selector>()

    private var invitePayment = 0.0

    private var inviteCurrencyId = -1

    private var inviteRate = 0.0

    private var expressPayment = 0.0

    private var expressCurrencyId = -1

    private var expressRate = 0.0

    private var isExpressCurrency = true

    private var activityPayment = 0.0

    private var activityCurrencyId = -1

    private var activityRate = 0.0

    private var isActivityCurrency = true

    private var translatePayment = 0.0

    private var translateCurrencyId = -1

    private var translateRate = 0.0

    private var isTranslateCurrency = true

    private var totalPayment = 0.0

    private var totalCurrencyId = 0

    private var paymentWayId = -1

    private var cardTypeId = 0

    private var cardTypeSelect = false

    private var bankNo = ""

    private var paymentMarkId = -1

    private lateinit var updateInviteOfficialRequest: UpdateInviteOfficialRequest

    private var isAudit = -1

    override fun getViewBinding() = ActivityAddInvitePaymentBinding.inflate(layoutInflater)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        screenAdaptation(binding)

        intent.apply {
            fromList = getBooleanExtra("fromList", false)
            groupId = getIntExtra("groupId", 0)
            paymentId = getIntExtra("paymentId", 0)
            binding.groupName.text = getStringExtra("teamName")
            binding.groupNumber.text = getStringExtra("tourCode")
            binding.groupCustomer.text = getStringExtra("clientName")
            binding.visitCountry.text = getStringExtra("visitCountry")



            if (fromList) {
                binding.inviteUnit.text = getStringExtra("currency")

                isAudit = getIntExtra("isAudit", -1)
            } else {
                isAudit = 0
            }
        }

        updateInviteOfficialRequest = UpdateInviteOfficialRequest()

        initTitle()

        //获取基础数据源
        getBaseData()
    }

    override fun initTitle() {

        titleBinding = LayoutTitleBinding.bind(binding.root).apply {

            if (fromList) {
                titleText.text = resources.getString(R.string.invite_payment_detail)
            } else {
                titleBinding = LayoutTitleBinding.bind(binding.root).apply {
                    titleText.text = resources.getString(R.string.add_new_invite_payment)
                }
            }

            backButton.setOnClickListener {
                back()
            }
        }
    }

    override fun initViews() {

        binding.invitePayment.filters = arrayOf(MoneyInputFilter())
        binding.officialActivityPayment.filters = arrayOf(MoneyInputFilter())
        binding.expressFee.filters = arrayOf(MoneyInputFilter())
        binding.officialTranslatePayment.filters = arrayOf(MoneyInputFilter())

        if (fromList) {
            //获取商邀费用详情
            getInviteOfficialDetail()

            binding.commit.setText(resources.getString(R.string.update))

            if (!canBeEdit()) {

                binding.apply {
                    inviteeName.isEnabled = false
                    inviteeArea.isEnabled = false
                    inviteeTime.isEnabled = false
                    yes.isEnabled = false
                    no.isEnabled = false
                    inviteContacts.isEnabled = false
                    contactsJob.isEnabled = false
                    contactsPhone.isEnabled = false
                    contactsEmail.isEnabled = false
                    contactsFax.isEnabled = false
                    inviteeLocation.isEnabled(false)
                    otherInfo.isEnabled(false)
                    invitePayment.isEnabled = false
                    inviteUnit.isEnabled = false
                    expressFee.isEnabled = false
                    expressUnit.isEnabled = false
                    officialActivityPayment.isEnabled = false
                    officialActivityUnit.isEnabled = false
                    officialTranslatePayment.isEnabled = false
                    officialTranslateUnit.isEnabled = false
                    paymentWay.isEnabled = false
                    consumeWay.isEnabled = false
                    consumeDate.isEnabled = false
                    cardType.isEnabled = false
                    companyBankNo.isEnabled = false
                    transferOtherBankName.isEnabled = false
                    transferOtherSideName.isEnabled = false
                    transferOtherSideName.isEnabled = false
                    otherBankName.isEnabled = false
                    otherSideNo.isEnabled = false
                    otherSideName.isEnabled = false
                    payee.isEnabled = false
                    paymentMark.isEnabled = false
                    notes.isEnabled(false)

                    commit.setText(resources.getString(R.string.back))
                }

            }

        } else {
            binding.commit.setText(resources.getString(R.string.add))
        }
    }

    override fun initEvents() {

        binding.inviteeTime.setOnClickListener {
            showDatePicker(resources.getString(R.string.invitee_time_hint), binding.inviteeTime) {}
        }

        binding.invitePayment.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?) {
                if (binding.invitePayment.text.isNullOrBlank()) {
                    showMessage(resources.getString(R.string.invite_payment_hint))
                    return
                }

                if (binding.invitePayment.text.endsWith('.')) {
                    return
                }

                invitePayment = binding.invitePayment.text.toString().toDouble()

                calculateTotalPayment()
            }
        })

        binding.inviteUnit.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setLayoutId(R.layout.item_selector)
                    setData(currencyList)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text =
                                String.format(
                                    resources.getString(R.string.currency_name_code_format),
                                    data.currencyName,
                                    data.currencyCode
                                )

                            if (inviteCurrencyId == data.currencyId) {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color_blue, null))
                            } else {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color, null))
                            }
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick =
                    object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                        override fun onItemClick(position: Int) {
                            currencyList[position].apply {
                                binding.inviteUnit.text = currencyCode
                                inviteCurrencyId = currencyId
                                inviteRate = rate
                            }

                            calculateTotalPayment()

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.expressFee.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?) {
                if (binding.expressFee.text.isNullOrBlank()) {
                    showMessage(resources.getString(R.string.express_fee_hint))
                    return
                }

                if (binding.expressFee.text.endsWith('.')) {
                    return
                }

                expressPayment = binding.expressFee.text.toString().toDouble()

                calculateTotalPayment()
            }
        })

        binding.expressUnit.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setLayoutId(R.layout.item_selector)
                    setData(currencyList)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text =
                                String.format(
                                    resources.getString(R.string.currency_name_code_format),
                                    data.currencyName,
                                    data.currencyCode
                                )

                            if (expressCurrencyId == data.currencyId) {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color_blue, null))
                            } else {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color, null))
                            }
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick =
                    object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                        override fun onItemClick(position: Int) {
                            currencyList[position].apply {
                                binding.expressUnit.text = currencyCode
                                expressCurrencyId = currencyId
                                expressRate = rate
                            }

                            calculateTotalPayment()

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.officialActivityPayment.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?) {
                if (binding.officialActivityPayment.text.isNullOrBlank()) {
                    showMessage(resources.getString(R.string.activity_payment_hint))
                    return
                }

                if (binding.officialActivityPayment.text.endsWith('.')) {
                    return
                }

                activityPayment = binding.officialActivityPayment.text.toString().toDouble()

                calculateTotalPayment()
            }
        })

        binding.officialActivityUnit.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setLayoutId(R.layout.item_selector)
                    setData(currencyList)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text =
                                String.format(
                                    resources.getString(R.string.currency_name_code_format),
                                    data.currencyName,
                                    data.currencyCode
                                )

                            if (activityCurrencyId == data.currencyId) {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color_blue, null))
                            } else {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color, null))
                            }
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick =
                    object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                        override fun onItemClick(position: Int) {
                            currencyList[position].apply {
                                binding.officialActivityUnit.text = currencyCode
                                activityCurrencyId = currencyId
                                activityRate = rate
                            }

                            calculateTotalPayment()

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.officialTranslatePayment.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?) {
                if (binding.officialTranslatePayment.text.isNullOrBlank()) {
                    showMessage(resources.getString(R.string.translate_payment_hint))
                    return
                }

                if (binding.officialTranslatePayment.text.endsWith('.')) {
                    return
                }

                translatePayment = binding.officialTranslatePayment.text.toString().toDouble()

                calculateTotalPayment()
            }
        })

        binding.officialTranslateUnit.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setLayoutId(R.layout.item_selector)
                    setData(currencyList)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text =
                                String.format(
                                    resources.getString(R.string.currency_name_code_format),
                                    data.currencyName,
                                    data.currencyCode
                                )

                            if (translateCurrencyId == data.currencyId) {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color_blue, null))
                            } else {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color, null))
                            }
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick =
                    object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                        override fun onItemClick(position: Int) {
                            currencyList[position].apply {
                                binding.officialTranslateUnit.text = currencyCode
                                translateCurrencyId = currencyId
                                translateRate = rate
                            }

                            calculateTotalPayment()

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.paymentWay.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setLayoutId(R.layout.item_selector)
                    setData(paymentWayList)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text = data.name

                            if (paymentWayId == data.id) {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color_blue, null))
                            } else {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color, null))
                            }
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick =
                    object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                        override fun onItemClick(position: Int) {
                            binding.paymentWay.text = paymentWayList[position].name
                            paymentWayId = paymentWayList[position].id

                            when (paymentWayId) {
                                //刷卡
                                72 -> {
                                    binding.swipe.visibility = View.VISIBLE
                                    binding.transfer.visibility = View.GONE
                                    binding.remit.visibility = View.GONE
                                }
                                //转账
                                73 -> {
                                    binding.swipe.visibility = View.GONE
                                    binding.transfer.visibility = View.VISIBLE
                                    binding.remit.visibility = View.GONE
                                }
                                //汇款
                                83 -> {
                                    binding.swipe.visibility = View.GONE
                                    binding.transfer.visibility = View.GONE
                                    binding.remit.visibility = View.VISIBLE
                                }
                                //其它
                                else -> {
                                    binding.swipe.visibility = View.GONE
                                    binding.transfer.visibility = View.GONE
                                    binding.remit.visibility = View.GONE
                                }

                            }

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.consumeDate.setOnClickListener {
            showDatePicker(
                resources.getString(R.string.consume_date_select_hint), binding.consumeDate
            ) {}
        }

        binding.cardType.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setData(cardList)
                    setLayoutId(R.layout.item_selector)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text = data.name

                            if (cardTypeId == data.id) {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color_blue, null))
                            } else {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color, null))
                            }
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick =
                    object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                        override fun onItemClick(position: Int) {
                            binding.cardType.text = cardList[position].name
                            binding.bankCardNumber.text = cardList[position].remark
                            binding.bankCardOwner.text = cardList[position].cardholder
                            cardTypeId = cardList[position].id
                            bankNo = cardList[position].remark
                            cardTypeSelect = true

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.paymentMark.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setLayoutId(R.layout.item_selector)
                    setData(OASystem.paymentMark)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text = data.name

                            if (paymentMarkId == data.id) {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color_blue, null))
                            } else {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color, null))
                            }
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick =
                    object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                        override fun onItemClick(position: Int) {
                            binding.paymentMark.text = OASystem.paymentMark[position].name
                            paymentMarkId = OASystem.paymentMark[position].id
                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.commit.setOnClickListener {

            if (!canBeEdit()) {
                back()
                return@setOnClickListener
            }

            if (binding.inviteeName.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.invitee_name_hint))
                return@setOnClickListener
            } else {
                updateInviteOfficialRequest.inviter = binding.inviteeName.text.toString()
            }

            if (binding.inviteeArea.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.invitee_city_hint))
                return@setOnClickListener
            } else {
                updateInviteOfficialRequest.inviterArea = binding.inviteeArea.text.toString()
            }

            if (binding.inviteeTime.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.invitee_time_hint))
                return@setOnClickListener
            } else {
                updateInviteOfficialRequest.inviteTime = binding.inviteeTime.text.toString()
            }

            if (binding.inviteContacts.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.invitee_contacts_hint))
                return@setOnClickListener
            } else {
                updateInviteOfficialRequest.contact = binding.inviteContacts.text.toString()
            }

            if (binding.contactsJob.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.contacts_job_hint))
                return@setOnClickListener
            } else {
                updateInviteOfficialRequest.job = binding.contactsJob.text.toString()
            }

            if (binding.contactsPhone.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.contacts_tel_hint))
                return@setOnClickListener
            } else {
                updateInviteOfficialRequest.tel = binding.contactsPhone.text.toString()
            }

            if (!binding.contactsEmail.text.isNullOrBlank()) {
                updateInviteOfficialRequest.email = binding.contactsEmail.text.toString()
            }

            if (!binding.contactsFax.text.isNullOrBlank()) {
                updateInviteOfficialRequest.fax = binding.contactsFax.text.toString()
            }

            if (binding.inviteeLocation.getText().isBlank()) {
                showMessage(resources.getString(R.string.invitee_location_hint))
                return@setOnClickListener
            } else {
                updateInviteOfficialRequest.address = binding.inviteeLocation.getText()
            }

            if (binding.otherInfo.getText().isNotBlank()) {
                updateInviteOfficialRequest.otherInformation = binding.otherInfo.getText()
            }

            if (binding.invitePayment.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.invite_payment_hint))
                return@setOnClickListener
            } else {
                updateInviteOfficialRequest.inviteCost = invitePayment
            }

            if (inviteCurrencyId == -1) {
                showMessage(resources.getString(R.string.invite_currency_hint))
                return@setOnClickListener
            } else {
                updateInviteOfficialRequest.inviteCurrency = inviteCurrencyId
            }

            if (binding.expressFee.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.express_fee_hint))
                return@setOnClickListener
            } else {
                updateInviteOfficialRequest.sendCost = expressPayment
            }

            if (expressCurrencyId == -1) {
                showMessage(resources.getString(R.string.express_currency_hint))
                return@setOnClickListener
            } else {
                updateInviteOfficialRequest.sendCurrency = expressCurrencyId
            }

            if (binding.officialActivityPayment.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.activity_payment_hint))
                return@setOnClickListener
            } else {
                updateInviteOfficialRequest.eventsCost = activityPayment
            }

            if (activityCurrencyId == -1) {
                showMessage(resources.getString(R.string.activity_currency_hint))
                return@setOnClickListener
            } else {
                updateInviteOfficialRequest.eventsCurrency = activityCurrencyId
            }

            if (binding.officialTranslatePayment.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.translate_payment_hint))
                return@setOnClickListener
            } else {
                updateInviteOfficialRequest.translateCost = translatePayment
            }

            if (translateCurrencyId == -1) {
                showMessage(resources.getString(R.string.translate_currency_hint))
                return@setOnClickListener
            } else {
                updateInviteOfficialRequest.translateCurrency = translateCurrencyId
            }

            updateInviteOfficialRequest.payMoney = totalPayment

            updateInviteOfficialRequest.paymentCurrency = totalCurrencyId

            if (paymentWayId == -1) {
                showMessage(resources.getString(R.string.payment_way_hint))
                return@setOnClickListener
            } else {
                updateInviteOfficialRequest.payDId = paymentWayId
            }

            if (binding.consumeWay.text.isBlank()) {
                showMessage(resources.getString(R.string.consume_way_hint))
                return@setOnClickListener
            } else {
                updateInviteOfficialRequest.consumptionPatterns = binding.consumeWay.text.toString()
            }

            if (binding.consumeDate.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.consume_date_select_hint))
                return@setOnClickListener
            } else {
                updateInviteOfficialRequest.consumptionDate = binding.consumeDate.text.toString()
            }

            when (paymentWayId) {
                72 -> {
                    if (!cardTypeSelect) {
                        showMessage(resources.getString(R.string.card_type_select_hint))
                        return@setOnClickListener
                    } else {
                        updateInviteOfficialRequest.ctdId = cardTypeId
                        updateInviteOfficialRequest.bankNo = bankNo
                        updateInviteOfficialRequest.cardholderName =
                            binding.bankCardOwner.text.toString()
                    }
                }

                73 -> {
                    if (binding.companyBankNo.text.isBlank()) {
                        showMessage(resources.getString(R.string.company_blank_number_input_hint))
                        return@setOnClickListener
                    } else {
                        updateInviteOfficialRequest.companyBankNo =
                            binding.companyBankNo.text.toString()
                    }

                    if (binding.transferOtherBankName.text.isBlank()) {
                        showMessage(resources.getString(R.string.other_blank_name_input_hint))
                        return@setOnClickListener
                    } else {
                        updateInviteOfficialRequest.otherBankName =
                            binding.transferOtherBankName.text.toString()
                    }

                    if (binding.transferOtherSideNo.text.isBlank()) {
                        showMessage(resources.getString(R.string.other_side_no))
                        return@setOnClickListener
                    } else {
                        updateInviteOfficialRequest.otherSideNo =
                            binding.transferOtherSideNo.text.toString()
                    }

                    if (binding.transferOtherSideName.text.isBlank()) {
                        showMessage(resources.getString(R.string.other_side_name))
                        return@setOnClickListener
                    } else {
                        updateInviteOfficialRequest.otherSideName =
                            binding.transferOtherSideName.text.toString()
                    }

                }

                83 -> {
                    if (binding.otherBankName.text.isBlank()) {
                        showMessage(resources.getString(R.string.transfer_other_bank_name_input_hint))
                        return@setOnClickListener
                    } else {
                        updateInviteOfficialRequest.otherBankName =
                            binding.otherBankName.text.toString()
                    }

                    if (binding.otherSideNo.text.isBlank()) {
                        showMessage(resources.getString(R.string.other_side_number_input_hint))
                        return@setOnClickListener
                    } else {
                        updateInviteOfficialRequest.otherSideNo =
                            binding.otherSideNo.text.toString()
                    }

                    if (binding.otherSideName.text.isBlank()) {
                        showMessage(resources.getString(R.string.other_side_name_input_hint))
                        return@setOnClickListener
                    } else {
                        updateInviteOfficialRequest.otherSideName =
                            binding.otherSideName.text.toString()
                    }
                }
            }

            if (binding.payee.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.payee_hint))
                return@setOnClickListener
            } else {
                updateInviteOfficialRequest.payee = binding.payee.text.toString()
            }

            if (paymentMarkId == -1) {
                showMessage(resources.getString(R.string.payment_mark_hint))
                return@setOnClickListener
            } else {
                updateInviteOfficialRequest.orbitalPrivateTransfer = paymentMarkId
            }

            if (binding.notes.getText().trim().isNotBlank()) {
                updateInviteOfficialRequest.remark = binding.notes.getText()
            }

            when (binding.isAttend.checkedRadioButtonId) {
                binding.yes.id -> {
                    updateInviteOfficialRequest.isGoOfficaiaBussiness = 1
                }

                binding.no.id -> {
                    updateInviteOfficialRequest.isGoOfficaiaBussiness = 0
                }
            }

            if (fromList) {
                updateInviteOfficialRequest.status = 2
                updateInvitePayment(2)
            } else {
                updateInviteOfficialRequest.status = 1
                updateInviteOfficialRequest.diId = groupId
                updateInvitePayment(1)
            }
        }
    }

    private fun getBaseData() {
        apiService.getInviteOfficialBaseData()
            .enqueue(object : Callback<InviteOfficialBaseDataResponse> {
                override fun onResponse(
                    call: Call<InviteOfficialBaseDataResponse>,
                    response: Response<InviteOfficialBaseDataResponse>
                ) {
                    val dataResponse = response.body()

                    if (dataResponse != null) {
                        if (dataResponse.code == 200) {
                            for (item in dataResponse.data.payTypeData) {
                                paymentWayList.add(item)
                            }

                            for (item in dataResponse.data.cardTypeData) {
                                cardList.add(item)
                            }

                            getCurrencyList()

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

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

    private fun getCurrencyList() {
        apiService.getGroupCurrency(GroupCurrencyRequest(groupId, OASystem.C_TABLE_INVITE_OFFICIAL))
            .enqueue(object : Callback<GroupCurrencyResponse> {
                override fun onResponse(
                    call: Call<GroupCurrencyResponse>, response: Response<GroupCurrencyResponse>
                ) {
                    val currencyResponse = response.body()

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

                            for (item in currencyResponse.data.teamRates) {
                                currencyList.add(item)
                            }

                            initViews()
                            initEvents()

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

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

    private fun calculateTotalPayment() {

        isExpressCurrency = expressCurrencyId == inviteCurrencyId

        isActivityCurrency = activityCurrencyId == inviteCurrencyId

        isTranslateCurrency = translateCurrencyId == inviteCurrencyId

        if (isExpressCurrency && isActivityCurrency && isTranslateCurrency) {

            totalPayment = invitePayment + expressPayment + activityPayment + translatePayment

            totalCurrencyId = inviteCurrencyId

            run {
                for (item in currencyList) {
                    if (item.currencyId == totalCurrencyId) {
                        binding.sumUnit.text = item.currencyCode
                        return@run
                    }
                }
            }

        } else {

            if (inviteCurrencyId != -1 && expressCurrencyId != -1 && activityCurrencyId != -1 && translateCurrencyId != -1) {

                totalPayment =
                    invitePayment * inviteRate + expressPayment * expressRate + activityPayment * activityRate + translatePayment * translateRate

                run {
                    for (item in currencyList) {
                        if (item.currencyCode == "CNY") {
                            totalCurrencyId = item.currencyId
                            binding.sumUnit.text = item.currencyCode
                            return@run
                        }
                    }
                }
            }
        }

        val decimalFormat = DecimalFormat("#.##")
        totalPayment = decimalFormat.format(totalPayment).toDouble()

        binding.paymentSum.text = totalPayment.toString()
    }

    private fun getInviteOfficialDetail() {
        apiService.getInviteOfficialPaymentDetail(InviteOfficialDetailRequest(paymentId))
            .enqueue(object : Callback<InviteOfficialDetailResponse> {
                override fun onResponse(
                    call: Call<InviteOfficialDetailResponse>,
                    response: Response<InviteOfficialDetailResponse>
                ) {
                    val detailResponse = response.body()

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

                            detailResponse.data.apply {

                                updateInviteOfficialRequest.diId = diId

                                updateInviteOfficialRequest.id = id

                                binding.inviteeName.setText(inviter)
                                binding.inviteeArea.setText(inviterArea)
                                binding.inviteeTime.text = inviteTime.substring(0, 10)

                                when (isGoOfficaiaBussiness) {
                                    1 -> {
                                        binding.yes.isChecked = true
                                    }

                                    0 -> {
                                        binding.no.isChecked = true
                                    }
                                }

                                binding.inviteContacts.setText(contact)
                                binding.contactsJob.setText(job)
                                binding.contactsPhone.setText(tel)
                                binding.contactsEmail.setText(email)
                                binding.contactsFax.setText(fax)
                                binding.inviteeLocation.setText(address)
                                binding.otherInfo.setText(otherInformation)

                                invitePayment = inviteCost
                                binding.invitePayment.setText(invitePayment.toString())
                                inviteCurrencyId = inviteCurrency

                                run {
                                    for (item in currencyList) {
                                        if (inviteCurrencyId == item.currencyId) {
                                            binding.inviteUnit.text = item.currencyCode
                                            inviteRate = item.rate
                                            return@run
                                        }
                                    }
                                }

                                expressPayment = sendCost
                                binding.expressFee.setText(expressPayment.toString())
                                expressCurrencyId = sendCurrency

                                run {
                                    for (item in currencyList) {
                                        if (expressCurrencyId == item.currencyId) {
                                            binding.expressUnit.text = item.currencyCode
                                            expressRate = item.rate
                                            return@run
                                        }
                                    }
                                }

                                activityPayment = eventsCost
                                binding.officialActivityPayment.setText(activityPayment.toString())
                                activityCurrencyId = eventsCurrency

                                run {
                                    for (item in currencyList) {
                                        if (activityCurrencyId == item.currencyId) {
                                            binding.officialActivityUnit.text = item.currencyCode
                                            activityRate = item.rate
                                            return@run
                                        }
                                    }
                                }

                                translatePayment = translateCost
                                binding.officialTranslatePayment.setText(translatePayment.toString())
                                translateCurrencyId = translateCurrency

                                run {
                                    for (item in currencyList) {
                                        if (translateCurrencyId == item.currencyId) {
                                            binding.officialTranslateUnit.text = item.currencyCode
                                            translateRate = item.rate
                                            return@run
                                        }
                                    }
                                }

                                totalPayment = payMoney
                                binding.paymentSum.text = totalPayment.toString()
                                totalCurrencyId = paymentCurrency

                                run {
                                    for (item in currencyList) {
                                        if (totalCurrencyId == item.currencyId) {
                                            binding.sumUnit.text = item.currencyCode
                                            return@run
                                        }
                                    }
                                }

                                paymentWayId = payDId

                                for (item in paymentWayList) {
                                    if (item.id == payDId) {
                                        updateInviteOfficialRequest.payDId = item.id
                                        binding.paymentWay.text = item.name
                                    }
                                }

                                binding.consumeWay.setText(consumptionPatterns)
                                binding.consumeDate.text = consumptionDate

                                binding.paymentSum.text = payMoney.toString()
                                totalCurrencyId

                                when (paymentWayId) {
                                    //刷卡
                                    72 -> {
                                        binding.swipe.visibility = View.VISIBLE
                                        binding.transfer.visibility = View.GONE
                                        binding.remit.visibility = View.GONE

                                        run {
                                            for (item in cardList) {
                                                if (item.id == ctdId) {
                                                    binding.cardType.text = item.name
                                                    binding.bankCardNumber.text = item.remark
                                                    binding.bankCardOwner.text = item.cardholder
                                                    cardTypeId = item.id
                                                    bankNo = item.remark
                                                    cardTypeSelect = true

                                                    return@run
                                                }
                                            }
                                        }
                                    }

                                    //转账
                                    73 -> {
                                        binding.swipe.visibility = View.GONE
                                        binding.transfer.visibility = View.VISIBLE
                                        binding.remit.visibility = View.GONE

                                        binding.companyBankNo.setText(companyBankNo)

                                        binding.transferOtherBankName.setText(otherBankName)

                                        binding.transferOtherSideNo.setText(otherSideNo)

                                        binding.transferOtherSideName.setText(otherSideName)
                                    }

                                    //汇款
                                    83 -> {
                                        binding.swipe.visibility = View.GONE
                                        binding.transfer.visibility = View.GONE
                                        binding.remit.visibility = View.VISIBLE

                                        binding.otherBankName.setText(otherBankName)

                                        binding.otherSideNo.setText(otherSideNo)

                                        binding.otherSideName.setText(otherSideName)
                                    }

                                    else -> {
                                        binding.swipe.visibility = View.GONE
                                        binding.transfer.visibility = View.GONE
                                        binding.remit.visibility = View.GONE
                                    }
                                }

                                binding.payee.setText(payee)

                                for (item in OASystem.paymentMark) {
                                    if (item.id == orbitalPrivateTransfer) {
                                        paymentMarkId = item.id
                                        binding.paymentMark.text = item.name
                                    }
                                }

                                binding.notes.setText(remark)
                            }

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

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

    private fun updateInvitePayment(type: Int) {

        binding.commit.setButtonStatus(1)

        apiService.inviteOfficialPaymentOperate(updateInviteOfficialRequest)
            .enqueue(object : Callback<BaseResponse> {
                override fun onResponse(
                    call: Call<BaseResponse>, response: Response<BaseResponse>
                ) {

                    val baseResponse = response.body()
                    if (baseResponse != null) {
                        if (baseResponse.code == 200) {
                            if (type == 1) {
                                showMessage(resources.getString(R.string.insert_success))
                            } else {
                                showMessage(resources.getString(R.string.update_success))
                            }

                            OASystem.needRefresh = true

                            back()

                        } else {

                            binding.commit.setButtonStatus(0)

                            showMessage(baseResponse.msg)
                        }
                    }
                }

                override fun onFailure(call: Call<BaseResponse>, t: Throwable) {

                    binding.commit.setButtonStatus(0)

                    showErrorInfo(R.string.update_error)
                }
            })
    }

    private fun canBeEdit(): Boolean {
        return OASystem.authorization(OASystem.INVITE_OFFICIAL_PAYMENT, OASystem.EDIT) and (isAudit == 0)
    }
}