package com.yidianling.consultant.ui.view

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Region
import android.graphics.drawable.BitmapDrawable
import androidx.recyclerview.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.PopupWindow
import com.tencent.mmkv.MMKV
import com.ydl.ydlcommon.adapter.MyBaseAdapter
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.ydl.ydlcommon.view.dialog.CommonDialog
import com.yidianling.common.tools.RxDeviceTool
import com.yidianling.common.tools.RxImageTool
import com.yidianling.common.tools.ToastUtil
import com.yidianling.consultant.R
import com.yidianling.consultant.adapter.RegionRecyclerViewAdapter
import com.yidianling.consultant.adapter.SubRecyclerViewAdapter
import com.yidianling.consultant.bean.ConsultantRecentCity
import com.yidianling.consultant.constants.ConsultBIConstants
import com.yidianling.consultant.constants.ConsultBIConstants.ConsultEvent.Companion.CITY_NAME_CLICK
import com.yidianling.consultant.constants.ConsultBIConstants.ConsultantLocationAuth.Companion.RECENT_CITY
import com.yidianling.consultant.model.SearchApi
import com.yidianling.consultant.model.bean.RegionItem
import com.yidianling.consultant.model.bean.SubItem
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.consultant_ui_region_popup_window.view.*

/**
 * 地区选择弹窗
 */
class AreaPopupWindow(
    val context: Context,
    regionList: ArrayList<RegionItem>,
    private var selectedRegion: RegionItem,
    private var selectedSub: SubItem,
    private val isAgree: Boolean
) : PopupWindow(null, ViewGroup.LayoutParams.MATCH_PARENT, RxImageTool.dp2px(369f)) {

    private val subList = ArrayList<SubItem>()
    private val regionAdapter = RegionRecyclerViewAdapter(context, regionList, selectedRegion)
    private var subAdapter: SubRecyclerViewAdapter

    private var recentCityBean: ConsultantRecentCity? = ConsultantRecentCity(arrayListOf())
    var onRegionSelectedListener: OnRegionSelectedListener? = null
    private var subLocationItem: SubItem? = SubItem()
    private val locationCode = "-1"
    private var locationList: ArrayList<SubItem>? = arrayListOf()
    private var locationHistoryList = regionList

    init {
        val view =
            LayoutInflater.from(context).inflate(R.layout.consultant_ui_region_popup_window, null)
        this.contentView = view
        this.isFocusable = true
        @Suppress("DEPRECATION")
        this.setBackgroundDrawable(BitmapDrawable())
        this.isOutsideTouchable = true
        this.height =
            ((RxDeviceTool.getScreenHeight(context) - RxImageTool.dp2px(90f)) * 0.618).toInt() //设置高度为屏幕的80%
        regionAdapter.regionList = regionList
        if (selectedRegion.sub.isNotEmpty()) {
            subList.addAll(selectedRegion.sub)
        } else {
            subList.addAll(regionList[0].sub)
        }
         recentCityBean =
             MMKV.defaultMMKV().decodeParcelable(
                 RECENT_CITY,
                 ConsultantRecentCity::class.java
             )
        if (recentCityBean == null) recentCityBean = ConsultantRecentCity(arrayListOf())
        subAdapter = SubRecyclerViewAdapter(context, subList, selectedSub, locationCode)
        subAdapter.setOnAuthClickLister(object : SubRecyclerViewAdapter.OnAuthClickLister {
            override fun onAuthClick() {
                val dialog = CommonDialog(context)
                    .setTitle("温馨提示")
                    .setMessage("建议您授权定位权限，就能轻松获取周边优秀咨询师和其他服务")
                    .setLeftOnclick("暂不") { v1 ->
                        ActionCountUtils.count(
                            ConsultBIConstants.ConsultEvent.AUTHORIZATION_ICON_CLICK,
                            "暂不"
                        )

                    }.setRightClick("授权") { v12 ->
                        ActionCountUtils.count(
                            ConsultBIConstants.ConsultEvent.AUTHORIZATION_ICON_CLICK,
                            "授权"
                        )

                        MMKV.defaultMMKV().encode(
                            ConsultBIConstants.ConsultantLocationAuth.WHETHER_LOCATION_AUTH,
                            true
                        )
                        getRegionByIp(true, true)
                    }
                dialog.show()
            }

        })
        view.rvRegion.layoutManager =
            LinearLayoutManager(
                context,
                LinearLayoutManager.VERTICAL,
                false
            )
        regionAdapter.onItemClickListener = MyBaseAdapter.OnItemClickListener { _, _, data ->
            selectedRegion = data
            subList.clear()
            subList.addAll(data.sub)
            subAdapter.notifyDataSetChanged()
            view.rvSub.scrollToPosition(0)
        }
        view.rvRegion.adapter = regionAdapter
        val i = regionList
            .takeWhile { it.key != selectedRegion.key }
            .count()
        view.rvRegion.scrollToPosition(i)


        view.rvSub.layoutManager =
            LinearLayoutManager(
                context,
                LinearLayoutManager.VERTICAL,
                false
            )
        subAdapter.onItemClickListener = MyBaseAdapter.OnItemClickListener { _, _, data ->
            saveCitySearchRecord(data)
            selectedSub = data
            ActionCountUtils.count(CITY_NAME_CLICK, data.value.toString())
            onRegionSelectedListener?.onRegionSelected(selectedRegion, selectedSub)
        }
        view.rvSub.adapter = subAdapter
        view.rvSub.scrollToPosition(subList.indexOf(selectedSub) + 1)
    }

    //倒序保留最近五次的搜索历史记录并去重
    private fun saveCitySearchRecord(data: SubItem) {
        if (data.value == "不限") return
        if (selectedRegion.code.toString() != "0") data.provinceCode =
            selectedRegion.code.toString()

        recentCityBean?.let {
            if (it.recentCity.size < 5) {
                it.recentCity.add(0, data)
                it.recentCity = it.recentCity.toMutableSet().toMutableList()
                MMKV.defaultMMKV().encode(RECENT_CITY, recentCityBean)
            } else {
                it.recentCity.removeAt(it.recentCity.size - 1)
                it.recentCity.add(0, data)
                it.recentCity = it.recentCity.toMutableSet().toMutableList()
                MMKV.defaultMMKV().encode(RECENT_CITY, recentCityBean)
            }
        }
    }

    @SuppressLint("CheckResult")
    fun getRegionByIp(agreeLocation: Boolean, refreshAdapter: Boolean) {
        if (agreeLocation) {
            SearchApi.getSearchApi().getCityByIp()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    if (it.code == "200") {
                        subLocationItem?.code = it.data.city_code
                        subLocationItem?.key = it.data.city_code
                        subLocationItem?.value = it.data.city_name
                        subLocationItem?.locationCode = locationCode
                        locationList?.clear()
                        subLocationItem?.let { locationList?.add(it) }

                        locationHistoryList.get(0).code = it.data.province_code
                        locationHistoryList.get(0).key = it.data.province_code
                        locationHistoryList.get(0).value = "定位"
                        locationList?.let { locationHistoryList.get(0).sub = it }
                        subList.clear()
                        locationList?.let { it1 -> subList.addAll(it1) }
                        subAdapter.notifyDataSetChanged()
                        regionAdapter.notifyDataSetChanged()
                    } else {
                        subLocationItem?.code = null
                        subLocationItem?.key = null
                        subLocationItem?.value = "定位失败，请稍后再试"
                        subLocationItem?.locationCode = "NotAuth"
                        subAdapter.notifyDataSetChanged()
                        regionAdapter.notifyDataSetChanged()
                    }
                }, {})
        } else {
            subLocationItem?.code = null
            subLocationItem?.key = null
            subLocationItem?.value = "开启授权，获得定位城市"
            subLocationItem?.locationCode = "NotAuth"
            subAdapter.notifyDataSetChanged()
            regionAdapter.notifyDataSetChanged()
        }

    }

    interface OnRegionSelectedListener {
        fun onRegionSelected(region: RegionItem, sub: SubItem)
    }
}
