package com.yidianling.consultant.adapter

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.Typeface
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextUtils
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.ydl.webview.H5Params
import com.ydl.webview.NewH5Activity
import com.ydl.ydl_image.config.SimpleImageOpConfiger
import com.ydl.ydlcommon.base.config.HttpConfig
import com.ydl.ydlcommon.modular.findRouteService
import com.ydl.ydlcommon.utils.URLUtils
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.ydl.ydlcommon.utils.remind.ToastHelper
import com.ydl.ydlcommon.view.dialog.CommonDialog
import com.yidianling.consultant.IExpertSearchView
import com.yidianling.consultant.R
import com.yidianling.consultant.constants.ConsultBIConstants
import com.yidianling.consultant.listener.OnExpertClickListener
import com.yidianling.consultant.model.bean.ExpertServiceItem
import com.yidianling.consultant.modular.utils.TempH5RouteUtils
import com.yidianling.consultant.router.ConsultantIn
import com.yidianling.user.api.service.IUserService
import kotlinx.android.synthetic.main.consultant_expert_search_header_view.view.*
import kotlinx.android.synthetic.main.consultant_expert_search_item_view.view.*
import kotlinx.android.synthetic.main.consultant_item_empty.view.*
import kotlinx.android.synthetic.main.consultant_item_footer.view.*
import kotlinx.android.synthetic.main.consultant_item_tag.view.*
import java.math.BigDecimal

/**
 * 专家服务列表适配器
 */
class ExpertSearchAdapter(
    private val context: Context,
    private val expertSearchView: IExpertSearchView,
    private val listData: ArrayList<ExpertServiceItem>,
    private val onExpertClick: OnExpertClickListener? = null
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    companion object {
        const val HEADER_VIEW = 3
        const val NORMAL_VIEW = 0
        const val FOOT_VIEW = 1
        const val EMPTY_VIEW = 2
    }

    interface OnClickLister {
        fun onClick(searchWords: String)
    }

    private lateinit var mOnClickLister: OnClickLister

    fun setOnClickLister(lister: OnClickLister) {
        mOnClickLister = lister
    }

    //记录当前选择主题的id
    var cateId: String? = null

    var hasMore = true

    var pageIndex: Int = 0
    var clickCount = 0                    // 搜索结果提示标签点击次数

    var mIsRecommendWords = false       // 是否是推荐词

    fun setEntrance(pageIndex: Int) {
        this.pageIndex = pageIndex
    }

    fun setIsRecommendWords(isRecommend: Boolean) {
        mIsRecommendWords = isRecommend
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is HeaderViewHolder) {
            //  搜索结果提示头部
            bindHeaderView(holder)
        } else if (holder is NormalViewHolder) {

            bindNormalView(position, holder)

        } else if (holder is FooterViewHolder) {
            bindFooterView(holder)
        }
    }

    /**底部布局*/
    private fun bindFooterView(holder: FooterViewHolder) {
        if (hasMore) {
            holder.itemView.visibility = View.VISIBLE
            holder.pbLoading.visibility = View.VISIBLE
            holder.tvHint.text = context.getString(R.string.consultant_loading)
        } else {
            holder.pbLoading.visibility = View.GONE
            holder.tvHint.text = context.getString(R.string.platform_no_more)
        }
    }

    /**item布局*/
    private fun bindNormalView(position: Int, holder: NormalViewHolder) {
        val itemBean = listData[position]
        //头像
        val headConfig = SimpleImageOpConfiger()
        headConfig.loadingPic = R.drawable.consultant_avatar_def_circle
        headConfig.errorPic = R.drawable.consultant_avatar_def_circle
        expertSearchView.showImage(
            itemBean.head,
            holder.imgHead,
            holder.imgHead.width,
            holder.imgHead.height,
            headConfig
        )

        //咨询显示状态：1.忙碌；2.现在有空；3.今日可约；4.最近可约；5.已约满；6.休息中
        when (itemBean.consult_display_status) {
            6 -> {
                holder.consult_display_status_str.setBackgroundColor(
                    ContextCompat.getColor(
                        context,
                        R.color.color_b6bece_90
                    )
                )
            }
            5, 1 -> {
                holder.consult_display_status_str.setBackgroundColor(
                    ContextCompat.getColor(
                        context,
                        R.color.color_f5a082_90
                    )
                )
            }
            else -> {
                holder.consult_display_status_str.setBackgroundColor(
                    ContextCompat.getColor(
                        context,
                        R.color.color_6ec8f9_90
                    )
                )
            }
        }
        //专家头像下方文案：如 忙碌；现在有空；今日可约；最近可约；已约满；休息中
        holder.consult_display_status_str.text = itemBean.consult_display_status_str

        //姓名
        holder.tvName.text = itemBean.doctor_name
        //年审
        if (!TextUtils.isEmpty(itemBean.audit_tag)) {
            holder.audit_tag.visibility = View.VISIBLE
            holder.audit_tag.text = itemBean.audit_tag
        } else {
            holder.audit_tag.visibility = View.GONE
        }
        //省市
        if (!TextUtils.isEmpty(itemBean.display_region)) {
            holder.tvCity.text = itemBean.display_region
            holder.tvCity.visibility = View.VISIBLE
        } else {
            holder.tvCity.visibility = View.GONE
        }
        //咨询师tag
        holder.tvTeamCertifications.text = itemBean.title

        //服务时长  经验
        val durationStringBuffer = StringBuffer()
        holder.tvSaleDurationForMonth.text =
            durationStringBuffer.append(itemBean.sum_service_time.toInt()).append("小时").toString()

        //口碑
        val numSb = StringBuffer()
        holder.tv_zixunOrderNum.text =
            numSb.append(itemBean.evaluate_num).append("条").toString()

        //咨询师标签
        holder.ll_tags.removeAllViews()
        if (itemBean.feature_tags?.isNotEmpty() == true) {
            holder.ll_tags.visibility = View.VISIBLE
            for (tag in itemBean.feature_tags) {
                val view = LayoutInflater.from(context)
                    .inflate(R.layout.consultant_item_tag, holder.ll_tags, false)
                tag.tag_name.let { name ->
                    view.tvTag.text = name
                }
                if (tag.is_highlight) {
                    view.tvTag.setBackgroundResource(R.drawable.consultant_bg_radius_line_eb892c)
                    view.tvTag.setTextColor(
                        ContextCompat.getColor(
                            context,
                            R.color.color_EB892C
                        )
                    )
                } else {
                    view.tvTag.setBackgroundResource(R.drawable.consultant_bg_radius_line_gray_1)
                    view.tvTag.setTextColor(
                        ContextCompat.getColor(
                            context,
                            R.color.color_1c1f28_50
                        )
                    )
                }
                holder.ll_tags.addView(view)
            }
        } else {
            holder.ll_tags.visibility = View.GONE
        }

        //价格
        val price = BigDecimal(itemBean.min_price)
        //             去掉末尾无用的.00
        val priceStr = "¥" + price.stripTrailingZeros().toPlainString()
        holder.tvPrice.text = priceStr

        //服务方式
        holder.attr_combine.text = itemBean.attr_combine

        if (1 == itemBean.open_chat_agency) {
            //联系顾问
            holder.tvChat.text = "联系顾问"
            holder.card_chat.setCardBackgroundColor(
                ContextCompat.getColor(
                    context,
                    R.color.color_6ec8f9
                )
            )
        } else {
            //私聊状态：1.上线；2.离线；3.忙碌中
            when (itemBean.chat_status) {
                2, 3 -> {
                    holder.tvChat.text = "留 言"
                    holder.card_chat.setCardBackgroundColor(
                        ContextCompat.getColor(
                            context,
                            R.color.color_b6bece
                        )
                    )
                }
                else -> {
                    holder.tvChat.text = "私 聊"
                    holder.card_chat.setCardBackgroundColor(
                        ContextCompat.getColor(
                            context,
                            R.color.color_6ec8f9
                        )
                    )
                }

            }
        }

        //问询   可约
        var bottomDec = if (itemBean.chat_num > 0) {
            if (!TextUtils.isEmpty(itemBean.today_time_des)) {
                "${itemBean.chat_num}人在问询·${itemBean.today_time_des}"
            } else {
                "${itemBean.chat_num}人在问询"
            }
        } else {
            if (!TextUtils.isEmpty(itemBean.today_time_des)) {
                itemBean.today_time_des
            } else {
                ""
            }
        }

        if (TextUtils.isEmpty(bottomDec)) {
            holder.chat_people_in_question.visibility = View.GONE
        } else {
            holder.chat_people_in_question.visibility = View.VISIBLE
            holder.chat_people_in_question.text = bottomDec
        }

    }

    /**顶部根据匹配，为您推荐布局*/
    private fun bindHeaderView(holder: HeaderViewHolder) {
        if (listData.size > 0) {
            if (listData[0].is_head_view) {
                if (clickCount == 0) {
                    holder.clSearchWords.visibility = View.VISIBLE
                    var text = "根据匹配，为您推荐“${listData[0].related_word}”的搜索结果"
                    holder.tvSearchRelatedWord.text = setTextBold(text, listData[0].related_word)
                    holder.tvSearchWord.text = listData[0].search_content
                    // 埋点
                    if (mIsRecommendWords) {
                        ActionCountUtils.baiDuCountSign3(
                            ConsultBIConstants.PART_ID_YDL_USER_MAIN_PAGE,
                            "ydl_user_map_word_visit",
                            listData[0].search_content,
                            listData[0].related_word,
                            "app"
                        )
                    } else {
                        ActionCountUtils.baiDuCountSign3(
                            ConsultBIConstants.PART_ID_YDL_USER_MAIN_PAGE,
                            "ydl_user_correction_word_visit",
                            listData[0].search_content,
                            listData[0].related_word,
                            "app"
                        )
                    }
                    holder.tvSearchWord.setOnClickListener {
                        mOnClickLister.onClick(holder.tvSearchWord.text.toString())
                        ++clickCount
                        if (clickCount == 1) {
                            text = "以下是“${listData[0].search_content}”的搜索结果"
                            holder.tvSearchRelatedWord.text =
                                setTextBold(text, listData[0].search_content)
                            holder.tvSearchTips.text = "你要找的是不是"
                            holder.tvSearchWord.text = listData[0].related_word
                            // 埋点
                            if (mIsRecommendWords) {
                                ActionCountUtils.baiDuCountSign3(
                                    ConsultBIConstants.PART_ID_YDL_USER_MAIN_PAGE,
                                    "ydl_user_map_inputword_click",
                                    listData[0].related_word,
                                    listData[0].search_content,
                                    "app"
                                )
                            } else {
                                ActionCountUtils.baiDuCountSign3(
                                    ConsultBIConstants.PART_ID_YDL_USER_MAIN_PAGE,
                                    "ydl_user_correction_inputword_click",
                                    listData[0].related_word,
                                    listData[0].search_content,
                                    "app"
                                )
                            }
                        } else if (clickCount == 2) {    // 第二次点击搜索标签隐藏搜索匹配结果提示
                            // 埋点
                            if (mIsRecommendWords) {
                                ActionCountUtils.baiDuCountSign3(
                                    ConsultBIConstants.PART_ID_YDL_USER_MAIN_PAGE,
                                    "ydl_user_map_recommendword_click",
                                    listData[0].search_content,
                                    listData[0].related_word,
                                    "app"
                                )
                            } else {
                                ActionCountUtils.baiDuCountSign3(
                                    ConsultBIConstants.PART_ID_YDL_USER_MAIN_PAGE,
                                    "ydl_user_correction_recommendword_click",
                                    listData[0].search_content,
                                    listData[0].related_word,
                                    "app"
                                )
                            }
                            listData.removeAt(0)
                            clickCount = 0  // 点击两次后重置为0
                        }
                    }
                }
            }
        }
    }

    override fun getItemCount(): Int =
        if (listData.size == 1) {
            listData.size
        } else {
            listData.size + 1
        }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =
        when (viewType) {
            HEADER_VIEW -> {
                val view = LayoutInflater.from(context)
                    .inflate(R.layout.consultant_expert_search_header_view, parent, false)
                HeaderViewHolder(view)
            }
            NORMAL_VIEW -> {
                val view = LayoutInflater.from(context)
                    .inflate(R.layout.consultant_expert_search_item_view, parent, false)
                NormalViewHolder(view)
            }
            FOOT_VIEW -> {
                val view = LayoutInflater.from(context)
                    .inflate(R.layout.consultant_item_footer, parent, false)
                FooterViewHolder(view)
            }
            else -> {
                val view = LayoutInflater.from(context)
                    .inflate(R.layout.consultant_item_empty, parent, false)
                EmptyViewHolder(view)
            }
        }

    override fun getItemViewType(position: Int): Int =
        when {
            position == 0 && listData.size > 0 && listData[0].is_head_view -> {
                HEADER_VIEW
            }
            position < listData.size -> {
                NORMAL_VIEW
            }
            !hasMore && listData.size == 0 -> {
                EMPTY_VIEW
            }
            else -> FOOT_VIEW
        }

    inner class NormalViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        //头像
        val imgHead = itemView.imgHead!!

        //专家姓名
        val tvName = itemView.tvName!!

        //年审
        val audit_tag = itemView.audit_tag!!

        //头像下方文案
        val consult_display_status_str = itemView.consult_display_status_str!!

        //服务方式
        val attr_combine = itemView.attr_combine

        //xxx人点评
        val tv_zixunOrderNum = itemView.tv_zixunOrderNum!!

        //咨询师简介
        val tvTeamCertifications = itemView.tvTeamCertifications!!

        //咨询师标签
        val ll_tags = itemView.ll_tags!!

        //服务时长
        val tvSaleDurationForMonth = itemView.tvSaleDurationForMonth!!

        //价格
        val tvPrice = itemView.tvPrice!!

        //私聊按钮
        val tvChat = itemView.tvChat!!

        //私聊背景
        val card_chat = itemView.card_chat!!

        //省市
        val tvCity = itemView.tvCity!!

        //多少人在问询
        val chat_people_in_question = itemView.people_in_question!!


        init {
            itemView.setOnClickListener {
                //跳转专家主页
                if (adapterPosition != RecyclerView.NO_POSITION) {
                    val itemBean = listData[adapterPosition]
                    var linkUrl = itemBean.link_url

                    if (!TextUtils.isEmpty(cateId)) {
                        linkUrl = URLUtils.appendParmas(linkUrl, "cateId", cateId)
                    }
                    onExpertClick?.onExpertClick()
                    TempH5RouteUtils.tempH5Route(linkUrl)

                    // 埋点
                    ActionCountUtils.baiDuCountSign3(
                        ConsultBIConstants.PART_ID_CONSULT_COUNSELOR_LIST_PAGE,
                        ConsultBIConstants.ConsultEvent.POSITION_CONSULT_COUNSELOR_CARD_CLICK,
                        itemBean.id ?: "",
                        "app",
                        ""
                    )
                }
            }

            itemView.card_chat.setOnClickListener {
                if (adapterPosition != RecyclerView.NO_POSITION) {
                    val doctor = listData[adapterPosition]
                    if (pageIndex == 0) {
                        ActionCountUtils.count(
                            ConsultBIConstants.ConsultEvent.APP_CONSULT_LIST_CHAT_CLICK,
                            doctor.id ?: ""
                        )
                    } else {
                        ActionCountUtils.count(
                            ConsultBIConstants.ConsultSearchListEvent.APP_CONSULT_SEARCH_LIST_CHAT_CLICK,
                            doctor.id ?: ""
                        )
                    }
                    onExpertClick?.onExpertClick()
                    //判断是否已登录
                    if (!ConsultantIn.getUserImpl().loginByOneKeyLogin(context, true)) {
                        return@setOnClickListener
                    }


                    if (!TextUtils.isEmpty(doctor.uid)) {
                        val userService = findRouteService(IUserService::class.java)
                        if (!userService.isBindPhone() && context is Activity) {
                            CommonDialog(context)
                                .setMessage("为了及时接收消息通知,请立即绑定手机")
                                .setLeftOnclick("忍痛放弃") {}
                                .setRightClick("果断绑定") {
                                    userService.wxBindToInputhonePage(context) // 跳转绑定手机号页面
                                }
                                .setCancelAble(false)
                                .show()
                            return@setOnClickListener
                        }
                        //跳转私聊
                        ConsultantIn.startP2PSession(context as AppCompatActivity, doctor.uid!!)
                        ActionCountUtils.count(ConsultBIConstants.UserMainEvent.YDL_PRIVATE_CHAT_CLICK)
                    } else {
                        ToastHelper.show("请联系客服,专家参数错误！")
                    }
                }
            }
        }
    }

    inner class HeaderViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val clSearchWords = itemView.cl_search_words
        val tvSearchRelatedWord = itemView.tv_search_related_word
        val tvSearchTips = itemView.tv_search_tips
        val tvSearchWord = itemView.tv_search_word
    }

    inner class FooterViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val pbLoading = itemView.pbLoading!!
        val tvHint = itemView.tvHint!!
    }

    inner class EmptyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val btnSearchByCat = itemView.btnSearchByCat!!

        init {
            btnSearchByCat.setOnClickListener {
                val h5Params = H5Params(HttpConfig.H5_URL + "experts/cates", null)
                NewH5Activity.start(context, h5Params)
            }
        }
    }

    private fun setTextBold(text: String, content: String): SpannableStringBuilder {
        return if (text.contains(content)) {
            val s1 = text.split(content)[0]
            val s2 = text.split(content)[1]
            val spannableBuilder1 = SpannableStringBuilder(s1)
            val spannableBuilder2 = SpannableStringBuilder(content)
            spannableBuilder2.setSpan(
                StyleSpan(Typeface.BOLD),
                0,
                content.length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            spannableBuilder1.append(spannableBuilder2).append(SpannableStringBuilder(s2))
        } else {
            SpannableStringBuilder(text)
        }
    }
}