package com.yidianling.consultant.ui.view

import android.content.Context
import android.graphics.drawable.BitmapDrawable
import android.text.SpannableString
import android.text.Spanned
import android.text.style.AbsoluteSizeSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.PopupWindow
import android.widget.TextView
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.yidianling.common.tools.RxDeviceTool
import com.yidianling.common.tools.RxImageTool
import com.yidianling.consultant.R
import com.yidianling.consultant.constants.ConsultBIConstants.ConsultEvent.Companion.BOTTOM_ICON_CLICK
import com.yidianling.consultant.constants.ConsultBIConstants.ConsultEvent.Companion.PRICE_CHOICE_CLICK
import com.yidianling.consultant.constants.ConsultBIConstants.ConsultEvent.Companion.PRICE_SLIDE_CLICK
import com.yidianling.consultant.listener.OnPriceItemSelectedListener
import com.yidianling.consultant.model.bean.AllFilter
import com.yidianling.consultant.model.bean.Filters
import com.yidianling.consultant.model.bean.PriceRangesItem
import com.yidianling.consultant.ui.view.rangeseekbar.OnRangeChangedListener
import com.yidianling.consultant.ui.view.rangeseekbar.RangeSeekBar
import kotlinx.android.synthetic.main.consultant_ui_price_popup_window.view.*


/**
 * 排序弹窗
 * Created by zqk on 17-9-15.
 */
class PricePopupWindow(
    val context: Context,
    private val filterData: Filters,
    private val tempFilter: AllFilter,
    var onPriceItemSelectedListener: OnPriceItemSelectedListener
) : PopupWindow(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) {

    private val popWidth = (RxDeviceTool.getScreenWidth(context))

    //价格筛选一行三个项
    private val enquirySize = 3
    private val priceRangeViews: ArrayList<View> = ArrayList()
    private var min_Price = ""
    private var max_Price = ""
    private var SeekBarLeftValue = 0f
    private var SeekBarRightValue = 0f
    private val maxPriceValue = 600
    private val infiniteText = "无限"
    private var track = false
    init {
        val view =
            LayoutInflater.from(context).inflate(R.layout.consultant_ui_price_popup_window, null)
        this.contentView = view
        this.isFocusable = true
        @Suppress("DEPRECATION")
        this.setBackgroundDrawable(BitmapDrawable())
        this.isOutsideTouchable = true
        initPriceTag()
        contentView.price_Confirm.setOnClickListener {
            ActionCountUtils.count(BOTTOM_ICON_CLICK, contentView.price_Confirm.text.toString())
            if (max_Price == infiniteText) max_Price = ""
            var priceRangesItem = PriceRangesItem(min_Price, max_Price)
            priceRangesItem.key1 = filterData.priceRanges[0].key1
            tempFilter.priceRanges?.key1 = filterData.priceRanges[0].key1
            onPriceItemSelectedListener.onPriceItemSelected(priceRangesItem)
            dismiss()
        }
        contentView.price_reset.setOnClickListener {
            ActionCountUtils.count(BOTTOM_ICON_CLICK, contentView.price_reset.text.toString())
            //重置
            contentView.range_price_seekbar.setProgress(0f, 100f)
            reset()
        }
        if (tempFilter.priceRanges != null) {
            if (tempFilter.priceRanges?.min_price.isNullOrEmpty()) {
                min_Price = "0"
                SeekBarLeftValue = 0f
            } else {
                min_Price = tempFilter.priceRanges?.min_price.toString()
                SeekBarLeftValue =
                    (tempFilter.priceRanges?.min_price.toString().toFloat() / maxPriceValue) * 100f
            }
            if (tempFilter.priceRanges?.max_price.isNullOrEmpty()) {
                max_Price = infiniteText
                SeekBarRightValue = 100f
            } else {
                max_Price = tempFilter.priceRanges?.max_price.toString()
                SeekBarRightValue =
                    (tempFilter.priceRanges?.max_price.toString().toFloat() / maxPriceValue) * 100f
            }
            if (SeekBarRightValue > 100f) SeekBarRightValue = 100f
            if (max_Price == infiniteText) {
                contentView.tv_start_end_price.text = "$min_Price-$max_Price"
            } else {
                contentView.tv_start_end_price.text = "$min_Price-$max_Price" + "元"
            }
            contentView.range_price_seekbar.setProgress(SeekBarLeftValue, SeekBarRightValue)

        } else {
            contentView.range_price_seekbar.setProgress(0f, 100f)
        }
        contentView.range_price_seekbar.setOnRangeChangedListener(object : OnRangeChangedListener {
            override fun onRangeChanged(
                view: RangeSeekBar?,
                leftValue: Float,
                rightValue: Float,
                isFromUser: Boolean
            ) {
                if (track) {
                    max_Price = ((rightValue / 100) * maxPriceValue).toInt().toString()
                    min_Price = ((leftValue / 100) * maxPriceValue).toInt().toString()
                    tempFilter.priceRanges = PriceRangesItem(min_Price, max_Price)
                    if (rightValue > 93) {
                        max_Price = infiniteText
                    }
                    ActionCountUtils.count(PRICE_SLIDE_CLICK, "$min_Price-$max_Price")
                    contentView.tv_start_end_price.text =
                        "$min_Price-$max_Price"

                }
            }

            override fun onStartTrackingTouch(view: RangeSeekBar?, isLeft: Boolean) {
                track = true
                reset()
            }

            override fun onStopTrackingTouch(view: RangeSeekBar?, isLeft: Boolean) {
                track = false
            }

        })
    }

    private fun reset() {
        tempFilter.priceRangesView = null
        tempFilter.priceRanges = null
        min_Price = ""
        max_Price = ""
        contentView?.tv_start_end_price?.text = "0-无限"
        for (v in priceRangeViews) {
            v.isSelected = false
            if (v is TextView) {
                v.paint.isFakeBoldText = false
            }
        }
        initPriceTag()
    }

    fun initPriceTag() {
        val mWidth = (popWidth - RxImageTool.dp2px(52f)) / enquirySize
        for ((index, priceRangesItem) in filterData.priceRanges.withIndex()) {
            val textView = View.inflate(context, R.layout.consultant_item_filter, null) as TextView
            val params = FrameLayout.LayoutParams(mWidth, RxImageTool.dp2px(50f))
            val marginNum = RxImageTool.dp2px(2f)
            params.setMargins(
                marginNum + (RxImageTool.dp2px(10f) + mWidth) * (index % enquirySize),
                RxImageTool.dp2px(58f) * (index / 3),
                marginNum,
                0
            )
            textView.layoutParams = params
            val contentStr = String.format(
                "%s\n%s",
                priceRangesItem.display_range,
                priceRangesItem.recommend_percent
            )
            val msp = SpannableString(contentStr)
            msp.setSpan(
                AbsoluteSizeSpan(10, true),
                contentStr.indexOf("\n"),
                contentStr.length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            textView.text = msp

            textView.setSingleLine(false)
            textView.setLineSpacing(1.0f, 1.2f)
            priceRangeViews.add(textView)
            if (priceRangesItem == tempFilter.priceRanges) {
                textView.isSelected = true
                textView.background = context.getDrawable(R.drawable.consult_price_expert_selected)
                textView.paint.isFakeBoldText = true
                tempFilter.priceRangesView = textView
            }

            textView.setOnClickListener {
                if (textView != tempFilter.priceRangesView) {
                    tempFilter.priceRangesView?.isSelected = false
                    tempFilter.priceRangesView?.background =
                        context.getDrawable(R.drawable.consult_price_expert_unseleted)
                    tempFilter.priceRangesView?.paint?.isFakeBoldText = false
                }
                if (textView.isSelected) {
                    textView.background =
                        context.getDrawable(R.drawable.consult_price_expert_unseleted)
                    tempFilter.priceRanges = null
                    textView.isSelected = false
                    textView.paint.isFakeBoldText = false
                    tempFilter.priceRangesView = null
                    min_Price = ""
                    max_Price = ""
                    contentView.range_price_seekbar.setProgress(0f, 100f)
                    contentView.tv_start_end_price.text = "0-$infiniteText"
                } else {
                    textView.background =
                        context.getDrawable(R.drawable.consult_price_expert_selected)
                    tempFilter.priceRanges = priceRangesItem.copy(
                        min_price = priceRangesItem.min_price,
                        max_price = priceRangesItem.max_price
                    )
                    ActionCountUtils.count(
                        PRICE_CHOICE_CLICK,
                        priceRangesItem.min_price + "-" + priceRangesItem.max_price
                    )
                    textView.isSelected = true
                    textView.paint.isFakeBoldText = true
                    tempFilter.priceRangesView = textView
                    if (priceRangesItem.min_price.isNullOrEmpty()) {
                        min_Price = "0"
                        SeekBarLeftValue = 0f
                    } else {
                        min_Price = priceRangesItem.min_price.toString()
                        SeekBarLeftValue =
                            (priceRangesItem.min_price.toString().toFloat() / maxPriceValue) * 100f
                    }
                    if (priceRangesItem.max_price.isNullOrEmpty()) {
                        max_Price = infiniteText
                        SeekBarRightValue = 100f
                    } else {
                        max_Price = priceRangesItem.max_price.toString()
                        SeekBarRightValue =
                            (priceRangesItem.max_price.toString().toFloat() / maxPriceValue) * 100f
                    }
                    if (SeekBarRightValue > 100f) SeekBarRightValue = 100f
                    contentView.range_price_seekbar.setProgress(SeekBarLeftValue, SeekBarRightValue)
                    contentView.postDelayed(Runnable { }, 30)
                    if (max_Price == infiniteText) {
                        contentView.tv_start_end_price.text = "$min_Price-$max_Price"
                    } else {
                        contentView.tv_start_end_price.text = "$min_Price-$max_Price" + "元"
                    }
                }
            }
            contentView.flPriceRangeView.addView(textView)
        }
    }


}