package com.abbidot.tracker.ui.common

import android.content.Context
import android.text.TextUtils
import android.view.View
import com.abbidot.baselibrary.list.BaseRecyclerAdapter
import com.abbidot.tracker.R
import com.abbidot.tracker.adapter.TextViewAdapter
import com.abbidot.tracker.bean.CountryCodeBean
import com.abbidot.tracker.bean.DataBean
import com.abbidot.tracker.dialog.CommonListDialog

/**
 *Created  by .yzq on 2024/7/10/010.
 * @link
 * @description:
 */
class CountryCommon(context: Context, listener: BaseRecyclerAdapter.OnItemClickListener) {

    private var mCountryCodeDialog: CommonListDialog? = null
    private var mCountryCodeAdapter: TextViewAdapter
    private var mCountryCode = ""
    private var mCountry = ""

    private var mContext: Context = context

    init {
        mCountryCodeAdapter = TextViewAdapter(context, null).apply {
            setOnItemClickListener(object : BaseRecyclerAdapter.OnItemClickListener {
                override fun onItemClick(itemView: View?, pos: Int) {
                    if (getData().isNotEmpty()) {
                        val dataBean = getData()[pos]
                        mCountryCode = dataBean.value
                        mCountry = dataBean.name
                        mCountryCodeDialog?.dismiss()
                        listener.onItemClick(itemView, pos)
                    }
                }
            })
        }
    }

    fun getCountryCode() = mCountryCode
    fun getCountry() = mCountry

    /**
     * 设置国家代码数据
     */
    fun setCountryCodeData(dataList: MutableList<CountryCodeBean>) {
        val countryCodeList = mutableListOf<DataBean>()
        val countryName = mContext.resources.getStringArray(R.array.country_name)
        val countryCode = mContext.resources.getIntArray(R.array.country_code)
        for (code in dataList) {
            for (i in countryCode.indices) {
                if (code.countryCode == countryCode[i]) {
                    val dataBean = DataBean()
                    dataBean.value = code.countryCode.toString()
                    dataBean.name = countryName[i]
                    countryCodeList.add(dataBean)
                    break
                }
            }
        }
        mCountryCodeAdapter.setData(countryCodeList, true)
    }

    fun showCountryCodeDialog() {
        if (null == mCountryCodeDialog) {
            mCountryCodeDialog =
                CommonListDialog(mContext, mCountryCodeAdapter, 3, 3, dialogHeightDp = 300)
        }
        mCountryCodeDialog?.show()
    }

    fun codeToCountry(code: String): String {
        var country = ""
        if (TextUtils.isEmpty(code)) return country
        val list = mCountryCodeAdapter.getData()
        for (data in list) {
            if (data.value == code) {
                country = data.name
                mCountryCode = data.value
                mCountry = data.name
                break
            }
        }
        return country
    }
}