package com.pan_american.android.ui.group_hotel.hotel_predetermine

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.PopupWindow
import android.widget.TextView
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.bin.david.form.core.SmartTable
import com.bin.david.form.data.style.FontStyle
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.CustomAlertDialog
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.GroupCostDataRequest
import com.pan_american.android.data.model.group_hotel.hotel_payment_insert.entity.HotelCost
import com.pan_american.android.data.model.group_hotel.hotel_payment_insert.entity.UpdateHotelPredetermine
import com.pan_american.android.data.model.group_hotel.hotel_payment_insert.network.GetHotelPredetermineDetailRequest
import com.pan_american.android.data.model.group_hotel.hotel_payment_insert.network.GetHotelPredetermineDetailResponse
import com.pan_american.android.data.model.group_hotel.hotel_payment_insert.network.HotelCostDetailResponse
import com.pan_american.android.data.model.group_hotel.hotel_payment_insert.network.HotelPredetermineResourceRequest
import com.pan_american.android.data.model.group_hotel.hotel_payment_insert.network.HotelPredetermineResourceResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.ActivityAddHotelPredetermineBinding
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
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

class AddHotelPredetermineActivity : BaseActivity<ActivityAddHotelPredetermineBinding>() {

    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 guestType = ArrayList<Selector>()

    private var customerTypeId = 0

    private var customerTypeSelect = false

    private var currencyList = ArrayList<Selector>()

    private var websiteList = ArrayList<Selector>()

    private var websiteId = 0

    private var websiteSelect = false

    private var customerList = ArrayList<Selector>()

    private var customerSelectList = ArrayList<Selector>()

    private var cardList = ArrayList<Selector>()

    private var bankCardId = 0

    private var bankCardCurrencyId = 0

    private var bankCardRate = 0.0

    private var bankCardSelect = false

    private var bankCardCurrencyStr = ""

    private var paymentWayList = ArrayList<Selector>()

    private var paymentWayId = 0

    private var paymentWaySelect = false

    private var checkInTypeList = ArrayList<Selector>()

    private var checkInTypeId = 0

    private var checkInTypeSelect = false

    private var paymentMarkId = -1

    private var paymentMarkSelect = false

    private var bankNumber = ""

    private var breakfastUnitId = 0

    private var breakfastRate = 0.0

    private var localTaxUnitId = 0

    private var localTaxRate = 0.0

    private var cityTaxUnitId = 0

    private var cityTaxRate = 0.0

    private var consumeDateSelect = false

    private var sumUnitCurrencyId = 0

    private var sumUnitCurrencyStr = ""

    private var updateHotelPredetermine = UpdateHotelPredetermine()

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

    private var singleRoomCount = 0

    private var singleRoomUnitPrice = 0.0

    private var singleRoomPrice = 0.0

    private var singleRoomPricePre = 0.0

    private var doubleRoomCount = 0

    private var doubleRoomUnitPrice = 0.0

    private var doubleRoomPrice = 0.0

    private var doubleRoomPricePre = 0.0

    private var suiteRoomCount = 0

    private var suiteRoomUnitPrice = 0.0

    private var suiteRoomPrice = 0.0

    private var suiteRoomPricePre = 0.0

    private var otherRoomCount = 0

    private var otherRoomUnitPrice = 0.0

    private var otherRoomPrice = 0.0

    private var otherRoomPricePre = 0.0

    private var breakfastPrice = 0.0

    private var localTax = 0.0

    private var cityTax = 0.0

    private var creditPayment = 0.0

    private var sumPayment = 0.0

    private var isBreakfastCurrency = true

    private var isLocalTaxCurrency = true

    private var isCityTaxCurrency = true

    private var hasCurrency = false

    private var isAuditGM = -1

    private var hotelCostInit = false

    private var hotelCostCurrency = ""

    private var hotelCostExchangeRate = 0.0

    private var hotelCostList = ArrayList<HotelCost>()

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

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

        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")

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

        initTitle()
        initViews()

        getSelectorResource()
    }

    override fun initTitle() {
        titleBinding = LayoutTitleBinding.bind(binding.root).apply {
            if (fromList) {
                titleText.text = resources.getString(R.string.hotel_payment_detail)
            } else {
                titleText.text = resources.getString(R.string.hotel_predetermine)
                binding.commit.setText(resources.getString(R.string.add))
            }

            rightTextField.apply {
                visibility = View.VISIBLE
                text = resources.getString(R.string.show_cost)
            }

            backButton.setOnClickListener {
                back()
            }

            rightTextField.setOnClickListener {

                val hotelCostPopView = View.inflate(OASystem.context, R.layout.popup_cost_table, null)
                popupWindow = PopupWindow(hotelCostPopView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)

                showPopupWindow {

                    val currencyAbbr = hotelCostPopView.findViewById<TextView>(R.id.currency_abbr)
                    val exchangeRate = hotelCostPopView.findViewById<TextView>(R.id.exchange_rate)
                    val hotelCostTable = hotelCostPopView.findViewById<SmartTable<HotelCost>>(R.id.table)

                    hotelCostTable.config.apply {
                        isShowXSequence = false
                        isShowYSequence = false
                        tableTitleStyle = FontStyle(50, ResourcesCompat.getColor(resources, R.color.text_color, theme))
                        contentStyle = FontStyle(40, ResourcesCompat.getColor(resources, R.color.text_color, theme))
                    }

                    if (!hotelCostInit) {
                        apiService.getGroupHotelCostData(GroupCostDataRequest(groupId, OASystem.C_TABLE_HOTEL_PREDETERMINE)).enqueue(object : Callback<HotelCostDetailResponse> {
                            override fun onResponse(
                                call: Call<HotelCostDetailResponse>,
                                response: Response<HotelCostDetailResponse>
                            ) {

                                val costResponse = response.body()

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

                                        hotelCostCurrency = costResponse.data.modulePromptInfos[0].currencyCode
                                        hotelCostExchangeRate = costResponse.data.modulePromptInfos[0].rate

                                        hotelCostList = costResponse.data.modulePromptInfos[0].data

                                        currencyAbbr.text = hotelCostCurrency
                                        exchangeRate.text = hotelCostExchangeRate.toString()

                                        hotelCostTable.setData(hotelCostList)

                                        hotelCostInit = true

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

                            override fun onFailure(call: Call<HotelCostDetailResponse>, t: Throwable) {
                                showErrorInfo(R.string.hotel_cost_detail_get_failed)
                            }
                        })
                    } else {
                        currencyAbbr.text = hotelCostCurrency
                        exchangeRate.text = hotelCostExchangeRate.toString()

                        hotelCostTable.setData(hotelCostList)
                    }

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

    override fun initViews() {

        binding.singleRoomPrice.filters = arrayOf(MoneyInputFilter())
        binding.doubleRoomPrice.filters = arrayOf(MoneyInputFilter())
        binding.suiteRoomPrice.filters = arrayOf(MoneyInputFilter())
        binding.otherRoomPrice.filters = arrayOf(MoneyInputFilter())
        binding.hotelBreakfast.filters = arrayOf(MoneyInputFilter())
        binding.localTax.filters = arrayOf(MoneyInputFilter())
        binding.cityTax.filters = arrayOf(MoneyInputFilter())

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

                    customerType.isEnabled = false
                    bankCard.isEnabled = false
                    predetermineWebsite.isEnabled = false
                    hotelConfirmCode.isEnabled = false
                    locatedCity.isEnabled = false
                    hotelName.isEnabled = false
                    hotelTel.isEnabled = false
                    hotelLocation.isEnabled(false)
                    addCustomer.visibility = View.GONE
                    checkInStartTime.isEnabled = false
                    checkInEndTime.isEnabled = false
                    checkInType.isEnabled = false
                    roomIntroduction.isEnabled(false)
                    hotelNotes.isEnabled(false)
                    realitySingleRoom.isEnabled = false
                    singleRoomPrice.isEnabled = false
                    realityDoubleRoom.isEnabled = false
                    doubleRoomPrice.isEnabled = false
                    realitySuiteRoom.isEnabled = false
                    suiteRoomPrice.isEnabled = false
                    realityOtherRoom.isEnabled = false
                    otherRoomPrice.isEnabled = false
                    hotelBreakfast.isEnabled = false
                    hotelBreakfastUnit.isEnabled = false
                    yes.isEnabled = false
                    no.isEnabled = false
                    localTax.isEnabled = false
                    localTaxUnit.isEnabled = false
                    cityTax.isEnabled = false
                    cityTaxUnit.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.update))
            }

        } else {

            binding.creditCardPayment.text = creditPayment.toString()
            binding.paymentSum.text = sumPayment.toString()

            binding.realitySingleRoom.setText(singleRoomCount.toString())
            binding.singleRoomPrice.setText(singleRoomUnitPrice.toString())
            binding.realityDoubleRoom.setText(doubleRoomCount.toString())
            binding.doubleRoomPrice.setText(doubleRoomUnitPrice.toString())
            binding.realitySuiteRoom.setText(suiteRoomCount.toString())
            binding.suiteRoomPrice.setText(suiteRoomUnitPrice.toString())
            binding.realityOtherRoom.setText(otherRoomCount.toString())
            binding.otherRoomPrice.setText(otherRoomUnitPrice.toString())

            binding.hotelBreakfast.setText(breakfastPrice.toString())
            binding.localTax.setText(localTax.toString())
            binding.cityTax.setText(cityTax.toString())

            initEvents()
        }
    }

    override fun initEvents() {

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

                            if (customerTypeId == data.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) {
                            binding.customerType.text = guestType[position].name

                            customerTypeId = guestType[position].id
                            customerTypeSelect = true

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.bankCard.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 (binding.bankCard.text == data.name) {
                                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) {

                            cardList[position].apply {
                                binding.bankCard.text = name
                                binding.cardType.text = name
                                binding.bankCardNumber.text = remark
                                binding.bankCardOwner.text = cardholder


                                bankNumber = remark

                                for (item in currencyList) {
                                    if (item.currencyCode == currency) {
                                        hasCurrency = true
                                        item.apply {
                                            bankCardCurrencyId = currencyId
                                            bankCardCurrencyStr = currencyCode
                                            bankCardRate = rate
                                            binding.singleRoomUnit.text = currencyCode
                                            binding.doubleRoomUnit.text = currencyCode
                                            binding.suiteRoomUnit.text = currencyCode
                                            binding.otherRoomUnit.text = currencyCode

                                            breakfastUnitId = currencyId
                                            breakfastRate = rate
                                            binding.hotelBreakfastUnit.text = currencyCode

                                            localTaxUnitId = currencyId
                                            localTaxRate = rate
                                            binding.localTaxUnit.text = currencyCode

                                            cityTaxUnitId = currencyId
                                            binding.cityTaxUnit.text = currencyCode
                                            cityTaxRate = rate

                                            sumUnitCurrencyId = currencyId
                                            binding.sumUnit.text = currencyCode
                                        }
                                    }
                                }
                            }

                            if (!hasCurrency) {
                                popupWindow.dismiss()
                                CustomAlertDialog.Builder(OASystem.context).apply {
                                    setTitle(resources.getString(R.string.alert))
                                    setMessage(resources.getString(R.string.currency_not_set_hint))
                                    setPositiveButtonAndListener(resources.getString(R.string.confirm)) { dialog, _ ->
                                        dialog.dismiss()
                                    }
                                }.show()
                                return
                            }

                            bankCardId = cardList[position].id
                            bankCardSelect = true

                            isBreakfastCurrency = true
                            isLocalTaxCurrency = true
                            isCityTaxCurrency = true

                            calculateTotalPayment()

                            popupWindow.dismiss()
                        }
                    }
            }
        }

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

                            if (websiteId == data.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) {
                            binding.predetermineWebsite.text = websiteList[position].name

                            websiteId = websiteList[position].id
                            websiteSelect = true

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.addCustomer.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setLayoutId(R.layout.item_selector)
                    setData(customerList)
                    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.checkInStartTime.setOnClickListener {
            showDatePicker(
                resources.getString(R.string.check_in_start_select_hint), binding.checkInStartTime
            ) {calculateRoomPayment(5)}
        }

        binding.checkInEndTime.setOnClickListener {
            showDatePicker(
                resources.getString(R.string.check_in_end_select_hint), binding.checkInEndTime
            ) {calculateRoomPayment(5)}
        }

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

                            if (checkInTypeId == data.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) {
                            binding.checkInType.text = checkInTypeList[position].name

                            checkInTypeId = checkInTypeList[position].id
                            checkInTypeSelect = true

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.realitySingleRoom.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.realitySingleRoom.text.isNullOrBlank()) {
                    showMessage(resources.getString(R.string.single_room_count_input_error))
                    return
                } else {
                    singleRoomCount = binding.realitySingleRoom.text.toString().toInt()

                    calculateRoomPayment(1)
                }
            }
        })

        binding.singleRoomPrice.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.singleRoomPrice.text.isNullOrBlank()) {
                    showMessage(resources.getString(R.string.single_room_price_input_error))
                    return
                }

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

                if (binding.singleRoomPrice.text.matches(regex)) {

                    singleRoomUnitPrice = binding.singleRoomPrice.text.toString().toDouble()

                    calculateRoomPayment(1)
                }
            }
        })

        binding.realityDoubleRoom.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.realityDoubleRoom.text.isNullOrBlank()) {
                    showMessage(resources.getString(R.string.double_room_count_input_error))
                    return
                }

                doubleRoomCount = binding.realityDoubleRoom.text.toString().toInt()

                calculateRoomPayment(2)
            }
        })

        binding.doubleRoomPrice.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.doubleRoomPrice.text.isNullOrBlank()) {
                    showMessage(resources.getString(R.string.double_room_price_input_error))
                    return
                }

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

                if (binding.doubleRoomPrice.text.matches(regex)) {

                    doubleRoomUnitPrice = binding.doubleRoomPrice.text.toString().toDouble()

                    calculateRoomPayment(2)
                }
            }
        })

        binding.realitySuiteRoom.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.realitySuiteRoom.text.isNullOrBlank()) {
                    showMessage(resources.getString(R.string.suite_room_count_input_error))
                    return
                }

                suiteRoomCount = binding.realitySuiteRoom.text.toString().toInt()

                calculateRoomPayment(3)
            }
        })

        binding.suiteRoomPrice.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.suiteRoomPrice.text.isNullOrBlank()) {
                    showMessage(resources.getString(R.string.suite_room_price_input_error))
                    return
                }

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

                if (binding.suiteRoomPrice.text.matches(regex)) {

                    suiteRoomUnitPrice = binding.suiteRoomPrice.text.toString().toDouble()

                    calculateRoomPayment(3)
                }
            }
        })

        binding.realityOtherRoom.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.realityOtherRoom.text.isNullOrBlank()) {
                    showMessage(resources.getString(R.string.other_room_count_input_error))
                    return
                }

                otherRoomCount = binding.realityOtherRoom.text.toString().toInt()

                calculateRoomPayment(4)
            }
        })

        binding.otherRoomPrice.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.otherRoomPrice.text.isNullOrBlank()) {
                    showMessage(resources.getString(R.string.other_room_price_input_error))
                    return
                }

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

                if (binding.otherRoomPrice.text.matches(regex)) {

                    otherRoomUnitPrice = binding.otherRoomPrice.text.toString().toDouble()

                    calculateRoomPayment(4)
                }
            }
        })

        binding.hotelBreakfast.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.hotelBreakfast.text.isNullOrBlank()) {
                    showMessage(resources.getString(R.string.breakfast_input_error))
                    return
                }

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

                if (binding.hotelBreakfast.text.matches(regex)) {
                    breakfastPrice = binding.hotelBreakfast.text.toString().toDouble()

                    calculateTotalPayment()
                }
            }
        })

        binding.hotelBreakfastUnit.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 (breakfastUnitId == 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) {
                            binding.hotelBreakfastUnit.text = currencyList[position].currencyCode

                            breakfastUnitId = currencyList[position].currencyId

                            breakfastRate = currencyList[position].rate

                            calculateTotalPayment()

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.localTax.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.localTax.text.isNullOrBlank()) {
                    showMessage(resources.getString(R.string.local_tax_input_error))
                    return
                }

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

                if (binding.localTax.text.matches(regex)) {
                    localTax = binding.localTax.text.toString().toDouble()

                    calculateTotalPayment()
                }
            }
        })

        binding.localTaxUnit.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 (localTaxUnitId == 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) {
                            binding.localTaxUnit.text = currencyList[position].currencyCode

                            localTaxUnitId = currencyList[position].currencyId

                            localTaxRate = currencyList[position].rate

                            calculateTotalPayment()

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.cityTax.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.cityTax.text.isNullOrBlank()) {
                    showMessage(resources.getString(R.string.city_tax_input_error))
                    return
                }

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

                if (binding.cityTax.text.matches(regex)) {
                    cityTax = binding.cityTax.text.toString().toDouble()

                    calculateTotalPayment()
                }
            }
        })

        binding.cityTaxUnit.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 (cityTaxUnitId == 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.cityTaxUnit.text = currencyList[position].currencyCode

                            cityTaxUnitId = currencyList[position].currencyId

                            cityTaxRate = currencyList[position].rate

                            calculateTotalPayment()

                            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) {
                            binding.paymentWay.text = paymentWayList[position].name

                            paymentWayId = paymentWayList[position].id
                            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
            ) {
                consumeDateSelect = true
            }
        }

        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) {
                            binding.paymentMark.text = OASystem.paymentMark[position].name

                            paymentMarkId = OASystem.paymentMark[position].id
                            paymentMarkSelect = true

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.commit.setOnClickListener {

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

            updateHotelPredetermine.id = paymentId
            updateHotelPredetermine.diId = groupId

            when {
                !customerTypeSelect -> {
                    showMessage(resources.getString(R.string.customer_type_select_hint))
                }

                !bankCardSelect -> {
                    showMessage(resources.getString(R.string.bank_card_select_hint))
                }

                !hasCurrency -> {
                    showMessage(resources.getString(R.string.currency_not_set_hint))
                }

                !websiteSelect -> {
                    showMessage(resources.getString(R.string.website_select_hint))
                }

                binding.hotelConfirmCode.text.isNullOrBlank() -> {
                    showMessage(resources.getString(R.string.hotel_confirm_code_hint))
                }

                binding.locatedCity.text.isNullOrBlank() -> {
                    showMessage(resources.getString(R.string.hotel_located_input_hint))
                }

                binding.hotelName.text.isNullOrBlank() -> {
                    showMessage(resources.getString(R.string.hotel_name_input_hint))
                }

                binding.hotelTel.text.isNullOrBlank() -> {
                    showMessage(resources.getString(R.string.hotel_tel_input_hint))
                }

                binding.hotelLocation.getText().isBlank() -> {
                    showMessage(resources.getString(R.string.hotel_address_input_hint))
                }

                customerSelectList.size == 0 -> {
                    showMessage(resources.getString(R.string.customer_select_hint))
                }

                binding.checkInStartTime.text.isNullOrBlank() -> {
                    showMessage(resources.getString(R.string.check_in_start_select_hint))
                }

                binding.checkInEndTime.text.isNullOrBlank() -> {
                    showMessage(resources.getString(R.string.check_in_end_select_hint))
                }

                !checkInTypeSelect -> {
                    showMessage(resources.getString(R.string.check_in_type_select_hint))
                }

                binding.roomIntroduction.getText().isBlank() -> {
                    showMessage(resources.getString(R.string.room_introduction_hint))
                }

                else -> {
                    updateHotelPredetermine.gtId = customerTypeId

                    updateHotelPredetermine.ctdId = bankCardId
                    updateHotelPredetermine.bankNo = bankNumber
                    updateHotelPredetermine.cardholderName = binding.bankCardOwner.text.toString()

                    updateHotelPredetermine.reservationsWebsite = websiteId

                    updateHotelPredetermine.determineNo = binding.hotelConfirmCode.text.toString()

                    updateHotelPredetermine.city = binding.locatedCity.text.toString()

                    updateHotelPredetermine.hotelName = binding.hotelName.text.toString()

                    updateHotelPredetermine.hotelTel = binding.hotelTel.text.toString()

                    updateHotelPredetermine.hotelAddress = binding.hotelLocation.getText()

                    var i = 0
                    var guestName = ""
                    while (i < customerSelectList.size) {

                        guestName += customerSelectList[i].id
                        i += 1

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

                    updateHotelPredetermine.guestName = guestName

                    updateHotelPredetermine.checkInDate = binding.checkInStartTime.text.toString()

                    updateHotelPredetermine.checkOutDate = binding.checkInEndTime.text.toString()

                    updateHotelPredetermine.checkType = checkInTypeId

                    updateHotelPredetermine.roomExplanation = binding.roomIntroduction.getText()

                    updateHotelPredetermine.hotelRemark = binding.hotelNotes.getText()

                    updateHotelPredetermine.singleRoomCount = singleRoomCount

                    updateHotelPredetermine.singleRoomPrice = singleRoomUnitPrice

                    updateHotelPredetermine.doubleRoomCount = doubleRoomCount

                    updateHotelPredetermine.doubleRoomPrice = doubleRoomUnitPrice

                    updateHotelPredetermine.suiteRoomCount = suiteRoomCount

                    updateHotelPredetermine.suiteRoomPrice = suiteRoomUnitPrice

                    updateHotelPredetermine.otherRoomCount = otherRoomCount

                    updateHotelPredetermine.otherRoomPrice = otherRoomUnitPrice

                    updateHotelPredetermine.cardPrice = creditPayment

                    updateHotelPredetermine.governmentRent = localTax

                    updateHotelPredetermine.governmentRentCurrency = localTaxUnitId

                    updateHotelPredetermine.cityTax = cityTax

                    updateHotelPredetermine.cityTaxCurrency = cityTaxUnitId

                    updateHotelPredetermine.breakfastPrice = breakfastPrice

                    updateHotelPredetermine.breakfastCurrency = breakfastUnitId

                    when (binding.breakfastOpPay.checkedRadioButtonId) {
                        binding.yes.id -> {
                            updateHotelPredetermine.isOpPay = 1
                        }

                        binding.no.id -> {
                            updateHotelPredetermine.isOpPay = 0
                        }
                    }

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

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

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

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

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

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

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

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

                        updateHotelPredetermine.payMoney = sumPayment

                        updateHotelPredetermine.paymentCurrency = sumUnitCurrencyId

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

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

                        binding.paymentApplyNotes.getText().apply {
                            if (isNotBlank()) {
                                updateHotelPredetermine.ccpRemark = this
                            }
                        }
                    } else {
                        showMessage(resources.getString(R.string.payment_way_hint))
                    }

                    updateHotelPredetermine()
                }
            }
        }
    }

    private fun getSelectorResource() {
        apiService.getHotelPredetermineResource(HotelPredetermineResourceRequest(groupId))
            .enqueue(object : Callback<HotelPredetermineResourceResponse> {
                override fun onResponse(
                    call: Call<HotelPredetermineResourceResponse>,
                    response: Response<HotelPredetermineResourceResponse>
                ) {
                    val resourceResponse = response.body()

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

                            for (item in resourceResponse.data.guestType) {
                                guestType.add(item)
                            }

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

                            for (item in resourceResponse.data.currencyList) {
                                currencyList.add(item)
                            }

                            for (item in resourceResponse.data.bankCard) {
                                cardList.add(item)
                            }

                            for (item in resourceResponse.data.bookingWebsite) {
                                websiteList.add(item)
                            }

                            for (item in resourceResponse.data.checkPerson) {
                                checkInTypeList.add(item)
                            }

                            for (item in resourceResponse.data.guestName) {
                                customerList.add(item)
                            }

                            if (fromList) {
                                getHotelPredetermineDetail()
                            }

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

                override fun onFailure(
                    call: Call<HotelPredetermineResourceResponse>, t: Throwable
                ) {
                    showErrorInfo(R.string.base_resource_data_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) {
                customerList.removeAt(position)
                binding.customerList.adapter!!.notifyItemRemoved(position)
                binding.customerList.adapter!!.notifyItemRangeChanged(position, customerList.size)
            }
        }
    }

    private fun updateHotelPredetermine() {

        binding.commit.setButtonStatus(1)

        apiService.updateHotelPredetermine(updateHotelPredetermine)
            .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 (fromList) {
                                showMessage(resources.getString(R.string.update_success))
                            } else {
                                showMessage(resources.getString(R.string.insert_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 getHotelPredetermineDetail() {
        apiService.getHotelPredetermineDetail(GetHotelPredetermineDetailRequest(groupId, paymentId))
            .enqueue(object : Callback<GetHotelPredetermineDetailResponse> {
                override fun onResponse(
                    call: Call<GetHotelPredetermineDetailResponse>,
                    response: Response<GetHotelPredetermineDetailResponse>
                ) {
                    val detailResponse = response.body()

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

                            detailResponse.data.apply {
                                run {
                                    for (item in guestType) {
                                        if (item.id == gtId) {
                                            binding.customerType.text = item.name

                                            customerTypeId = item.id
                                            customerTypeSelect = true

                                            return@run
                                        }
                                    }
                                }

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

                                            binding.singleRoomUnit.text = item.currency
                                            binding.doubleRoomUnit.text = item.currency
                                            binding.suiteRoomUnit.text = item.currency
                                            binding.otherRoomUnit.text = item.currency

                                            bankNumber = bankNo
                                            bankCardCurrencyStr = item.currency

                                            bankCardId = item.id
                                            bankCardSelect = true

                                            return@run
                                        }
                                    }
                                }

                                run {
                                    for (item in currencyList) {
                                        if (item.currencyCode == bankCardCurrencyStr) {

                                            bankCardCurrencyId = item.currencyId
                                            bankCardRate = item.rate

                                            hasCurrency = true

                                            return@run
                                        }
                                    }
                                }

                                binding.checkInCode.text = checkNumber

                                run {
                                    for (item in websiteList) {
                                        if (item.id == reservationsWebsite) {
                                            binding.predetermineWebsite.text = item.name

                                            websiteId = item.id
                                            websiteSelect = true

                                            return@run
                                        }
                                    }
                                }

                                binding.hotelConfirmCode.setText(determineNo)

                                binding.locatedCity.setText(city)

                                binding.hotelName.setText(hotelName)

                                binding.hotelTel.setText(hotelTel)

                                binding.hotelLocation.setText(hotelAddress)

                                val customerSelectedId = guestName.split(",")

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

                                initCustomerList()

                                binding.checkInStartTime.text = checkInDate

                                binding.checkInEndTime.text = checkOutDate

                                val days = if(binding.checkInStartTime.text.isNotBlank() && binding.checkInEndTime.text.isNotBlank()) {

                                    val startTime = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).parse(binding.checkInStartTime.text.toString())
                                    val endTime = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).parse(binding.checkInEndTime.text.toString())

                                    getGapCount(startTime!!, endTime!!)

                                } else {
                                    0
                                }

                                run {
                                    for (item in checkInTypeList) {
                                        if (item.id == checkType) {
                                            binding.checkInType.text = item.name

                                            checkInTypeId = item.id
                                            checkInTypeSelect = true

                                            return@run
                                        }
                                    }
                                }

                                binding.roomIntroduction.setText(roomExplanation)

                                binding.hotelNotes.setText(hotelRemark)

                                binding.realitySingleRoom.setText(singleRoomCount.toString())

                                this@AddHotelPredetermineActivity.singleRoomCount = singleRoomCount

                                binding.singleRoomPrice.setText(singleRoomPrice.toString())

                                singleRoomUnitPrice = singleRoomPrice

                                this@AddHotelPredetermineActivity.singleRoomPrice = singleRoomUnitPrice * singleRoomCount * days

                                binding.realityDoubleRoom.setText(doubleRoomCount.toString())

                                this@AddHotelPredetermineActivity.doubleRoomCount = doubleRoomCount

                                binding.doubleRoomPrice.setText(doubleRoomPrice.toString())

                                doubleRoomUnitPrice = doubleRoomPrice

                                this@AddHotelPredetermineActivity.doubleRoomPrice = doubleRoomUnitPrice * doubleRoomCount * days

                                binding.realitySuiteRoom.setText(suiteRoomCount.toString())

                                this@AddHotelPredetermineActivity.suiteRoomCount = suiteRoomCount

                                binding.suiteRoomPrice.setText(suiteRoomPrice.toString())

                                suiteRoomUnitPrice = suiteRoomPrice

                                this@AddHotelPredetermineActivity.suiteRoomPrice = suiteRoomUnitPrice * suiteRoomCount * days

                                binding.realityOtherRoom.setText(otherRoomCount.toString())

                                this@AddHotelPredetermineActivity.otherRoomCount = otherRoomCount

                                binding.otherRoomPrice.setText(otherRoomPrice.toString())

                                otherRoomUnitPrice = otherRoomPrice

                                this@AddHotelPredetermineActivity.otherRoomPrice = otherRoomPrice * otherRoomCount * days

                                binding.creditCardPayment.text = cardPrice.toString()

                                this@AddHotelPredetermineActivity.creditPayment = cardPrice

                                binding.hotelBreakfast.setText(breakfastPrice.toString())

                                this@AddHotelPredetermineActivity.breakfastPrice = breakfastPrice

                                run {
                                    for (item in currencyList) {
                                        if (item.currencyId == breakfastCurrency) {
                                            binding.hotelBreakfastUnit.text = item.currencyCode

                                            breakfastUnitId = breakfastCurrency

                                            isBreakfastCurrency =
                                                breakfastUnitId == bankCardCurrencyId

                                            breakfastRate = item.rate

                                            return@run
                                        }
                                    }
                                }

                                when (isOpPay) {
                                    0 -> {
                                        binding.no.isChecked = true
                                    }

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

                                binding.localTax.setText(governmentRent.toString())

                                this@AddHotelPredetermineActivity.localTax = governmentRent

                                run {
                                    for (item in currencyList) {
                                        if (item.currencyId == governmentRentCurrency) {
                                            binding.localTaxUnit.text = item.currencyCode

                                            localTaxUnitId = item.currencyId

                                            isLocalTaxCurrency =
                                                localTaxUnitId == bankCardCurrencyId

                                            localTaxRate = item.rate

                                            return@run
                                        }
                                    }
                                }

                                binding.cityTax.setText(cityTax.toString())

                                this@AddHotelPredetermineActivity.cityTax = cityTax

                                run {
                                    for (item in currencyList) {
                                        if (item.currencyId == cityTaxCurrency) {
                                            binding.cityTaxUnit.text = item.currencyCode

                                            cityTaxUnitId = item.currencyId

                                            isCityTaxCurrency = cityTaxUnitId == bankCardCurrencyId

                                            cityTaxRate = item.rate

                                            return@run
                                        }
                                    }
                                }
                            }

                            detailResponse.data.apply {

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

                                binding.consumeWay.setText(consumptionPatterns)

                                if (consumptionDate.isNotBlank()) {
                                    binding.consumeDate.text = consumptionDate

                                    consumeDateSelect = true
                                }

                                binding.paymentSum.text = payMoney.toString()

                                sumUnitCurrencyId = paymentCurrency

                                run {
                                    for (item in currencyList) {
                                        if (paymentCurrency == item.currencyId) {
                                            binding.sumUnit.text = item.currencyCode

                                            sumUnitCurrencyId = item.currencyId

                                            return@run
                                        }
                                    }
                                }

                                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

                                        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)

                                if (orbitalPrivateTransfer != -1) {
                                    binding.paymentMark.text =
                                        OASystem.paymentMark[orbitalPrivateTransfer].name
                                    paymentMarkId = orbitalPrivateTransfer
                                    paymentMarkSelect = true
                                }

                                if (ccpRemark.isNotBlank()) {
                                    binding.paymentApplyNotes.setText(ccpRemark)
                                }
                            }

                            initEvents()

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

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

    private fun calculateRoomPayment(type: Int) {

        val days = if(binding.checkInStartTime.text.isNotBlank() && binding.checkInEndTime.text.isNotBlank()) {

            val startTime = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).parse(binding.checkInStartTime.text.toString())
            val endTime = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).parse(binding.checkInEndTime.text.toString())

            getGapCount(startTime!!, endTime!!)

        } else {
            0
        }

        when (type) {
            1 -> {
                singleRoomPricePre = singleRoomPrice

                singleRoomPrice = singleRoomUnitPrice * singleRoomCount * days

                creditPayment -= singleRoomPricePre - singleRoomPrice
            }

            2 -> {
                doubleRoomPricePre = doubleRoomPrice

                doubleRoomPrice = doubleRoomUnitPrice * doubleRoomCount * days

                creditPayment -= doubleRoomPricePre - doubleRoomPrice
            }

            3 -> {
                suiteRoomPricePre = suiteRoomPrice

                suiteRoomPrice = suiteRoomUnitPrice * suiteRoomCount * days

                creditPayment -= suiteRoomPricePre - suiteRoomPrice
            }

            4 -> {
                otherRoomPricePre = otherRoomPrice

                otherRoomPrice = otherRoomUnitPrice * otherRoomCount * days

                creditPayment -= otherRoomPricePre - otherRoomPrice
            }

            5 -> {
                singleRoomPricePre = singleRoomPrice

                singleRoomPrice = singleRoomUnitPrice * singleRoomCount * days

                creditPayment -= singleRoomPricePre - singleRoomPrice

                doubleRoomPricePre = doubleRoomPrice

                doubleRoomPrice = doubleRoomUnitPrice * doubleRoomCount * days

                creditPayment -= doubleRoomPricePre - doubleRoomPrice

                suiteRoomPricePre = suiteRoomPrice

                suiteRoomPrice = suiteRoomUnitPrice * suiteRoomCount * days

                creditPayment -= suiteRoomPricePre - suiteRoomPrice

                otherRoomPricePre = otherRoomPrice

                otherRoomPrice = otherRoomUnitPrice * otherRoomCount * days

                creditPayment -= otherRoomPricePre - otherRoomPrice
            }
        }

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

        binding.creditCardPayment.text = creditPayment.toString()

        calculateTotalPayment()
    }

    private fun calculateTotalPayment() {

        isBreakfastCurrency = breakfastUnitId == bankCardCurrencyId

        isLocalTaxCurrency = localTaxUnitId == bankCardCurrencyId

        isCityTaxCurrency = cityTaxUnitId == bankCardCurrencyId

        if (isBreakfastCurrency && isLocalTaxCurrency && isCityTaxCurrency) {
            sumPayment = creditPayment + breakfastPrice + localTax + cityTax

            sumUnitCurrencyId = bankCardCurrencyId

            sumUnitCurrencyStr = bankCardCurrencyStr

        } else {
            sumPayment =
                creditPayment * bankCardRate + breakfastPrice * breakfastRate + localTax * localTaxRate + cityTax * cityTaxRate

            run {
                for (item in currencyList) {
                    if (item.currencyCode == "CNY") {
                        sumUnitCurrencyId = item.currencyId
                        sumUnitCurrencyStr = item.currencyCode
                        return@run
                    }
                }
            }
        }

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

        binding.paymentSum.text = sumPayment.toString()

        binding.sumUnit.text = sumUnitCurrencyStr
    }

    private fun getGapCount(startData: Date, endDate: Date): Int {
        //开始时间
        val startTime = Calendar.getInstance()
        startTime.time = startData
        startTime.set(Calendar.HOUR_OF_DAY, 0)
        startTime.set(Calendar.MINUTE, 0)
        startTime.set(Calendar.SECOND, 0)
        startTime.set(Calendar.MILLISECOND, 0)

        //结束时间
        val endTime = Calendar.getInstance()
        endTime.time = endDate
        endTime.set(Calendar.HOUR_OF_DAY, 0)
        endTime.set(Calendar.MINUTE, 0)
        endTime.set(Calendar.SECOND, 0)
        endTime.set(Calendar.MILLISECOND, 0)

        return (((endTime.time.time - startTime.time.time) / (1000 * 60 * 60 * 24)).toInt())
    }

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