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 android.widget.ImageView
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.ydl_image.module.GlideApp
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_feedbackrate.view.*
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_expert_search_products_item.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) {           //  搜索结果提示头部
            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
                            }
                        }
                    }
                }
            }
        } else if (holder is 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
            )
            //姓名
            holder.tvName.text = itemBean.doctor_name

            //服务中
            if (itemBean.open_chat_agency == 2 && itemBean.service_status == 2) {
                holder.imgHead_online_server.visibility = View.VISIBLE
                holder.chat_people_in_question.visibility = View.GONE
                holder.imgHead_online.visibility = View.GONE
            } else {
                //不是服务中且问询人数大于0
                when {
                    itemBean.chat_num > 5 -> {
                        holder.chat_people_in_question.visibility = View.VISIBLE
                        holder.chat_people_in_question.text = "多人在问询"
                    }
                    itemBean.chat_num > 0 -> {
                        holder.chat_people_in_question.visibility = View.VISIBLE
                        holder.chat_people_in_question.text = "${itemBean.chat_num}人在问询"
                    }
                    else -> {
                        holder.chat_people_in_question.visibility = View.GONE
                    }
                }
                //可预约
                holder.imgHead_online_server.visibility = View.GONE
                if (itemBean.is_free_today== 1) {
                    holder.imgHead_online.visibility = View.VISIBLE
                } else {
                    holder.imgHead_online.visibility = View.GONE
                }
            }


            //省市
            if (!TextUtils.isEmpty(itemBean.display_region)) {
                holder.tvCity.text = itemBean.display_region
            } else {
                holder.tvCity.text = ""
            }

            //公益图标,不与其他图标冲突
            if (1 == itemBean.has_servicefree_experience) {
                if (null != itemBean.icons && !TextUtils.isEmpty(itemBean.icons.service_free_icon)) {
                    expertSearchView.showImage(
                        itemBean.icons.service_free_icon,
                        holder.imgServiceFree
                    )
                } else {
                    val sp = SimpleImageOpConfiger()
                    sp.loadingPic = R.drawable.consultant_service_free
                    sp.errorPic = R.drawable.consultant_service_free
                    expertSearchView.showImage("", holder.imgServiceFree, sp)
                }
                holder.imgServiceFree.visibility = View.VISIBLE
            } else {
                holder.imgServiceFree.visibility = View.GONE
            }
            // 展示了抗疫，就不展示其他标签
            if (itemBean.fightEpidemicIconShow) {
                itemBean.icons?.fight_epidemic_icon?.let {
                    GlideApp.with(context).load(itemBean.icons?.fight_epidemic_icon)
                        .into(holder.imgFightEpidemicIcon)
                    holder.imgFightEpidemicIcon.visibility = View.VISIBLE
                }

                if (itemBean.joinActivity == true) {
                    //活动图标
                    if (!TextUtils.isEmpty(itemBean.activityImg)) {
                        holder.imgActivity.visibility = View.VISIBLE
                        GlideApp.with(context).load(itemBean.activityImg).into(holder.imgActivity)
                    } else {
                        holder.imgActivity.visibility = View.GONE
                    }
                } else {
                    holder.imgActivity.visibility = View.GONE
                }

                //影藏其余所有标签（除公益）
                holder.imgAbilityLevel.visibility = View.GONE
                holder.imgNewEnter.visibility = View.GONE
            } else {
                holder.imgFightEpidemicIcon.visibility = View.GONE
                //能力等级标签
                when (itemBean.abilityLevel) {
                    1 -> {
                        //实习
                        holder.imgAbilityLevel.background =
                            context.resources.getDrawable(R.drawable.consultant_expert_search_shixi)
                        holder.imgAbilityLevel.visibility = View.VISIBLE
                    }
                    2 -> {
                        //新手
                        holder.imgAbilityLevel.background =
                            context.resources.getDrawable(R.drawable.consultant_expert_search_xinshou)
                        holder.imgAbilityLevel.visibility = View.VISIBLE
                    }
                    else -> {
                        holder.imgAbilityLevel.visibility = View.GONE
                    }
                }
                //活动图标
                if (!TextUtils.isEmpty(itemBean.activityImg)) {
                    holder.imgActivity.visibility = View.VISIBLE
                    GlideApp.with(context).load(itemBean.activityImg).into(holder.imgActivity)
                } else {
                    holder.imgActivity.visibility = View.GONE
                }
                //新驻图标
                if (itemBean.is_new_enter != null && itemBean.is_new_enter!!) {
                    if (null != itemBean.icons && !TextUtils.isEmpty(itemBean.icons.new_enter_icon)) {
                        expertSearchView.showImage(
                            itemBean.icons.new_enter_icon,
                            holder.imgNewEnter
                        )
                    } else {
                        val sp = SimpleImageOpConfiger()
                        sp.loadingPic = R.drawable.consultant_new_enter
                        sp.errorPic = R.drawable.consultant_new_enter
                        expertSearchView.showImage("", holder.imgNewEnter, sp)
                    }
                    holder.imgNewEnter.visibility = View.VISIBLE
                } else {
                    holder.imgNewEnter.visibility = View.GONE
                }
            }
            holder.ll_feedbackRate.removeAllViews()
            for (num in 1..5) {
                val view = LayoutInflater.from(context).inflate(
                    R.layout.consultant_expert_search_feedbackrate,
                    holder.ll_feedbackRate,
                    false
                )
                if (itemBean.evaluation_average_score >= num) {
                    (view.imgRate as ImageView).background =
                        context.resources.getDrawable(R.drawable.consultant_expert_search_full_star)
                } else if (itemBean.evaluation_average_score < num && itemBean.evaluation_average_score > num - 1) {
                    (view.imgRate as ImageView).background =
                        context.resources.getDrawable(R.drawable.consultant_expert_search_half_star)
                } else {
                    (view.imgRate as ImageView).background =
                        context.resources.getDrawable(R.drawable.consultant_expert_search_nothing_star)
                }
                holder.ll_feedbackRate.addView(view)
            }
            //XXX人点评
            val numSb = StringBuffer()
            holder.tv_zixunOrderNum.text =
                numSb.append(itemBean.evaluate_num).append("").toString()
            //咨询师简介
            holder.tvTeamCertifications.text = itemBean.title
            //咨询师标签
            holder.ll_tags.removeAllViews()
            itemBean.feature_tags?.let {
                if (it.isNotEmpty()) {
                    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 ->
                            if (name.length > 4) {
                                view.tvTag.text = "${name.substring(0, 4)}…"
                            } else {
                                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.platform_color_666666
                                )
                            )
                        }
                        holder.ll_tags.addView(view)
                    }
                }
            }
            //帮助人数
            val orderUser = StringBuffer()
            holder.tvOrderNum.text = orderUser.append(itemBean.help_num).append("").toString()
            //私聊文案
            if (TextUtils.isEmpty(itemBean.chat_btn_text)) {
                holder.tvChat.text = "私聊"
                holder.tvChat.setTextColor(
                    ContextCompat.getColor(
                        context,
                        R.color.platform_but_text_color
                    )
                )
                holder.tvChat.setTextColor(
                    ContextCompat.getColor(
                        context,
                        R.color.platform_but_text_color
                    )
                )
                holder.tvChat.background =
                    ContextCompat.getDrawable(context, R.drawable.consultant_expert_search_chat)
            } else {
                holder.tvChat.text = itemBean.chat_btn_text
                holder.tvChat.setTextColor(
                    ContextCompat.getColor(
                        context,
                        R.color.platform_color_999999
                    )
                )
                holder.tvChat.background = ContextCompat.getDrawable(
                    context,
                    R.drawable.consultant_expert_search_chat_rest
                )
            }
            //服务时长
            val durationStringBuffer = StringBuffer()
            holder.tvSaleDurationForMonth.text =
                durationStringBuffer.append(itemBean.sum_service_time.toInt()).append("").toString()
            //价格
            val price = BigDecimal(itemBean.min_price)
//             去掉末尾无用的.00
            holder.tvPrice.text = price.stripTrailingZeros().toPlainString()
            //套餐
            holder.ll_products.removeAllViews()
            if (null != itemBean.doctor_products && itemBean.doctor_products.isNotEmpty()) {
                for (item in itemBean.doctor_products) {
                    val view = LayoutInflater.from(context).inflate(
                        R.layout.consultant_expert_search_products_item,
                        holder.ll_tags,
                        false
                    )
                    when (item.product_type) {
                        "1" -> {
                            view.tvTitle.text = "单次"
                            view.tvTitle.setTextColor(context.resources.getColor(R.color.platform_color_1DA1F2))
                            view.tvTitle.background =
                                context.resources.getDrawable(R.drawable.consultant_expert_search_single)
                            view.tvContent.text = item.product_name
                            holder.ll_products.addView(view)
                        }
                        "2" -> {
                            view.tvTitle.text = "套餐"
                            view.tvTitle.setTextColor(context.resources.getColor(R.color.consultant_color_FF9500))
                            view.tvTitle.background =
                                context.resources.getDrawable(R.drawable.consultant_expert_search_menu)
                            view.tvContent.text = item.product_name
                            holder.ll_products.addView(view)
                        }
                        else -> {

                        }
                    }
                }
            }
        } else if (holder is 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)
            }
        }
    }

    override fun getItemCount(): Int =
//        if (listData.size < ExpertSearchActivity.PAGE_SIZE && hasMore) {
        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 cv_head_view = itemView.cv_head_view!!

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

        //活动图标
        val imgActivity = itemView.img_activity!!

        //优质图标
        val imgAbilityLevel = itemView.imgAbilityLevel!!

        //公益图标
        val imgServiceFree = itemView.imgServiceFree!!

        //新驻图标
        val imgNewEnter = itemView.imgNewEnter!!

        //荣誉标签
        val ll_honor_layout = itemView.ll_honor_layout!!

        //好评率
        val ll_feedbackRate = itemView.ll_feedbackRate!!

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

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

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

        //帮助人数
        val tvOrderNum = itemView.tvOrderNum!!

        //帮助人数文案
        val tvOrderNumContent = itemView.tvOrderNumContent

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

        //月售时长文案
        val tvSaleDurationForMonthContent = itemView.tvSaleDurationForMonthContent

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

        //服务套餐
        val ll_products = itemView.ll_products!!

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

        //个人铭言整个布局
        val group_desc = itemView.group_desc!!

        //个人铭言
        val tvDesc = itemView.tvDesc!!

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

        //今日是否可约
        val imgHead_online = itemView.imgHead_online!!

        //服务中（咨询中或者聆听中）
        val imgHead_online_server = itemView.imgHead_online_server!!

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

        // 抗疫先锋图标
        val imgFightEpidemicIcon = itemView.img_fightEpidemicIcon

        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.tvChat.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)
        }
    }
}