package com.pan_american.android.ui.group_airplane_ticket.airplane_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.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.ListAdapter
import com.pan_american.android.data.model.common.entity.CardPaymentResource
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_airplane_ticket.airplane_payment_insert.entity.AirplaneCost
import com.pan_american.android.data.model.group_airplane_ticket.airplane_payment_insert.entity.AirplaneItinerary
import com.pan_american.android.data.model.group_airplane_ticket.airplane_payment_insert.entity.AirplaneTicketResource
import com.pan_american.android.data.model.group_airplane_ticket.airplane_payment_insert.network.AirplaneCostDetailResponse
import com.pan_american.android.data.model.group_airplane_ticket.airplane_payment_insert.network.AirplaneTicketDetailRequest
import com.pan_american.android.data.model.group_airplane_ticket.airplane_payment_insert.network.AirplaneTicketDetailResponse
import com.pan_american.android.data.model.group_airplane_ticket.airplane_payment_insert.network.AirplaneTicketSelectorResourceRequest
import com.pan_american.android.data.model.group_airplane_ticket.airplane_payment_insert.network.AirplaneTicketSelectorResourceResponse
import com.pan_american.android.data.model.group_airplane_ticket.airplane_payment_insert.network.UpdateAirplaneTicketRequest
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.ActivityAddAirplaneTicketBinding
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
import java.util.Calendar

class AddAirplaneTicketActivity : BaseActivity<ActivityAddAirplaneTicketBinding>() {

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

    private var berthItemId = 0

    private var berthSelect = false

    private var unitPriceCorrect = false

    private var priceUnitId = -1

    private var priceUnitSelect = false

    private var flightSketch = ArrayList<String>()

    private var flightCity = ArrayList<String>()

    private var flightDateAndTime = ArrayList<String>()

    private var customerSelector = ArrayList<Selector>()

    private var customerList = ArrayList<Selector>()

    private var paymentWayList = ArrayList<Selector>()

    private var paymentWayId = 0

    private var paymentWaySelect = false

    private var cardTypeList = ArrayList<Selector>()

    private var cardTypeId = 0

    private var bankNo = ""

    private var cardTypeSelect = false

    private var paymentMarkId = 0

    private var paymentMarkSelect = false

    private var airTicketAgentsList = ArrayList<Selector>()

    private var airplaneTicketResource = AirplaneTicketResource()

    private var cardPaymentResource = CardPaymentResource()

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

    private var isAuditGM = -1

    private var airplaneCostInit = false

    private var airplaneCostCurrency = ""

    private var airplaneCostExchangeRate = 0.0

    private var airplaneCostList = ArrayList<AirplaneCost>()

    private var airplaneItineraryList = ArrayList<AirplaneItinerary>()

    override fun getViewBinding() = ActivityAddAirplaneTicketBinding.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")

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

        initTitle()

        getSelectorResource()
    }

    override fun initTitle() {

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

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

            backButton.setOnClickListener {
                back()
            }

            rightTextField.setOnClickListener {

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

                showPopupWindow {

                    val currencyAbbr = airplaneCostPopView.findViewById<TextView>(R.id.currency_abbr)
                    val exchangeRate = airplaneCostPopView.findViewById<TextView>(R.id.exchange_rate)
                    val airplaneCostTable = airplaneCostPopView.findViewById<SmartTable<AirplaneCost>>(R.id.airplane_cost_table)
                    val airplaneItineraryTable = airplaneCostPopView.findViewById<SmartTable<AirplaneItinerary>>(R.id.airplane_itinerary_table)

                    airplaneCostTable.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))
                    }

                    airplaneItineraryTable.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 (!airplaneCostInit) {
                        apiService.getAirplaneCostData(GroupCostDataRequest(groupId, OASystem.C_TABLE_AIRPLANE_TICKET)).enqueue(object : Callback<AirplaneCostDetailResponse> {
                            override fun onResponse(
                                call: Call<AirplaneCostDetailResponse>,
                                response: Response<AirplaneCostDetailResponse>
                            ) {

                                val costResponse = response.body()

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

                                        airplaneCostCurrency = costResponse.data.modulePromptInfos[0].currencyCode
                                        airplaneCostExchangeRate = costResponse.data.modulePromptInfos[0].rate

                                        airplaneCostList = costResponse.data.modulePromptInfos[0].data.airFeeData
                                        airplaneItineraryList = costResponse.data.modulePromptInfos[0].data.airInitData

                                        currencyAbbr.text = airplaneCostCurrency
                                        exchangeRate.text = airplaneCostExchangeRate.toString()

                                        airplaneCostTable.setData(airplaneCostList)
                                        airplaneItineraryTable.setData(airplaneItineraryList)

                                        airplaneCostInit = true

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

                            override fun onFailure(call: Call<AirplaneCostDetailResponse>, t: Throwable) {
                                showErrorInfo(R.string.airplane_cost_get_failed)
                            }
                        })
                    } else {
                        currencyAbbr.text = airplaneCostCurrency
                        exchangeRate.text = airplaneCostExchangeRate.toString()

                        airplaneCostTable.setData(airplaneCostList)
                        airplaneItineraryTable.setData(airplaneItineraryList)
                    }

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

    override fun initViews() {

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

        if (fromList) {

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

            if (!canBeEdit()) {
                binding.apply {
                    berthType.isEnabled = false
                    unitPrice.isEnabled = false
                    priceUnit.isEnabled = false
                    ticketIdentifier.isEnabled = false
                    ticketCode.isEnabled = false
                    flightDescriptionIdentify.visibility = View.GONE
                    flightDescription.isEnabled(false)
                    addCustomer.visibility = View.GONE
                    isCheckInYes.isEnabled = false
                    isCheckInNo.isEnabled = false
                    isSelectSeatYes.isEnabled = false
                    isSelectSeatNo.isEnabled = false
                    isBuyBaggageYes.isEnabled = false
                    isBuyBaggageNo.isEnabled = false
                    isBagHandleYes.isEnabled = false
                    isBagHandleNo.isEnabled = false
                    isTrainYes.isEnabled = false
                    isTrainNo.isEnabled = false
                    paymentSketch.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
                    airplaneTicketAgents.isEnabled = false
                    paymentApplyNotes.isEnabled(false)

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

            getAirplaneTicketDetail()

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

    override fun initEvents() {

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

                            if (berthItemId == 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) {
                            berthItemId = berthList[position].id
                            binding.berthType.text = berthList[position].name
                            berthSelect = true

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.unitPrice.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 (p0.toString().isNotBlank()) {
                    binding.paymentSum.text = (binding.unitPrice.text.trim().toString()
                        .toDouble() * customerList.size).toString()
                    unitPriceCorrect = true
                } else {
                    showMessage(resources.getString(R.string.airplane_price_input_hint))
                    binding.paymentSum.text = ""
                }
            }
        })

        binding.priceUnit.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setData(OASystem.currency)
                    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 (priceUnitId == 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) {
                            priceUnitId = OASystem.currency[position].currencyId
                            binding.priceUnit.text = OASystem.currency[position].currencyCode
                            binding.sumUnit.text = OASystem.currency[position].currencyCode
                            priceUnitSelect = true

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.flightDescriptionIdentify.setOnClickListener {

            flightSketch.clear()
            flightDateAndTime.clear()
            flightCity.clear()

            val flightDescription = binding.flightDescription.getText()
            if (flightDescription.isBlank()) {
                showMessage(resources.getString(R.string.flight_description_input_hint))
                return@setOnClickListener
            }
            val descriptionItem = flightDescription.split("\n")

//            for (item in descriptionItem) {
//                Log.e("item", item)
//            }

            var count = 1

            for (item in descriptionItem) {
                var i = 0
                for (character in item.toCharArray()) {
                    if (character.isLetter()) {
                        //解决EditText自动换行后部分空格字符串无法分割的问题
                        val flightInfo =
                            item.substring(i, item.length).replace(Regex("\\s+"), "\u00A0")
                                .split("\u00A0")
//                        for (info in flightInfo) {
//                            Log.e("info", info)
//                        }
                        if (flightInfo.size < 9) {
                            showMessage(
                                String.format(
                                    resources.getString(R.string.flight_description_format_error),
                                    count
                                )
                            )
                            return@setOnClickListener
                        } else {
                            flightSketch.add(flightInfo[0])
                            flightCity.add(flightInfo[3])

                            var timeStamp = ""
                            if (flightInfo[2].length != 7) {
                                showMessage(
                                    String.format(
                                        resources.getString(R.string.flight_description_date_format_error),
                                        count
                                    )
                                )
                                return@setOnClickListener
                            }
                            when (flightInfo[2].substring(4, 7)) {
                                "JAN" -> {
                                    timeStamp += "01"
                                }

                                "FEB" -> {
                                    timeStamp += "02"
                                }

                                "MAR" -> {
                                    timeStamp += "03"
                                }

                                "APR" -> {
                                    timeStamp += "04"
                                }

                                "MAY" -> {
                                    timeStamp += "05"
                                }

                                "JUN" -> {
                                    timeStamp += "06"
                                }

                                "JUL" -> {
                                    timeStamp += "07"
                                }

                                "AUG" -> {
                                    timeStamp += "08"
                                }

                                "SEP" -> {
                                    timeStamp += "09"
                                }

                                "OCT" -> {
                                    timeStamp += "10"
                                }

                                "NOV" -> {
                                    timeStamp += "11"
                                }

                                "DEC" -> {
                                    timeStamp += "12"
                                }

                                else -> {
                                    showMessage(
                                        String.format(
                                            resources.getString(R.string.flight_description_month_format_error),
                                            count
                                        )
                                    )
                                    return@setOnClickListener
                                }
                            }

                            timeStamp += flightInfo[2].substring(2, 4)

                            if (flightInfo[5].length != 4) {
                                showMessage(
                                    String.format(
                                        resources.getString(R.string.flight_description_time_format_error),
                                        count
                                    )
                                )
                                return@setOnClickListener
                            }

                            timeStamp += flightInfo[5]

                            when (flightInfo[2].substring(0, 2)) {
                                "MO" -> {
                                    timeStamp += "周一"
                                }

                                "TU" -> {
                                    timeStamp += "周二"
                                }

                                "WE" -> {
                                    timeStamp += "周三"
                                }

                                "TH" -> {
                                    timeStamp += "周四"
                                }

                                "FR" -> {
                                    timeStamp += "周五"
                                }

                                "SA" -> {
                                    timeStamp += "周六"
                                }

                                "SU" -> {
                                    timeStamp += "周日"
                                }

                                else -> {
                                    showMessage(
                                        String.format(
                                            resources.getString(R.string.flight_description_week_format_error),
                                            count
                                        )
                                    )
                                    return@setOnClickListener
                                }
                            }
                            flightDateAndTime.add(timeStamp)

                            break
                        }
                    } else {
                        i += 1
                    }
                }
                ++count
            }

            var sketchAll = ""
            var sketchCount = 1

            flightSketch.forEach {
                sketchAll += it
                if (sketchCount < flightSketch.size) {
                    sketchAll += "/"
                }
                ++sketchCount
            }
            binding.flightSketch.text = sketchAll

            var flightCityAll = ""
            var flightCityCount = 1

            flightCity.forEach {
                if (it.length < 6) {
                    showMessage(
                        String.format(
                            resources.getString(R.string.flight_description_city_format_error),
                            flightCityCount
                        )
                    )
                    return@setOnClickListener
                }
                flightCityAll += String.format("%s-%s", it.substring(0, 3), it.substring(3, 6))
                if (flightCityCount < flightCity.size) {
                    flightCityAll += "/"
                }
                ++flightCityCount
            }
            binding.flightCity.text = flightCityAll

            var minTimeStamp = flightDateAndTime[0].substring(0, 8).toInt()
            var timeStampCount = 0
            var minTimeStampIndex = 0

            flightDateAndTime.forEach {
                if (minTimeStamp > it.substring(0, 8).toInt()) {
                    minTimeStamp = it.substring(0, 8).toInt()
                    minTimeStampIndex = timeStampCount
                }
                ++timeStampCount
            }

            val calendar = Calendar.getInstance()

            var flightDate = String.format(
                resources.getString(R.string.date_format),
                calendar.get(Calendar.YEAR),
                flightDateAndTime[minTimeStampIndex].substring(0, 2).toInt(),
                flightDateAndTime[minTimeStampIndex].substring(2, 4).toInt()
            )

            flightDate = String.format(
                resources.getString(R.string.currency_name_code_format),
                flightDate,
                flightDateAndTime[minTimeStampIndex].substring(8, 10)
            )

            binding.flightDate.text = flightDate

            val flightTime = flightDateAndTime[minTimeStampIndex].substring(
                4, 6
            ) + ":" + flightDateAndTime[minTimeStampIndex].substring(6, 8)

            binding.flightTime.text = flightTime
        }

        binding.addCustomer.setOnClickListener {
            if (berthSelect) {
                showSelector {
                    val adapter = ListAdapter.Builder<Selector>().apply {
                        setData(customerSelector)
                        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 customerList) {
                                    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 customerList) {
                                    if (customerSelector[position].id == item.id) {
                                        showMessage(resources.getString(R.string.customer_selected))
                                        popupWindow.dismiss()
                                        return
                                    }
                                }

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

                                if (unitPriceCorrect) {
                                    binding.paymentSum.text = String.format(
                                        resources.getString(R.string.decimal_format),
                                        binding.unitPrice.text.trim().toString()
                                            .toDouble() * customerList.size
                                    )
                                } else {
                                    showMessage(resources.getString(R.string.airplane_price_input_format_alert))
                                }

                                popupWindow.dismiss()
                            }
                        }
                }
            } else {
                showMessage(resources.getString(R.string.berth_type_select_alert))
            }
        }

        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.airplaneTicketAgents.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setData(airTicketAgentsList)
                    setLayoutId(R.layout.item_selector)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text = data.name

                            if (binding.airplaneTicketAgents.text == data.name.trim()) {
                                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.payee.setText(airTicketAgentsList[position].name.trim())
                            binding.airplaneTicketAgents.text =
                                airTicketAgentsList[position].name.trim()

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.commit.setOnClickListener {

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

            airplaneTicketResource.diId = groupId
            cardPaymentResource.diId = groupId

            if (!berthSelect) {
                showMessage(resources.getString(R.string.berth_type_select_alert))
                return@setOnClickListener
            } else {
                airplaneTicketResource.cType = berthItemId
            }

            if (binding.unitPrice.text.trim().isBlank()) {
                showMessage(resources.getString(R.string.airplane_price_input_hint))
                return@setOnClickListener
            } else {
                if (!binding.unitPrice.text.toString().matches(regex)) {
                    showMessage(resources.getString(R.string.airplane_price_input_format_alert))
                    unitPriceCorrect = false
                    return@setOnClickListener
                } else {
                    airplaneTicketResource.prePrice = binding.unitPrice.text.toString().toDouble()
                    unitPriceCorrect = true
                }
            }

            if (!priceUnitSelect) {
                showMessage(resources.getString(R.string.payment_currency_hint))
                return@setOnClickListener
            } else {
                airplaneTicketResource.preCurrency = priceUnitId
                airplaneTicketResource.currency = priceUnitId
            }

            if (binding.ticketIdentifier.text.isNotBlank()) {
                airplaneTicketResource.ticketNumber =
                    binding.ticketIdentifier.text.trim().toString()
            }

            if (binding.ticketCode.text.isNotBlank()) {
                airplaneTicketResource.ticketCode = binding.ticketCode.text.trim().toString()
            }

            if (binding.flightDescription.getText()
                    .isBlank() || binding.flightSketch.text.isBlank() || binding.flightCity.text.isBlank()
            ) {
                showMessage(resources.getString(R.string.flight_description_input_hint))
                return@setOnClickListener
            } else {
                airplaneTicketResource.flightsDescription = binding.flightDescription.getText()
                airplaneTicketResource.flightsCode =
                    binding.flightSketch.text.toString().replace(" ", "")
                airplaneTicketResource.flightsCity =
                    binding.flightCity.text.toString().replace(" ", "")
                airplaneTicketResource.flightsDate =
                    binding.flightDate.text.toString().substring(0, 10)
                airplaneTicketResource.flightsTime = binding.flightTime.text.toString()
            }

            if (customerList.size == 0) {
                showMessage(resources.getString(R.string.customer_select_hint))
                return@setOnClickListener
            } else {
                var customerName = ""
                var i = 1
                customerList.forEach {
                    customerName += it.id
                    if (i < customerList.size) {
                        customerName += ","
                    }
                    ++i
                }
                airplaneTicketResource.clientName = customerName
                airplaneTicketResource.clientNum = customerList.size
            }

            when (binding.isCheckIn.checkedRadioButtonId) {
                binding.isCheckInYes.id -> {
                    airplaneTicketResource.isCheckIn = 1
                }

                binding.isCheckInNo.id -> {
                    airplaneTicketResource.isCheckIn = 0
                }
            }

            when (binding.isSelectSeat.checkedRadioButtonId) {
                binding.isSelectSeatYes.id -> {
                    airplaneTicketResource.isSetSeat = 1
                }

                binding.isSelectSeatNo.id -> {
                    airplaneTicketResource.isSetSeat = 0
                }
            }

            when (binding.isBuyBaggage.checkedRadioButtonId) {
                binding.isBuyBaggageYes.id -> {
                    airplaneTicketResource.isPackage = 1
                }

                binding.isBuyBaggageNo.id -> {
                    airplaneTicketResource.isPackage = 0
                }
            }

            when (binding.isBagHandle.checkedRadioButtonId) {
                binding.isBagHandleYes.id -> {
                    airplaneTicketResource.isBagHandle = 1
                }

                binding.isBagHandleNo.id -> {
                    airplaneTicketResource.isBagHandle = 0
                }
            }

            when (binding.isTrain.checkedRadioButtonId) {
                binding.isTrainYes.id -> {
                    airplaneTicketResource.isTrain = 1
                }

                binding.isTrainNo.id -> {
                    airplaneTicketResource.isTrain = 0
                }
            }

            if (binding.paymentSketch.getText().isNotBlank()) {
                airplaneTicketResource.priceDescription = binding.paymentSketch.getText()
            }

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

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

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

            if (binding.consumeDate.text.isNotBlank()) {
                cardPaymentResource.consumptionDate = binding.consumeDate.text.toString()
            }

            if (!unitPriceCorrect) {
                showMessage(resources.getString(R.string.airplane_price_input_format_alert))
                return@setOnClickListener
            } else {
                airplaneTicketResource.price = binding.paymentSum.text.toString().toDouble()
                cardPaymentResource.payMoney = binding.paymentSum.text.toString().toDouble()
            }

            cardPaymentResource.paymentCurrency = priceUnitId

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

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

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

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

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

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

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

            if (binding.payee.getText().isBlank()) {
                showMessage(resources.getString(R.string.payee_hint))
                return@setOnClickListener
            } else {
                cardPaymentResource.payee = binding.payee.getText().trim()
            }

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

            if (binding.paymentApplyNotes.getText().trim().isNotBlank()) {
                cardPaymentResource.remark = binding.paymentApplyNotes.getText()
            }

            if (fromList) {
                updateAirplaneTicket(2)
            } else {
                updateAirplaneTicket(1)
            }
        }
    }

    private fun getSelectorResource() {
        apiService.getAirplaneTicketSelectorResource(AirplaneTicketSelectorResourceRequest(groupId))
            .enqueue(object : Callback<AirplaneTicketSelectorResourceResponse> {
                override fun onResponse(
                    call: Call<AirplaneTicketSelectorResourceResponse>,
                    response: Response<AirplaneTicketSelectorResourceResponse>
                ) {
                    val selectorResourceResponse = response.body()
                    if (selectorResourceResponse != null) {
                        if (selectorResourceResponse.code == 200) {
                            for (item in selectorResourceResponse.data.ticketClass) {
                                berthList.add(item)
                            }
                            for (item in selectorResourceResponse.data.payment) {
                                paymentWayList.add(item)
                            }
                            for (item in selectorResourceResponse.data.cardType) {
                                cardTypeList.add(item)
                            }
                            for (item in selectorResourceResponse.data.clientArr) {
                                customerSelector.add(item)
                            }

                            val agentItem = Selector()
                            agentItem.id = 0
                            agentItem.name = "无"

                            airTicketAgentsList.add(agentItem)

                            for (item in selectorResourceResponse.data.airTicketAgents) {
                                airTicketAgentsList.add(item)
                            }

                            initViews()
                            initEvents()
                        } else {
                            showMessage(selectorResourceResponse.msg)
                        }
                    }
                }

                override fun onFailure(
                    call: Call<AirplaneTicketSelectorResourceResponse>, 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(customerList)
            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 - position)

                binding.paymentSum.text = (binding.unitPrice.text.trim().toString()
                    .toDouble() * customerList.size).toString()
            }
        }
    }

    private fun updateAirplaneTicket(status: Int) {

        binding.commit.setButtonStatus(CommitButton.STATUS_IN_COMMITING)

        val updateAirplaneTicketRequest =
            UpdateAirplaneTicketRequest(status, airplaneTicketResource, cardPaymentResource)

        apiService.updateAirplaneTicket(updateAirplaneTicketRequest)
            .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(CommitButton.STATUS_COMMITTED)

                            showMessage(baseResponse.msg)
                        }
                    }
                }

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

                    binding.commit.setButtonStatus(CommitButton.STATUS_COMMITTED)

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

    private fun getAirplaneTicketDetail() {
        apiService.getAirplaneTicketDetail(AirplaneTicketDetailRequest(paymentId))
            .enqueue(object : Callback<AirplaneTicketDetailResponse> {
                override fun onResponse(
                    call: Call<AirplaneTicketDetailResponse>,
                    response: Response<AirplaneTicketDetailResponse>
                ) {
                    val detailResponse = response.body()

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

                            airplaneTicketResource = detailResponse.data.airTicket
                            cardPaymentResource = detailResponse.data.creditCard

                            for (item in berthList) {
                                if (item.id == airplaneTicketResource.cType) {
                                    binding.berthType.text = item.name
                                    berthItemId = airplaneTicketResource.cType
                                    berthSelect = true
                                }
                            }

                            binding.unitPrice.setText(airplaneTicketResource.prePrice.toString())
                            unitPriceCorrect = true

                            run {
                                for (item in OASystem.currency) {
                                    if (airplaneTicketResource.preCurrency == item.currencyId) {
                                        binding.priceUnit.text = item.currencyCode
                                        priceUnitId = airplaneTicketResource.preCurrency
                                        priceUnitSelect = true

                                        return@run
                                    }
                                }
                            }

                            if (airplaneTicketResource.ticketNumber.isNotBlank()) {
                                binding.ticketIdentifier.setText(airplaneTicketResource.ticketNumber)
                            }

                            if (airplaneTicketResource.ticketCode.isNotBlank()) {
                                binding.ticketCode.setText(airplaneTicketResource.ticketCode)
                            }

                            binding.flightDescription.setText(airplaneTicketResource.flightsDescription)

                            binding.flightSketch.text = airplaneTicketResource.flightsCode

                            binding.flightCity.text = airplaneTicketResource.flightsCity

                            binding.flightDate.text = airplaneTicketResource.flightsDate

                            binding.flightTime.text = airplaneTicketResource.flightsTime

                            when (airplaneTicketResource.isCheckIn) {
                                1 -> {
                                    binding.isCheckInYes.isChecked = true
                                }

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

                            when (airplaneTicketResource.isSetSeat) {
                                1 -> {
                                    binding.isSelectSeatYes.isChecked = true
                                }

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

                            when (airplaneTicketResource.isPackage) {
                                1 -> {
                                    binding.isBuyBaggageYes.isChecked = true
                                }

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

                            when (airplaneTicketResource.isBagHandle) {
                                1 -> {
                                    binding.isBagHandleYes.isChecked = true
                                }

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

                            when (airplaneTicketResource.isTrain) {
                                1 -> {
                                    binding.isTrainYes.isChecked = true
                                }

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

                            if (airplaneTicketResource.priceDescription.isNotBlank()) {
                                binding.paymentSketch.setText(airplaneTicketResource.priceDescription)
                            }

                            if (airplaneTicketResource.remark.isNotBlank()) {
                                binding.notes.setText(airplaneTicketResource.remark)
                            }

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

                            binding.consumeWay.setText(cardPaymentResource.consumptionPatterns)

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

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

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

                                        return@run
                                    }
                                }
                            }

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

                                    for (item in cardTypeList) {
                                        if (item.id == cardPaymentResource.ctdId) {
                                            binding.cardType.text = item.name
                                            binding.bankCardNumber.text = item.remark
                                            cardTypeId = cardPaymentResource.ctdId
                                            bankNo = cardPaymentResource.bankNo
                                            cardTypeSelect = true
                                        }
                                    }
                                }

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

                                    binding.companyBankNo.setText(cardPaymentResource.companyBankNo)

                                    binding.transferOtherBankName.setText(cardPaymentResource.otherBankName)

                                    binding.transferOtherSideNo.setText(cardPaymentResource.otherSideNo)

                                    binding.transferOtherSideName.setText(cardPaymentResource.otherSideName)
                                }

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

                                    binding.otherBankName.setText(cardPaymentResource.otherBankName)

                                    binding.otherSideNo.setText(cardPaymentResource.otherSideNo)

                                    binding.otherSideName.setText(cardPaymentResource.otherSideName)
                                }

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

                            binding.payee.setText(cardPaymentResource.payee)

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

                            binding.airplaneTicketAgents.text = cardPaymentResource.payee

                            if (cardPaymentResource.remark.isNotBlank()) {
                                binding.paymentApplyNotes.setText(cardPaymentResource.remark)
                            }

                            val customerSelected = airplaneTicketResource.clientName.split(",")

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

                            initCustomerList()

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

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

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