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

import android.os.Bundle
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 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.data.model.common.network.GroupCostDataRequest
import com.pan_american.android.data.model.group_hotel.hotel_predetermine.entity.HotelCost
import com.pan_american.android.data.model.group_hotel.hotel_predetermine.entity.UpdateHotelPredetermine
import com.pan_american.android.data.model.group_hotel.hotel_predetermine.network.GetHotelPredetermineDetailRequest
import com.pan_american.android.data.model.group_hotel.hotel_predetermine.network.GetHotelPredetermineDetailResponse
import com.pan_american.android.data.model.group_hotel.hotel_predetermine.network.HotelCostDetailResponse
import com.pan_american.android.data.model.group_hotel.hotel_predetermine.network.HotelPredetermineResourceRequest
import com.pan_american.android.data.model.group_hotel.hotel_predetermine.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 org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class AddHotelPredetermineActivity : BaseActivity<ActivityAddHotelPredetermineBinding>() {

    private lateinit var titleBinding: LayoutTitleBinding

    private var fromList = false

    private var groupId = 0

    private var paymentId = 0

    private var teamName = ""

    private var tourCode = ""

    private var clientName = ""

    private var visitCountry = ""

    private var isAuditGM = -1

    private var canBeEdit = false

    private var hotelCostInit = false

    private var hotelCostCurrency = ""

    private var hotelCostExchangeRate = 0.0

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

    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)
            teamName = getStringExtra("teamName").toString()
            tourCode = getStringExtra("tourCode").toString()
            clientName = getStringExtra("clientName").toString()
            visitCountry = getStringExtra("visitCountry").toString()

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

        canBeEdit = canBeEdit()

        OASystem.hotelPredetermineRequest = UpdateHotelPredetermine()

        initTitle()

        //初始化数据源

        OASystem.hotelPredetermineCustomerType.clear()
        OASystem.hotelPredeterminePaymentWay.clear()
        OASystem.hotelPredeterminePaymentCurrency.clear()
        OASystem.hotelPredetermineBankCard.clear()
        OASystem.hotelPredetermineHotelWebSite.clear()
        OASystem.hotelPredetermineCheckInType.clear()
        OASystem.hotelPredetermineCustomerList.clear()
        OASystem.hotelPredetermineCountries.clear()

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

            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() {

        val hotelPredetermineBaseFragment = HotelPredetermineBaseFragment()

        val bundle = Bundle().apply {
            putBoolean("fromList", fromList)
            putString("teamName", teamName)
            putString("tourCode", tourCode)
            putString("clientName", clientName)
            putString("visitCountry", visitCountry)
            putBoolean("canBeEdit", canBeEdit)

            putInt("groupId", groupId)
        }

        hotelPredetermineBaseFragment.arguments = bundle

        supportFragmentManager.beginTransaction().addToBackStack(null)
            .add(binding.hotelPredetermineContainer.id, hotelPredetermineBaseFragment)
            .commit()

    }

    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) {
                                OASystem.hotelPredetermineCustomerType.add(item)
                            }

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

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

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

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

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

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

                            for (item in resourceResponse.data.countrys) {
                                OASystem.hotelPredetermineCountries.add(item)
                            }

                            if (fromList) {
                                getHotelPredetermineDetail()
                            } else {
                                initViews()
                            }

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

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

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

                            OASystem.hotelPredetermineRequest = detailResponse.data

                            initViews()

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

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

    private fun canBeEdit(): Boolean {
        return if (fromList) {
            OASystem.authorization(OASystem.HOTEL_PREDETERMINE, OASystem.EDIT) and (isAuditGM != 1)
        } else {
            true
        }
    }

    override fun onStart() {
        super.onStart()

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

    override fun onStop() {
        super.onStop()

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

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateHotelPredetermine(hotelPredetermine: UpdateHotelPredetermine) {

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

                if (updateResponse != null) {
                    if (updateResponse.code == 200) {
                        if (fromList) {
                            showMessage(resources.getString(R.string.update_success))
                        } else {
                            showMessage(resources.getString(R.string.insert_success))
                        }

                        OASystem.needRefresh = true

                        finish()



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

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