package com.pan_american.android.ui.group_visa.visa_payment_insert

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.PopupWindow
import android.widget.TextView
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
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.CardAdapter
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.GroupClientListRequest
import com.pan_american.android.data.model.common.network.GroupClientListResponse
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_visa.visa_payment_insert.network.UpdateVisaPaymentRequest
import com.pan_american.android.data.model.group_visa.visa_payment_insert.network.VisaPaymentDetailRequest
import com.pan_american.android.data.model.group_visa.visa_payment_insert.network.VisaPaymentDetailResponse
import com.pan_american.android.data.model.group_visa.visa_payment_insert.network.VisaPaymentSelectorResourceResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.ActivityAddVisaPaymentBinding
import com.pan_american.android.databinding.LayoutTitleBinding
import com.pan_american.android.util.CommitButton
import com.pan_american.android.util.MoneyInputFilter
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class AddVisaPaymentActivity : BaseActivity<ActivityAddVisaPaymentBinding>() {

    private lateinit var titleBinding: LayoutTitleBinding

    private var fromList = false

    private var groupId = 0

    private var paymentId = 0

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

    private var customerList = ArrayList<Selector>()

    private var customerSelectList = ArrayList<Selector>()

    private var priceUnit = -1

    private var priceUnitList = ArrayList<Selector>()

    private var customerTypeSelect = false

    private var customerTypeList = ArrayList<Selector>()

    private var paymentWaySelect = false

    private var paymentWayList = ArrayList<Selector>()

    private var paymentWayId = -1

    private var cardTypeSelect = false

    private var cardTypeList = ArrayList<Selector>()

    private var cardTypeId = -1

    private var bankNo = ""

    private var paymentMarkId = -1

    private var paymentMarkSelect = false

    private val regex = Regex("^-?\\d+(\\.\\d{1,2})?\$")

    private var updateVisaPaymentRequest = UpdateVisaPaymentRequest()

    private var isAuditGM = -1

    private var agencyFeeTypeId = -1

    private val agencyFeeTypeList = ArrayList<Selector>()

    private val countryFeeList = ArrayList<Selector>()

    override fun getViewBinding() = ActivityAddVisaPaymentBinding.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.priceUnit.text = getStringExtra("paymentCurrency")
                binding.sumUnit.text = getStringExtra("paymentCurrency")

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

        initTitle()

        getVisaPaymentSelector()

    }

    override fun initTitle() {

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

            backButton.setOnClickListener {
                back()
            }
        }
    }

    override fun initViews() {

        binding.visaPrice.filters = arrayOf(MoneyInputFilter())

        if (fromList) {
            getVisaPaymentDetail()

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

            if (!canBeEdit()) {
                binding.apply {

                    visaDescription.isEnabled(false)
                    area.isEnabled = false
                    agencyFeeType.isEnabled = false
                    addCustomer.visibility = View.GONE
                    visaPrice.isEnabled = false
                    priceUnit.isEnabled = false
                    isAgentYes.isEnabled = false
                    isAgentNo.isEnabled = false
                    customerType.isEnabled = false
                    visaHandleNumber.isEnabled = false
                    visaExemptionNumber.isEnabled = false
                    notes.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
                    paymentApplyNotes.isEnabled(false)

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

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

            initCustomerList()

            binding.visaHandleNumber.setText(customerSelectList.size.toString())

            binding.visaExemptionNumber.setText("0")

            for (item in priceUnitList) {
                if (item.currencyCode == "CNY") {
                    binding.priceUnit.text = item.currencyCode
                    binding.sumUnit.text = item.currencyCode
                    priceUnit = item.currencyId
                }
            }
        }
    }

    override fun initEvents() {

        binding.area.setOnClickListener {

            val selectDataSource = ArrayList<Selector>()

            for (item in countryFeeList) {
                selectDataSource.add(item)
            }

            val searchSelectorView =
                View.inflate(OASystem.context, R.layout.popup_list_selector_with_search, null)
            popupWindow = PopupWindow(
                searchSelectorView,
                ViewGroup.LayoutParams.MATCH_PARENT,
                binding.root.height * 3 / 4
            )

            showPopupWindow {

                val searchTextView = searchSelectorView.findViewById<EditText>(R.id.search_text)
                val selectorView = searchSelectorView.findViewById<RecyclerView>(R.id.recycler_view)

                val layoutManager = LinearLayoutManager(OASystem.context)
                selectorView.layoutManager = layoutManager

                val adapter = ListAdapter.Builder<Selector>().apply {
                    setData(selectDataSource)
                    setLayoutId(R.layout.item_selector)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            if (binding.area.text == data.country) {
                                setTextColor(
                                    ResourcesCompat.getColor(
                                        resources,
                                        R.color.text_color_blue,
                                        null
                                    )
                                )
                            } else {
                                setTextColor(
                                    ResourcesCompat.getColor(
                                        resources,
                                        R.color.text_color,
                                        null
                                    )
                                )
                            }

                            text = data.country
                        }
                    }
                }.create()

                selectorView.adapter = adapter

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

                            binding.area.text = selectDataSource[position].country

                            popupWindow.dismiss()
                        }
                    }

                searchTextView.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?) {
                        adapter.notifyItemRangeRemoved(0, selectDataSource.size)

                        selectDataSource.clear()

                        for (item in countryFeeList) {
                            if (item.country.contains(s.toString())) {
                                selectDataSource.add(item)
                            }
                        }

                        adapter.notifyItemRangeInserted(0, selectDataSource.size)
                    }
                })

                popupWindow.showAtLocation(binding.root, Gravity.BOTTOM, 0, 0)
            }
        }

        binding.agencyFeeType.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setData(agencyFeeTypeList)
                    setLayoutId(R.layout.item_selector)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            if (data.id == agencyFeeTypeId) {
                                setTextColor(
                                    ResourcesCompat.getColor(
                                        resources,
                                        R.color.text_color_blue,
                                        null
                                    )
                                )
                            } else {
                                setTextColor(
                                    ResourcesCompat.getColor(
                                        resources,
                                        R.color.text_color,
                                        null
                                    )
                                )
                            }

                            text = data.text
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick =
                    object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                        override fun onItemClick(position: Int) {
                            agencyFeeTypeList[position].apply {
                                agencyFeeTypeId = id

                                binding.agencyFeeType.text = text

                                popupWindow.dismiss()
                            }
                        }
                    }
            }
        }

        binding.addCustomer.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setData(customerList)
                    setLayoutId(R.layout.item_selector)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text = String.format(
                                resources.getString(R.string.currency_name_code_format),
                                String.format(
                                    resources.getString(R.string.with_space_format),
                                    data.lastName,
                                    data.firstName
                                ),
                                data.pinyin
                            )

                            for (item in customerSelectList) {
                                if (data.id == item.id) {
                                    setTextColor(
                                        ResourcesCompat.getColor(
                                            resources, R.color.title_background_color, null
                                        )
                                    )
                                }
                            }
                        }
                    }
                }.create()

                selector.adapter = adapter

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

                            for (item in customerSelectList) {
                                if (customerList[position].id == item.id) {
                                    showMessage(resources.getString(R.string.customer_selected))
                                    popupWindow.dismiss()
                                    return
                                }
                            }

                            customerSelectList.add(customerList[position])
                            initCustomerList()

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.visaPrice.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?) {
                binding.paymentSum.text = binding.visaPrice.text
            }
        })

        binding.priceUnit.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setData(priceUnitList)
                    setLayoutId(R.layout.item_selector)
                    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 (priceUnit == 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.priceUnit.text = priceUnitList[position].currencyCode
                            binding.sumUnit.text = priceUnitList[position].currencyCode
                            priceUnit = priceUnitList[position].currencyId

                            popupWindow.dismiss()
                        }
                    }
            }
        }

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

                            if (updateVisaPaymentRequest.passengerType == 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.customerType.text = customerTypeList[position].name
                            updateVisaPaymentRequest.passengerType = customerTypeList[position].id
                            customerTypeSelect = true

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.paymentWay.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setData(paymentWayList)
                    setLayoutId(R.layout.item_selector)
                    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) {
                            paymentWayId = paymentWayList[position].id
                            binding.paymentWay.text = paymentWayList[position].name
                            paymentWaySelect = true

                            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(cardTypeList)
                    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 = cardTypeList[position].name
                            binding.bankCardNumber.text = cardTypeList[position].remark
                            cardTypeId = cardTypeList[position].id
                            bankNo = cardTypeList[position].remark
                            cardTypeSelect = true

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.paymentMark.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setData(OASystem.paymentMark)
                    setLayoutId(R.layout.item_selector)
                    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) {
                            paymentMarkId = OASystem.paymentMark[position].id
                            binding.paymentMark.text = OASystem.paymentMark[position].name
                            paymentMarkSelect = true

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.commit.setOnClickListener {

            updateVisaPaymentRequest.id = paymentId
            updateVisaPaymentRequest.diId = groupId

            if (binding.visaDescription.getText().isBlank()) {
                showMessage(resources.getString(R.string.visa_description_hint))
                return@setOnClickListener
            } else {
                updateVisaPaymentRequest.visaDescription = binding.visaDescription.getText()
            }

            if (agencyFeeTypeId == -1) {
                showMessage(resources.getString(R.string.agency_fee_type_select_hint))
                return@setOnClickListener
            } else {
                updateVisaPaymentRequest.agencyFeeType = agencyFeeTypeId
            }

            if (binding.area.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.area_select_hint))
                return@setOnClickListener
            } else {
                updateVisaPaymentRequest.area = binding.area.text.toString()
            }

            if (customerSelectList.size == 0) {
                showMessage(resources.getString(R.string.customer_select_hint))
                return@setOnClickListener
            } else {
                var i = 0
                var clientList = ""

                while (i < customerSelectList.size) {

                    clientList += customerSelectList[i].id.toString()

                    i += 1

                    if (i < customerSelectList.size) {
                        clientList += ","
                    }
                }

                updateVisaPaymentRequest.visaClient = clientList
            }

            if (!binding.visaPrice.text.toString().matches(regex)) {
                showMessage(resources.getString(R.string.payment_price_hint))
                return@setOnClickListener
            } else {
                updateVisaPaymentRequest.visaPrice = binding.visaPrice.text.toString().toDouble()
            }

            if (priceUnit == -1) {
                showMessage(resources.getString(R.string.payment_currency_hint))
                return@setOnClickListener
            } else {
                updateVisaPaymentRequest.visaCurrency = priceUnit
            }

            if (!binding.isAgentYes.isChecked && !binding.isAgentNo.isChecked) {
                showMessage(resources.getString(R.string.is_agent_select_hint))
                return@setOnClickListener
            } else {
                when (binding.isAgent.checkedRadioButtonId) {
                    R.id.is_agent_yes -> {
                        updateVisaPaymentRequest.isThird = 1
                    }

                    R.id.is_agent_no -> {
                        updateVisaPaymentRequest.isThird = 0
                    }
                }
            }

            if (binding.customerType.text.isBlank()) {
                showMessage(resources.getString(R.string.customer_type_select_hint))
                return@setOnClickListener
            }

            if (binding.visaHandleNumber.text.isBlank()) {
                showMessage(resources.getString(R.string.visa_handle_number_input_hint))
                return@setOnClickListener
            } else {
                updateVisaPaymentRequest.visaNumber =
                    binding.visaHandleNumber.text.toString().toInt()
            }

            if (binding.visaExemptionNumber.text.isBlank()) {
                showMessage(resources.getString(R.string.visa_exemption_number_input_hint))
                return@setOnClickListener
            } else {
                updateVisaPaymentRequest.visaFreeNumber =
                    binding.visaExemptionNumber.text.toString().toInt()
            }

            if (binding.visaHandleNumber.text.toString()
                    .toInt() + binding.visaExemptionNumber.text.toString()
                    .toInt() != customerSelectList.size
            ) {
                showMessage(resources.getString(R.string.customer_number_input_hint))
                return@setOnClickListener
            }

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

            if (!paymentWaySelect) {
                showMessage(resources.getString(R.string.payment_way_hint))
                return@setOnClickListener
            } else {
                updateVisaPaymentRequest.payDId = paymentWayId
            }

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

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

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

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

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

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

                    if (binding.transferOtherSideName.text.isBlank()) {
                        showMessage(resources.getString(R.string.other_side_name))
                        return@setOnClickListener
                    } else {
                        updateVisaPaymentRequest.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 {
                        updateVisaPaymentRequest.otherBankName =
                            binding.otherBankName.text.toString()
                    }

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

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

            if (binding.payee.text.isNotBlank()) {
                updateVisaPaymentRequest.payee = binding.payee.text.trim().toString()
            }

            if (!paymentMarkSelect) {
                showMessage(resources.getString(R.string.payment_mark_hint))
                return@setOnClickListener
            } else {
                updateVisaPaymentRequest.orbitalPrivateTransfer = paymentMarkId
            }

            if (binding.paymentApplyNotes.getText().trim().isNotBlank()) {
                updateVisaPaymentRequest.cRemark = binding.paymentApplyNotes.getText()
            }

            if (fromList) {
                updateVisaPaymentRequest.status = 2
            } else {
                updateVisaPaymentRequest.status = 1
            }

            updateVisaPayment()
        }
    }

    private fun getVisaPaymentSelector() {
        apiService.getVisaPaymentSelectorResource()
            .enqueue(object : Callback<VisaPaymentSelectorResourceResponse> {
                override fun onResponse(
                    call: Call<VisaPaymentSelectorResourceResponse>,
                    response: Response<VisaPaymentSelectorResourceResponse>
                ) {
                    val selectorResponse = response.body()

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

                            for (item in selectorResponse.data.payment) {
                                paymentWayList.add(item)
                            }

                            for (item in selectorResponse.data.passengerType) {
                                customerTypeList.add(item)
                            }

                            for (item in selectorResponse.data.bankCard) {
                                cardTypeList.add(item)
                            }

                            for (item in selectorResponse.data.agencyFeeType) {
                                agencyFeeTypeList.add(item)
                            }

                            for (item in selectorResponse.data.countryFeeData) {
                                countryFeeList.add(item)
                            }

                            getCustomerList()

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

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

    private fun getCustomerList() {
        apiService.getClientListByDiId(GroupClientListRequest(groupId))
            .enqueue(object : Callback<GroupClientListResponse> {
                override fun onResponse(
                    call: Call<GroupClientListResponse>, response: Response<GroupClientListResponse>
                ) {

                    val customerListResponse = response.body()

                    if (customerListResponse != null) {
                        if (customerListResponse.code == 200) {
                            for (item in customerListResponse.data) {
                                customerList.add(item)

                                if (!fromList) {
                                    customerSelectList.add(item)
                                }
                            }

                            getCurrencyByGroupId()

                        } else {
                            showMessage(customerListResponse.msg)
                        }
                    }

                }

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

    private fun getCurrencyByGroupId() {
        apiService.getGroupCurrency(GroupCurrencyRequest(groupId, OASystem.C_TABLE_VISA))
            .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) {
                                priceUnitList.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 initCustomerList() {
        val layoutManager = LinearLayoutManager(OASystem.context)
        binding.customerList.layoutManager = layoutManager

        val adapter = CardAdapter.Builder<Selector>().apply {
            setData(customerSelectList)
            setLayoutId(R.layout.item_delete_button_selector)
            setCanDelete(canBeEdit())
            addBindView { itemView, data ->
                itemView.findViewById<TextView>(R.id.left_text).text = data.pinyin
                itemView.findViewById<TextView>(R.id.right_text).text = String.format(
                    resources.getString(R.string.with_space_format), data.lastName, data.firstName
                )
            }
        }.create()

        binding.customerList.adapter = adapter

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

            }

            override fun onItemDelete(position: Int) {

                customerSelectList.removeAt(position)
                binding.customerList.adapter!!.notifyItemRemoved(position)
                binding.customerList.adapter!!.notifyItemRangeChanged(
                    position,
                    customerSelectList.size - position
                )

            }
        }
    }

    private fun getVisaPaymentDetail() {
        apiService.getVisaPaymentDetail(VisaPaymentDetailRequest(paymentId))
            .enqueue(object : Callback<VisaPaymentDetailResponse> {
                override fun onResponse(
                    call: Call<VisaPaymentDetailResponse>,
                    response: Response<VisaPaymentDetailResponse>
                ) {
                    val visaPaymentDetailResponse = response.body()

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

                            visaPaymentDetailResponse.data.visaInfo.apply {
                                binding.visaDescription.setText(visaDescription)

                                binding.area.text = area

                                for (item in agencyFeeTypeList) {
                                    if (item.id == agencyFeeType) {
                                        binding.agencyFeeType.text = item.text

                                        agencyFeeTypeId = item.id
                                    }
                                }

                                val customer = visaClient.split(",")

                                for (selectedItem in customer) {
                                    for (item in customerList) {
                                        if (selectedItem.matches(Regex("[0-9]*\$"))) {
                                            if (selectedItem.toInt() == item.id) {
                                                customerSelectList.add(item)
                                            }
                                        }
                                    }
                                }

                                initCustomerList()

                                binding.visaPrice.setText(visaPrice.toString())

                                priceUnit = visaCurrency

                                when (isThird) {
                                    0 -> {
                                        binding.isAgentNo.isChecked = true
                                    }

                                    1 -> {
                                        binding.isAgentYes.isChecked = true
                                    }
                                }

                                run {
                                    for (item in customerTypeList) {
                                        if (item.id == passengerType) {
                                            binding.customerType.text = item.name
                                            updateVisaPaymentRequest.passengerType = item.id
                                            customerTypeSelect = true
                                            return@run
                                        }
                                    }
                                }

                                binding.visaHandleNumber.setText(visaNumber.toString())
                                binding.visaExemptionNumber.setText(visaFreeNumber.toString())

                                binding.notes.setText(remark)
                            }

                            visaPaymentDetailResponse.data.creditCardPayment.apply {
                                run {
                                    for (item in paymentWayList) {
                                        if (item.id == payDId) {
                                            binding.paymentWay.text = item.name
                                            paymentWayId = item.id
                                            paymentWaySelect = true

                                            return@run
                                        }
                                    }
                                }

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

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

                                        run {
                                            for (item in cardTypeList) {
                                                if (item.id == ctdId) {
                                                    binding.cardType.text = item.name
                                                    binding.bankCardNumber.text = item.remark
                                                    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)

                                binding.paymentMark.text =
                                    OASystem.paymentMark[orbitalPrivateTransfer].name
                                paymentMarkId = orbitalPrivateTransfer
                                paymentMarkSelect = true

                                if (visaPaymentDetailResponse.data.creditCardPayment.remark.isNotBlank()) {
                                    binding.paymentApplyNotes.setText(remark)
                                }
                            }

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

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

    private fun updateVisaPayment() {

        binding.commit.setButtonStatus(CommitButton.STATUS_IN_COMMITING)

        apiService.updateVisaPayment(updateVisaPaymentRequest)
            .enqueue(object : Callback<BaseResponse> {
                override fun onResponse(
                    call: Call<BaseResponse>, response: Response<BaseResponse>
                ) {
                    val updateResponse = response.body()

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

                            if (fromList) {
                                showMessage(resources.getString(R.string.update_success))
                            } else {
                                showMessage(resources.getString(R.string.insert_success))
                            }

                            OASystem.needRefresh = true

                            back()

                        } else {

                            binding.commit.setButtonStatus(CommitButton.STATUS_COMMITTED)

                            showMessage(updateResponse.msg)
                        }
                    }
                }

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

                    binding.commit.setButtonStatus(CommitButton.STATUS_COMMITTED)

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

    private fun canBeEdit(): Boolean {
        return OASystem.authorization(
            OASystem.VISA_PAYMENT_INSERT,
            OASystem.EDIT
        ) and (isAuditGM != 1)
    }
}