package com.yidianling.consultant.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
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.data.PlatformDataManager
import com.ydl.ydlcommon.router.IYDLRouterConstant
import com.ydl.ydlcommon.utils.BuryPointUtils
import com.ydl.ydlcommon.utils.URLUtils
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.ydl.ydlcommon.utils.remind.ToastHelper
import com.yidianling.common.tools.LogUtil
import com.yidianling.common.tools.RxImageTool
import com.yidianling.consultant.ExpertSearchActivity
import com.yidianling.consultant.IExpertSearchView
import com.yidianling.consultant.R
import com.yidianling.consultant.constants.ConsultBIConstants
import com.yidianling.consultant.model.bean.DoctorServiceItem
import com.yidianling.consultant.modular.utils.TempH5RouteUtils
import com.yidianling.consultant.router.ConsultantIn
import kotlinx.android.synthetic.main.consultant_expert_search_feedbackrate.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.*

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

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

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

    var hasMore = true

    var pageIndex: Int = 0

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

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
        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.name

            //服务中
            if (itemBean.inConsult || itemBean.isListening) {
                holder.imgHead_online_server.visibility = View.VISIBLE
                holder.chat_people_in_question.visibility = View.GONE
                holder.imgHead_online.visibility = View.GONE
            } else {
                //不是服务中且问询人数大于0
                if (itemBean.chatNum > 5) {
                    holder.chat_people_in_question.visibility = View.VISIBLE
                    holder.chat_people_in_question.text = "多人在问询"
                } else if (itemBean.chatNum > 0) {
                    holder.chat_people_in_question.visibility = View.VISIBLE
                    holder.chat_people_in_question.text = "${itemBean.chatNum}人在问询"
                } else {
                    holder.chat_people_in_question.visibility = View.GONE
                }
                //可预约
                holder.imgHead_online_server.visibility = View.GONE
                if (itemBean.isTodayFree == true) {
                    holder.imgHead_online.visibility = View.VISIBLE
                } else {
                    holder.imgHead_online.visibility = View.GONE
                }
            }


            //省市
            if (!TextUtils.isEmpty(itemBean.province)) {
                holder.tvCity.text = itemBean.province + "·" + itemBean.city
            } else {
                holder.tvCity.text = ""
            }

            //公益图标,不与其他图标冲突
            if (1 == itemBean.hasServiceFree) {
                if (null != itemBean.tagsIcon && !TextUtils.isEmpty(itemBean.tagsIcon.serviceFreeIcon)) {
                    expertSearchView.showImage(
                        itemBean.tagsIcon.serviceFreeIcon,
                        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.tagsIcon?.fightEpidemicIcon?.let {
                    GlideApp.with(context).load(itemBean.tagsIcon?.fightEpidemicIcon)
                        .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
                //能力等级标签
                if (1 == itemBean.abilityLevel) {
                    //实习
                    holder.imgAbilityLevel.background =
                        context.resources.getDrawable(R.drawable.consultant_expert_search_shixi)
                    holder.imgAbilityLevel.visibility = View.VISIBLE
                } else if (2 == itemBean.abilityLevel) {
                    //新手
                    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.isNewEnter) {
                    if (null != itemBean.tagsIcon && !TextUtils.isEmpty(itemBean.tagsIcon.newEnterIcon)) {
                        expertSearchView.showImage(
                            itemBean.tagsIcon.newEnterIcon,
                            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.feedbackRate >= num) {
                    (view.imgRate as ImageView).background =
                        context.resources.getDrawable(R.drawable.consultant_expert_search_full_star)
                } else if (itemBean.feedbackRate < num && itemBean.feedbackRate > 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.zixunOrderNum).append("").toString()
            //咨询师简介
            holder.tvTeamCertifications.text = itemBean.teamCertifications
            //咨询师标签
            holder.ll_tags.removeAllViews()
            if (!TextUtils.isEmpty(itemBean.tags)) {
                val tagList = itemBean.tags!!.split("|")
                for (tag in tagList) {
                    if (!TextUtils.isEmpty(tag)) {
                        val view = LayoutInflater.from(context)
                            .inflate(R.layout.consultant_item_tag, holder.ll_tags, false)
                        view.tvTag.text = tag
                        holder.ll_tags.addView(view)
                    }
                }
            }
            //帮助人数
            val orderUser = StringBuffer()
            holder.tvOrderNum.text = orderUser.append(itemBean.zixunOrderUser).append("").toString()
            //私聊文案
            if (TextUtils.isEmpty(itemBean.chatBtnText)) {
                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.chatBtnText
                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.allSaleDuration.toInt()).append("").toString()
            //价格
            val sb = StringBuffer()
            holder.tvPrice.text = sb.append("").append(itemBean.minBookingPrice).toString()
            //套餐
            holder.ll_products.removeAllViews()
            if (null != itemBean.products && !itemBean.products.isEmpty()) {
                for (item in itemBean.products) {
                    val view = LayoutInflater.from(context).inflate(
                        R.layout.consultant_expert_search_products_item,
                        holder.ll_tags,
                        false
                    )
                    if (1 == item.isPackage) {
                        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.name
                        holder.ll_products.addView(view)
                    } else if (2 == item.isPackage) {
                        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.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) {
            listData.size
        } else {
            listData.size + 1
        }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder =
        when (viewType) {
            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 < 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.linkUrl

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

                    if (pageIndex == 0) {
                        ActionCountUtils.count(
                            ConsultBIConstants.ConsultEvent.APP_CONSULT_LIST_DOCTOR_CLICK,
                            itemBean.doctorId ?: ""
                        )
                    } else {
                        ActionCountUtils.count(
                            ConsultBIConstants.ConsultSearchListEvent.APP_CONSULT_SEARCH_LIST_CONSULT_ITEM_CLICK,
                            itemBean.doctorId ?: ""
                        )
                    }

                    TempH5RouteUtils.tempH5Route(linkUrl)
                }
            }

            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.doctorId ?: ""
                        )
                    } else {
                        ActionCountUtils.count(
                            ConsultBIConstants.ConsultSearchListEvent.APP_CONSULT_SEARCH_LIST_CHAT_CLICK,
                            doctor.doctorId ?: ""
                        )
                    }
                    //判断是否已登录
                    if (!ConsultantIn.getUserImpl().isLogin()) {
                        TempH5RouteUtils.tempH5Route(IYDLRouterConstant.ROUTER_MINE_LOGIN)
                        return@setOnClickListener
                    }


                    if (!TextUtils.isEmpty(doctor.uid)) {
                        //跳转私聊
                        ConsultantIn.startP2PSession(context as AppCompatActivity, doctor.uid!!)
                    } else {
                        ToastHelper.show("请联系客服,专家参数错误！")
                    }
                }
            }
        }
    }

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