package com.pan_american.android.ui.efficiency_tools.exchange_tool

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.view.WindowManager
import android.widget.PopupWindow
import android.widget.TextView
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.pan_american.android.R
import com.pan_american.android.base.BaseActivity
import com.pan_american.android.base.ListAdapter
import com.pan_american.android.data.model.currency.entity.Currency
import com.pan_american.android.data.model.currency.network.CurrencyExchangeRequest
import com.pan_american.android.data.model.currency.network.CurrencyExchangeResponse
import com.pan_american.android.data.model.currency.network.CurrencyResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.ActivityExchangeToolBinding
import com.pan_american.android.databinding.LayoutNumericalInputBinding
import com.pan_american.android.databinding.LayoutTitleBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class ExchangeToolActivity : BaseActivity<ActivityExchangeToolBinding>() {

    companion object {
        const val CURRENCY_PRE = 1
        const val CURRENCY_SUF = 0
    }

    private lateinit var titleBinding: LayoutTitleBinding

    private lateinit var numericalInputBinding: LayoutNumericalInputBinding

    val apiService = ServiceCreator.create<APIService>()

    private var currencyList = ArrayList<Currency>()

    private var listInit = false

    private var currencyPre = "CNY"

    private var currencySuf = "USD"

    private var reverseItem = ""

    private lateinit var currencyExchangeRequest: CurrencyExchangeRequest

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

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

        initTitle()
        initViews()
        initEvents()
    }

    override fun onStart() {
        super.onStart()
        initEvents()
    }

    override fun initTitle() {
        titleBinding = LayoutTitleBinding.bind(binding.root).apply {
            titleText.text = resources.getString(R.string.exchange_tool)
            backButton.setOnClickListener {
                back()
            }
        }
    }

    override fun initViews() {
        numericalInputBinding = LayoutNumericalInputBinding.bind(binding.root)
    }

    override fun initEvents() {

        initNumericalInputListener()

        binding.currencyPre.setOnClickListener {
            initCurrencyList(CURRENCY_PRE)
        }
        binding.currencySuf.setOnClickListener {
            initCurrencyList(CURRENCY_SUF)
        }
        binding.exchangeInput.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?) {
                startCurrencyExchange()
            }
        })
        binding.reverse.setOnClickListener {

            reverseItem = binding.currencySuf.text.toString()
            binding.currencySuf.text = binding.currencyPre.text
            binding.currencyPre.text = reverseItem

            reverseItem = currencySuf
            currencySuf = currencyPre
            currencyPre = reverseItem

            startCurrencyExchange()
        }
    }

    private fun initCurrencyList(type: Int) {
        //避免出现界面透明的问题
        window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)

        if (!listInit) {

            apiService.getCurrency().enqueue(object : Callback<CurrencyResponse> {
                override fun onResponse(
                    call: Call<CurrencyResponse>, response: Response<CurrencyResponse>
                ) {
                    val currencyResponse = response.body()
                    if (currencyResponse != null) {
                        if (currencyResponse.code == 200) {
                            for (item in currencyResponse.data) {
                                currencyList.add(item)
                            }
                            listInit = true
                            initPopupWindow(type)
                        } else {
                            showMessage(currencyResponse.msg)
                        }
                    }
                }

                override fun onFailure(call: Call<CurrencyResponse>, t: Throwable) {
                    showErrorInfo(R.string.currency_list_get_failed)
                }
            })
        } else {
            initPopupWindow(type)
        }
    }

    private fun initPopupWindow(type: Int) {

        val popView = View.inflate(this, R.layout.popup_smart_refresh_selector, null)
        popupWindow = PopupWindow(
            popView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
        )

        showPopupWindow {
            //初始化RecyclerView
            selector = popView.findViewById(R.id.selector_list)

            selectorContainer = popView.findViewById(R.id.selector_refresh_container)
            selectorContainer.setEnableRefresh(false)
            selectorContainer.setEnableLoadMore(false)

            val adapter = ListAdapter.Builder<Currency>().setData(currencyList)
                .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
                        )

                        when (type) {
                            CURRENCY_PRE -> {
                                if (currencyPre == data.currencyCode) {
                                    setTextColor(ResourcesCompat.getColor(resources, R.color.text_color_blue, null))
                                } else {
                                    setTextColor(ResourcesCompat.getColor(resources, R.color.text_color, null))
                                }
                            }

                            CURRENCY_SUF -> {
                                if (currencySuf == data.currencyCode) {
                                    setTextColor(ResourcesCompat.getColor(resources, R.color.text_color_blue, null))
                                } else {
                                    setTextColor(ResourcesCompat.getColor(resources, R.color.text_color, null))
                                }
                            }
                        }
                    }
                }.create()

            val layoutManager = LinearLayoutManager(this)
            selector.layoutManager = layoutManager

            selector.adapter = adapter

            adapter.onRecyclerViewItemClick =
                object : ListAdapter.OnRecyclerViewItemClick<Currency> {
                    override fun onItemClick(position: Int) {
                        popupWindow.dismiss()
                        if (type == CURRENCY_PRE) {
                            binding.currencyPre.text = String.format(
                                resources.getString(R.string.currency_name_code_format),
                                currencyList[position].currencyName,
                                currencyList[position].currencyCode
                            )
                            currencyPre = currencyList[position].currencyCode
                            startCurrencyExchange()
                        } else {
                            binding.currencySuf.text = String.format(
                                resources.getString(R.string.currency_name_code_format),
                                currencyList[position].currencyName,
                                currencyList[position].currencyCode
                            )
                            currencySuf = currencyList[position].currencyCode
                            startCurrencyExchange()
                        }
                    }
                }

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

    private fun startCurrencyExchange() {
        if (binding.exchangeInput.text.isEmpty()) {
            binding.exchangeOutput.text = "-"
            binding.refreshTime.text = ""
        } else {
            if (binding.exchangeInput.text.endsWith(".")) {
                binding.exchangeInput.text.substring(0, binding.exchangeInput.text.length - 1)
            }
            if (currencyPre == currencySuf) {
                binding.exchangeOutput.text = binding.exchangeInput.text
            } else {
                currencyExchange()
            }
        }
    }

    private fun currencyExchange() {
        val apiService = ServiceCreator.create<APIService>()
        currencyExchangeRequest = CurrencyExchangeRequest(
            currencyPre, currencySuf, binding.exchangeInput.text.toString().toFloat()
        )

        apiService.currencyExchange(currencyExchangeRequest)
            .enqueue(object : Callback<CurrencyExchangeResponse> {
                override fun onResponse(
                    call: Call<CurrencyExchangeResponse>,
                    response: Response<CurrencyExchangeResponse>
                ) {
                    val currencyExchangeResponse = response.body()
                    if (currencyExchangeResponse != null) {
                        if (currencyExchangeResponse.code == 200) {
                            binding.exchangeOutput.text =
                                currencyExchangeResponse.data.moneySuf.toString()
                            binding.refreshTime.text = String.format(
                                resources.getString(R.string.update_time),
                                currencyExchangeResponse.data.updateTime
                            )
                        } else {
                            showMessage(currencyExchangeResponse.msg)
                        }
                    }
                }

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

    private fun initNumericalInputListener() {
        numericalInputBinding.input00.setOnClickListener {
            if (binding.exchangeInput.text.isNotEmpty()) {
                binding.exchangeInput.append("00")
            }
        }
        numericalInputBinding.input0.setOnClickListener {
            if (binding.exchangeInput.text.isNotEmpty()) {
                binding.exchangeInput.append("0")
            }
        }
        numericalInputBinding.inputPoint.setOnClickListener {
            if (binding.exchangeInput.text.isNotEmpty() && !binding.exchangeInput.text.contains(".")) {
                binding.exchangeInput.append(".")
            }
        }
        numericalInputBinding.input1.setOnClickListener {
            binding.exchangeInput.append("1")
        }
        numericalInputBinding.input2.setOnClickListener {
            binding.exchangeInput.append("2")
        }
        numericalInputBinding.input3.setOnClickListener {
            binding.exchangeInput.append("3")
        }
        numericalInputBinding.input4.setOnClickListener {
            binding.exchangeInput.append("4")
        }
        numericalInputBinding.input5.setOnClickListener {
            binding.exchangeInput.append("5")
        }
        numericalInputBinding.input6.setOnClickListener {
            binding.exchangeInput.append("6")
        }
        numericalInputBinding.inputAc.setOnClickListener {
            binding.exchangeInput.text = ""
        }
        numericalInputBinding.input7.setOnClickListener {
            binding.exchangeInput.append("7")
        }
        numericalInputBinding.input8.setOnClickListener {
            binding.exchangeInput.append("8")
        }
        numericalInputBinding.input9.setOnClickListener {
            binding.exchangeInput.append("9")
        }
        numericalInputBinding.inputDelete.setOnClickListener {
            if (binding.exchangeInput.text.isNotEmpty()) {
                binding.exchangeInput.text =
                    binding.exchangeInput.text.substring(0, binding.exchangeInput.text.length - 1)
            }
        }
    }
}