package com.yidianling.consultant.ui.view

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.drawable.BitmapDrawable
import android.os.Build
import androidx.core.content.ContextCompat
import android.text.*
import android.text.style.AbsoluteSizeSpan
import android.util.Log
import android.view.Gravity
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.*
import com.ydl.ydlcommon.data.http.RxUtils
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.ydl.ydlcommon.utils.remind.ToastHelper
import com.yidianling.common.tools.RxDeviceTool
import com.yidianling.common.tools.RxImageTool
import com.yidianling.common.tools.RxKeyboardTool
import com.yidianling.consultant.R
import com.yidianling.consultant.constants.ConsultBIConstants
import com.yidianling.consultant.http.ExpertSearchDataManager
import com.yidianling.consultant.listener.OnFilterConfirmListener
import com.yidianling.consultant.model.bean.AllFilter
import com.yidianling.consultant.model.bean.Filters
import com.yidianling.consultant.model.bean.PriceRangesItem
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.consultant_item_filter.view.*
import kotlinx.android.synthetic.main.consultant_item_price_range.view.*
import kotlinx.android.synthetic.main.consultant_ui_filter_popup.view.*


/**
 * 筛选弹窗
 * Created by zqk on 17-9-15.
 */
class FilterPopupWindow(private val context: Context, private val filterData: Filters, private val tempFilter: AllFilter)
    : PopupWindow(context) {

    private val mDisposableList = CompositeDisposable()

    private val showTypeViews: ArrayList<View> = ArrayList()
    private val enquiryViews: ArrayList<View> = ArrayList()
    private val priceRangeViews: ArrayList<View> = ArrayList()
    private val ageViews: ArrayList<View> = ArrayList()
    private val otherViews: ArrayList<View> = ArrayList()
    private val ziZhiViews: ArrayList<View> = ArrayList()
    var onFilterConfirmListener: OnFilterConfirmListener? = null

    private var dp5 = 0
    private var dp10 = 0
    private var dp36 = 0
    private var dp46 = 0

    //    val pad = RxImageTool.dp2px(15f)
    private val popWidth = (RxDeviceTool.getScreenWidth(context) * 0.8).toInt()

    var etMinPrice: EditText? = null
    var etMaxPrice: EditText? = null

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.consultant_ui_filter_popup, null)

        dp5 = RxImageTool.dip2px(5f)
        dp10 = RxImageTool.dip2px(10f)
        dp36 = RxImageTool.dip2px(36f)
        dp46 = RxImageTool.dip2px(46f)
        this.width = popWidth
        this.height = RxDeviceTool.getAppHeight(context) + RxDeviceTool.getStatusBarHeight(context)
        contentView = view

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            contentView.foregroundGravity = Gravity.RIGHT
        }

        this.isFocusable = true
        @Suppress("DEPRECATION")
        this.setBackgroundDrawable(BitmapDrawable())
        this.isOutsideTouchable = true

        this.animationStyle = R.style.consultant_expert_service_popupwindow_filter_anim_style

        initShowTypeViews(view)
        initEnquiryViews(view)
        initPriceViews(view)
        initAgeViews(view)
        initOtherViews(view)
        initZiZhiViews(view)
        initKeyboardListener(view)

        updateCount()

        view.btnReset.setOnClickListener {
            reset()
        }

        view.btnConfirm.setOnClickListener {
            biEvent(ConsultBIConstants.POSITION_CONSULT_FILTER_CHECKOUT_CLICK)
            onFilterConfirmListener?.onFilterConfirmed()
            dismiss()
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun initKeyboardListener(view: View) {
        var svFilter = view.findViewById<ScrollView>(R.id.sv_filter)
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

        svFilter.setOnTouchListener { _, _ ->
            if (imm.isActive(etMinPrice) || imm.isActive(etMaxPrice)) {
                RxKeyboardTool.hideSoftInput(context, etMaxPrice)
                RxKeyboardTool.hideSoftInput(context, etMinPrice)
            }
            false
        }

        val activity = context as Activity;
        RxKeyboardTool.setKeyboardChangedListener(activity) { b: Boolean, i: Int, i1: Int, i2: Int ->
            if (!b) {
                //软键盘隐藏
                updatePriceFilter()
            }
        }
    }


    private fun reset() {
        tempFilter.showType = filterData.showType[0]
        tempFilter.ages.clear()
        tempFilter.enquiries.clear()
        tempFilter.others.clear()
        tempFilter.title.clear()
        tempFilter.priceRangesView = null
        tempFilter.priceRanges = null
        etMinPrice?.setText("")
        etMaxPrice?.setText("")

        for (v in showTypeViews) {
            v.isSelected = false
            if (v is TextView) {
                v.paint.isFakeBoldText = false
            }
        }
        showTypeViews[1].isSelected = true
        for (v in enquiryViews) {
            v.isSelected = false
            if (v is TextView) {
                v.paint.isFakeBoldText = false
            }
        }
        for (v in ageViews) {
            v.isSelected = false
            if (v is TextView) {
                v.paint.isFakeBoldText = false
            }
        }
        for (v in otherViews) {
            v.isSelected = false
            if (v is TextView) {
                v.paint.isFakeBoldText = false
            }
        }
        for (v in ziZhiViews) {
            v.isSelected = false
            if (v is TextView) {
                v.paint.isFakeBoldText = false
            }
        }

        for (v in priceRangeViews) {
            v.isSelected = false
            if (v is TextView) {
                v.paint.isFakeBoldText = false
            }
        }

        updateCount(ConsultBIConstants.POSITION_CONSULT_FILTER_RESET_CLICK)
    }

    //获取筛选结果数
    @SuppressLint("CheckResult")
    private fun updateCount(biEventName: String = "") {
        var showType = 0
        val sb = StringBuffer()
        var biEventParams = ""

        sb.append("searchWord=").append(if (TextUtils.isEmpty(tempFilter.searchWord)) "" else tempFilter.searchWord)
        if (tempFilter.categories.isNotEmpty()) {
            var categorys = tempFilter.categories.map { it.cateId }.joinToString(",")
            if ("0" == categorys) {
                categorys = ""
            }
            sb.append("&categories=").append(categorys)
        }
        if (tempFilter.sub.key != null) {
            sb.append("&city=").append(Integer.parseInt(tempFilter.sub.key))
        }
        if (tempFilter.region.key != null) {
            sb.append("&province=").append(Integer.parseInt(tempFilter.region.key))
        }
        if (tempFilter.reorder.key != null) {
            sb.append("&reorder=").append(tempFilter.reorder.key)
        }
        if (tempFilter.enquiries.isNotEmpty()) {
            sb.append("&enquirys=").append(tempFilter.enquiries.map { it.key }.joinToString(","))
            if (ConsultBIConstants.POSITION_CONSULT_TYPE_CLICK == biEventName) {
                biEventParams = tempFilter.enquiries.map { it.key }.joinToString(",")
            }
        }
        if (tempFilter.ages.isNotEmpty()) {
            sb.append("&ages=").append(tempFilter.ages.map { it.key }.joinToString(","))
            if (ConsultBIConstants.POSITION_AGE_CHOICE_CLICK == biEventName) {
                biEventParams = tempFilter.ages.map { it.key }.joinToString(",")
            }
        }
        if (tempFilter.others.isNotEmpty()) {
            sb.append("&others=").append(tempFilter.others.map { it.key }.joinToString(","))
            if (ConsultBIConstants.POSITION_OTHER_CHOICE_CLICK == biEventName) {
                biEventParams = tempFilter.others.map { it.key }.joinToString(",")
            }
        }
        if (tempFilter.showType.key != null) {
            showType = tempFilter.showType.key!!
            sb.append("&showType=").append(tempFilter.showType.key!!)
        }
        if (tempFilter.title.isNotEmpty()) {
            sb.append("&title=").append(tempFilter.title.map { it.key }.joinToString(","))
            if (ConsultBIConstants.POSITION_QUALIFICATION_CHOICE_CLICK == biEventName) {
                biEventParams = tempFilter.title.map { it.key }.joinToString(",")
            }
        }

        if (tempFilter.priceRanges != null) {
            sb.append("&minPrice=").append(tempFilter.priceRanges?.minPrice)
            sb.append("&maxPrice=").append(tempFilter.priceRanges?.maxPrice)
            if (ConsultBIConstants.POSITION_AVERAGE_SERVICE_INPUT == biEventName) {
                var account = 0.0
                if (!TextUtils.isEmpty(tempFilter.priceRanges?.minPrice)) {
                    account += tempFilter.priceRanges?.minPrice?.toDouble()!!
                }
                if (!TextUtils.isEmpty(tempFilter.priceRanges?.maxPrice)) {
                    account += tempFilter.priceRanges?.maxPrice?.toDouble()!!
                }

                biEventParams = (Math.round(account / 2)).toString()
            }
        }

        //用户行为数据埋点
        biEvent(biEventName, biEventParams)

//        sb.append("&page=").append(1)
        ExpertSearchDataManager.getHttp().getFilterCount(sb.toString())
                .subscribeOn(Schedulers.io())
                .compose(RxUtils.resultJavaData())
                .map { it }
                .filter { it != null }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({

                    contentView.btnConfirm.text = if (it > 0) "确定" else "暂无匹配咨询师"
                    //按钮置灰/解除置灰
                    contentView.btnConfirm.isEnabled = it > 0
                    if (it > 0) {
                        contentView.btnConfirm.setTextColor(ContextCompat.getColor(context,R.color.platform_but_text_color))
                        contentView.btnConfirm.background = ContextCompat.getDrawable(context, R.drawable.consultant_bg_radius_5_dark)
//                        contentView.btnConfirm.setTextColor(ContextCompat.getColor(context,R.color.consultant_white))
                    } else {
                        contentView.btnConfirm.setTextColor(ContextCompat.getColor(context,R.color.platform_text_light_color))
                        contentView.btnConfirm.background = ContextCompat.getDrawable(context, R.drawable.consultant_bg_radius_5_light)
//                        contentView.btnConfirm.setTextColor(ContextCompat.getColor(context,R.color.color_999999))
                    }

                }, {
                    ToastHelper.show(it.message!!)
                })
    }

    private fun biEvent(biEventName: String, biEventParams: String = "") {
        if (!TextUtils.isEmpty(biEventName)) {
            ActionCountUtils.count(ConsultBIConstants.PART_ID_CONSULT_FILTER_PAGE+"|"+biEventName,  biEventParams)
        }
    }

    fun addSubscription(disposable: Disposable) {
        mDisposableList.add(disposable)
    }

    private fun initOtherViews(view: View) {
        val mWidth = (popWidth - RxImageTool.dp2px(52f)) / 3
        for ((index, other) in filterData!!.other!!.withIndex()) {
            val textView = View.inflate(context, R.layout.consultant_item_filter, null) as TextView
            val params = FrameLayout.LayoutParams(mWidth, dp36)
            val marginNum = dp5
            params.setMargins(marginNum + (dp10 + mWidth) * (index % 3),
                    RxImageTool.dp2px(46f) * (index / 3),
                    marginNum,
                    0)
            textView.layoutParams = params
            textView.text = other.value

            otherViews.add(textView)
            if (tempFilter!!.others!!.contains(other)) {
                textView.isSelected = true
                textView.paint.isFakeBoldText = true
            }
            textView.tvFilterName.text = "   " + other.value + "   "
            textView.setOnClickListener {

                if (textView.isSelected) {
                    tempFilter!!.others!!.remove(other)
                    textView!!.isSelected = false
                    textView.paint.isFakeBoldText = false
                } else {
                    tempFilter!!.others!!.add(other)
                    textView.isSelected = true
                    textView.paint.isFakeBoldText = true
                }
                updateCount(ConsultBIConstants.POSITION_OTHER_CHOICE_CLICK)
            }
            view.flOther.addView(textView)
        }
    }

    private fun initZiZhiViews(view: View) {
        val mWidth = (popWidth - RxImageTool.dp2px(40f)) / 2
        var float = 46f
        for ((index, other) in filterData!!.title!!.withIndex()) {
            val textView = View.inflate(context, R.layout.consultant_item_filter, null) as TextView
//            val params = FrameLayout.LayoutParams(mWidth,FrameLayout.LayoutParams.WRAP_CONTENT)
            val params = FrameLayout.LayoutParams(mWidth, dp36)
            val marginNum = dp5
//            params.setMargins(marginNum + (dp10 + mWidth) * (index % 2),
//                    RxImageTool.dp2px(float) * (index / 2),
//                    marginNum,
//                    0)
            params.setMargins(0, 0, RxImageTool.dp2px(10f), 0)
            textView.layoutParams = params
            textView.text = other.value

            if (textView.lineCount > 1) {

            }

            ziZhiViews.add(textView)
            if (tempFilter!!.title!!.contains(other)) {
                textView.isSelected = true
                textView.paint.isFakeBoldText = true
            }
            textView.tvFilterName.text = "   " + other.value + "   "
            textView.setOnClickListener {

                if (textView.isSelected) {
                    tempFilter!!.title!!.remove(other)
                    textView!!.isSelected = false
                    textView.paint.isFakeBoldText = false
                } else {
                    tempFilter!!.title!!.add(other)
                    textView.isSelected = true
                    textView.paint.isFakeBoldText = true
                }
                updateCount(ConsultBIConstants.POSITION_QUALIFICATION_CHOICE_CLICK)
            }
            view.flZhizi.addView(textView)
        }
    }

    private fun initAgeViews(view: View) {
        val mWidth = (popWidth - RxImageTool.dp2px(52f)) / 3
        for ((index, age) in filterData!!.age!!.withIndex()) {
            val textView = View.inflate(context, R.layout.consultant_item_filter, null) as TextView
            val params = FrameLayout.LayoutParams(mWidth, RxImageTool.dp2px(36f))
            val marginNum = RxImageTool.dp2px(5f)
            params.setMargins(marginNum + (dp10 + mWidth) * (index % 3),
                    dp46 * (index / 3),
                    marginNum,
                    0)
            textView.layoutParams = params
            textView.text = age.value

            ageViews.add(textView)
            if (tempFilter!!.ages!!.contains(age)) {
                textView.isSelected = true
                textView.paint.isFakeBoldText = true
            }
            textView.text = "    " + age.value + "    "
            textView.setOnClickListener {

                if (textView.isSelected) {
                    tempFilter!!.ages!!.remove(age)
                    textView.isSelected = false
                    textView.paint.isFakeBoldText = false
                } else {
                    tempFilter!!.ages!!.add(age)
                    textView.isSelected = true
                    textView.paint.isFakeBoldText = true
                }
                updateCount(ConsultBIConstants.POSITION_AGE_CHOICE_CLICK)
            }
            view.flAge.addView(textView)
        }
    }

    private fun initEnquiryViews(view: View) {
        val mWidth = (popWidth - RxImageTool.dp2px(52f)) / 3
        for ((index, enquiry) in filterData!!.enquiry!!.withIndex()) {
            val textView = View.inflate(context, R.layout.consultant_item_filter, null) as TextView
            val params = FrameLayout.LayoutParams(mWidth, RxImageTool.dp2px(36f))
            val marginNum = RxImageTool.dp2px(5f)
            params.setMargins(marginNum + (RxImageTool.dp2px(10f) + mWidth) * (index % 3),
                    RxImageTool.dp2px(46f) * (index / 3),
                    marginNum,
                    0)
            textView.layoutParams = params
            textView.text = enquiry.value

            enquiryViews.add(textView)
            if (tempFilter!!.enquiries!!.contains(enquiry)) {
                textView.isSelected = true
                textView.paint.isFakeBoldText = true
            }
            textView.setOnClickListener {

                if (textView.isSelected) {
                    tempFilter!!.enquiries!!.remove(enquiry)
                    textView.isSelected = false
                    textView.paint.isFakeBoldText = false
                } else {
                    tempFilter!!.enquiries!!.add(enquiry)
                    textView.isSelected = true
                    textView.paint.isFakeBoldText = true
                }
                updateCount(ConsultBIConstants.POSITION_CONSULT_TYPE_CLICK)
            }
            view.flEnquiryType.addView(textView)
        }
    }

    private fun initPriceViews(view: View) {
        val priceRange = View.inflate(context, R.layout.consultant_item_price_range, null) as LinearLayout
        etMinPrice = priceRange.findViewById<EditText>(R.id.etMinPrice);
        etMaxPrice = priceRange.findViewById<EditText>(R.id.etMaxPrice);

        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

        var listener: TextView.OnEditorActionListener = TextView.OnEditorActionListener { _, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE || event != null && event.keyCode == KeyEvent.KEYCODE_ENTER) {
                updatePriceFilter()
                true
            } else {
                false
            }
        }

        if (tempFilter.priceRanges != null) {
            etMinPrice?.setText(tempFilter.priceRanges?.minPrice)
            etMaxPrice?.setText(tempFilter.priceRanges?.maxPrice)
        }

        etMaxPrice?.setOnEditorActionListener(listener)
        etMinPrice?.setOnEditorActionListener(listener)

        etMaxPrice?.addTextChangedListener(object : TextWatcher {

            override fun afterTextChanged(s: Editable?) {}

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                // 以小数点开头，前面自动加上 "0"
                if (s.toString().startsWith(".")) {
                    etMaxPrice?.setText("0$s");
                    etMaxPrice?.setSelection(etMaxPrice?.text!!.length);
                }
            }
        })
        etMinPrice?.addTextChangedListener(object : TextWatcher {

            override fun afterTextChanged(s: Editable?) {}

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                // 以小数点开头，前面自动加上 "0"
                if (s.toString().startsWith(".")) {
                    etMinPrice?.setText("0$s");
                    etMinPrice?.setSelection(etMinPrice?.text!!.length);
                }
            }
        })

        val mWidth = (popWidth - RxImageTool.dp2px(52f)) / 3
        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(48f))
            val marginNum = RxImageTool.dp2px(2f)
            params.setMargins(marginNum + (RxImageTool.dp2px(10f) + mWidth) * (index % 3),
                    RxImageTool.dp2px(58f) * (index / 3),
                    marginNum,
                    0)
            textView.layoutParams = params
            val maxPriceStr = if (TextUtils.isEmpty(priceRangesItem.maxPrice)) "+" else "-" + priceRangesItem.maxPrice
            val contentStr = String.format("%s%s\n%s", priceRangesItem.minPrice, maxPriceStr, priceRangesItem.recommendPercent)


            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.paint.isFakeBoldText = true
                tempFilter.priceRangesView = textView
            }

            textView.setOnClickListener {
                if (textView != tempFilter.priceRangesView) {
                    tempFilter.priceRangesView?.isSelected = false
                    tempFilter.priceRangesView?.paint?.isFakeBoldText = false
                }
                if (textView.isSelected) {
                    tempFilter.priceRanges = null
                    textView.isSelected = false
                    textView.paint.isFakeBoldText = false
                    tempFilter.priceRangesView = null
                    etMaxPrice?.setText("")
                    etMinPrice?.setText("")
                } else {
                    tempFilter.priceRanges = priceRangesItem.copy(priceRangesItem.minPrice, priceRangesItem.maxPrice)
                    textView.isSelected = true
                    textView.paint.isFakeBoldText = true
                    tempFilter.priceRangesView = textView
                    etMinPrice?.setText(priceRangesItem.minPrice)
                    etMaxPrice?.setText(priceRangesItem.maxPrice)
                }

                updateCount(ConsultBIConstants.POSITION_AVERAGE_SERVICE_INPUT)
            }
            priceRange.flPriceRangeContainer.addView(textView)
        }
        view.flPriceRange.addView(priceRange)
    }

    private fun updatePriceFilter() {

        RxKeyboardTool.hideSoftInput(context, etMaxPrice)
        RxKeyboardTool.hideSoftInput(context, etMinPrice)

        if (tempFilter.priceRanges == null) {
            val priceRangesItem = PriceRangesItem()
            tempFilter.priceRanges = priceRangesItem;
        }

        tempFilter.priceRanges!!.maxPrice = etMaxPrice?.text.toString()
        tempFilter.priceRanges!!.minPrice = etMinPrice?.text.toString()
        tempFilter.priceRangesView?.isSelected = false
        tempFilter.priceRangesView?.paint?.isFakeBoldText = false
        tempFilter.priceRangesView = null
        etMinPrice?.clearFocus()
        etMaxPrice?.clearFocus()
        updateCount(ConsultBIConstants.POSITION_AVERAGE_SERVICE_INPUT)
    }

    private fun initShowTypeViews(view: View) {
        val mWidth = (popWidth - RxImageTool.dp2px(42f)) / 2
        for ((index, showType) in filterData.showType.withIndex()) {
            val textView = View.inflate(context, R.layout.consultant_item_filter, null) as TextView
            val params = FrameLayout.LayoutParams(mWidth, dp36)
            val marginNum = dp5
            var textMarginLeft = marginNum + (dp10 + mWidth) * (index % 2)
            Log.e("Tag", "----------left=$textMarginLeft")
            params.setMargins(textMarginLeft,
                    0,
                    marginNum,
                    marginNum)
            textView.layoutParams = params
            textView.text = showType.value
            showTypeViews.add(textView)

            if (showType == tempFilter!!.showType) {
                textView.isSelected = true
                textView.paint.isFakeBoldText = true
            }
            textView.setOnClickListener {

                if (!textView.isSelected) {
                    for (v in showTypeViews) {
                        v.isSelected = false
                        (v as TextView).paint.isFakeBoldText = false
                    }
                    textView.isSelected = true
                    textView.paint.isFakeBoldText = true
                    tempFilter!!.showType = showType
                }
                updateCount()
            }

            view.flShowType.addView(textView)
        }
    }

    override fun dismiss() {
        mDisposableList.clear()
        super.dismiss()
    }
}