package com.yidianling.home.ui.view

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.text.*
import android.text.style.ForegroundColorSpan
import android.text.style.ImageSpan
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import com.yidianling.home.R
import com.yidianling.home.event.IHomeBaseEvent
import com.yidianling.home.model.bean.HomeAskBean
import com.ydl.ydl_image.config.SimpleImageOpConfiger
import com.ydl.ydl_image.manager.YDLImageCacheManager
import com.ydl.ydlcommon.modular.ModularServiceManager
import com.ydl.ydlcommon.utils.MoonUtil
import com.ydl.ydlcommon.utils.Utils
import com.yidianling.common.tools.RxDeviceTool
import com.yidianling.common.tools.RxImageTool
import com.yidianling.user.api.service.IUserService
import kotlinx.android.synthetic.ydl.home_assuage_grief_item_view.view.*


/**
 * @author <a href="https://www.jianshu.com/u/c1e5310dd724">xujian</a>
 * @描述: 解忧*问答模块item
 * @Copyright Copyright (c) 2019
 * @Company 壹点灵
 * @date 2019/02/15
 */
class HomeAssuageGriefItemView(private val mContext: Context, private var homeEvent: IHomeBaseEvent?) : LinearLayout(mContext) {

    private var homeAssuageGriefImageItemView: HomeAssuageGriefImageItemView? = null
    private var focusClick: Boolean = false;

    init {
        initView()
    }

    private fun initView() {
        val params = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        params.setMargins((15 * RxDeviceTool.getScreenDensity(mContext)).toInt()
                , (0 * RxDeviceTool.getScreenDensity(mContext)).toInt()
                , (15 * RxDeviceTool.getScreenDensity(mContext)).toInt()
                , (16 * RxDeviceTool.getScreenDensity(mContext)).toInt())
        layoutParams = params
        View.inflate(mContext, R.layout.home_assuage_grief_item_view, this)


    }

    fun updateData(bean: HomeAskBean.DataBean, position: Int, index: Int) {
        this.setOnClickListener {
            homeEvent?.askItemClick(bean)
        }
        val op = SimpleImageOpConfiger()
        op.errorPic = R.drawable.platform_head_place_hold_pic
        op.loadingPic = R.drawable.platform_head_place_hold_pic
        YDLImageCacheManager.showImage(mContext, bean?.header, homeModuleAssuageGriefViewPersonImg, op)
        homeModuleAssuageGriefViewPersonName.text = bean?.name
        homeModuleAssuageGriefViewTime.text = bean?.timeStr
        MoonUtil.identifyFaceExpression(mContext, homeModuleAssuageGriefViewContent,
                bean?.content, ImageSpan.ALIGN_BOTTOM)
        homeModuleAssuageGriefViewTag.text = bean?.askTag
        homeModuleAssuageGriefViewCommentsCount.text = bean?.commentsCount.toString()
        homeModuleAssuageGriefViewZanCount.text = bean?.zanCount.toString()
        ll_topic_detail.setOnClickListener {
            //跳转话题详情
            homeEvent?.jumpToTopicDetail(bean.topicId.toString())
        }

        /**
         * 点赞
         */
        ll_zan.setOnClickListener {
            //防止连击
            if (!Utils.isFastClick()) {
                if (!ModularServiceManager.provide(IUserService::class.java).loginByOneKeyLogin(mContext,true)) {
                    //判断登录状态内部已完成 跳转登录
                    return@setOnClickListener
                }
                bean.isZan = if (bean.isZan == 1 ) 0 else 1

                if (bean.isZan == 1) {
                    homeModuleAssuageGriefViewIsZan.progress = 0f
                    homeModuleAssuageGriefViewIsZan.visibility = View.VISIBLE
                    homeModuleAssuageGriefViewIsNotZan.visibility = View.GONE
                    homeModuleAssuageGriefViewIsZan.playAnimation()
                } else {
                    homeModuleAssuageGriefViewIsZan.visibility = View.GONE
                    homeModuleAssuageGriefViewIsNotZan.visibility = View.VISIBLE
                }

                bean.zanCount =  if (bean.isZan == 1 ) bean.zanCount+1 else bean.zanCount-1
                homeModuleAssuageGriefViewZanCount.text = bean?.zanCount.toString()
                homeEvent?.askItemZanClick(position, index, bean.id.toString())
            }
        }

        homeModuleAssuageGriefItemViewIsFollow.setOnClickListener {
            //防止连击
            if (!Utils.isFastClick()) {
                if (bean.isFocused == 1) {
                    homeEvent?.askItemClick(bean)
                } else {
                    if (!ModularServiceManager.provide(IUserService::class.java).loginByOneKeyLogin(mContext,true)) {
                        //判断登录状态内部已完成 跳转登录
                        return@setOnClickListener
                    }
                    bean.isFocused = if(bean.isFocused == 1) 0 else 1
                    setFollowType(bean.isFocused == 1)
                    homeEvent?.askItemFocusClick(position, bean.uid.toString())
                }
            }
        }

        if (bean.uid == 0) {
            //匿名，隐藏关注按钮
            homeModuleAssuageGriefItemViewIsFollow.visibility = View.GONE
        } else {
            /**
             * 关注
             */
            if (bean.isFocused == 1) {
                setFollowType(true)
            } else {
                setFollowType(false)
            }
        }


        /**
         * 标题
         */
        if (!TextUtils.isEmpty(bean?.title)) {
            homeModuleAssuageGriefViewTitle.visibility = View.VISIBLE
            homeModuleAssuageGriefViewTitle.text = bean?.title
        }

        /**
         * 点赞
         */
        if (bean?.isZan == 1) {
            homeModuleAssuageGriefViewIsZan.visibility = View.VISIBLE
            homeModuleAssuageGriefViewIsZan.progress = 1.0f
            homeModuleAssuageGriefViewIsNotZan.visibility = View.GONE
        } else {
            homeModuleAssuageGriefViewIsZan.visibility = View.GONE
            homeModuleAssuageGriefViewIsNotZan.visibility = View.VISIBLE
        }

        /**
         * 图片
         */
        if (null != bean?.smallAttach && bean?.smallAttach!!.isNotEmpty()) {
            if (homeAssuageGriefImageItemView != null) {
                homeModuleAssuageGriefViewChildLayout.removeView(homeAssuageGriefImageItemView)
            }
            homeAssuageGriefImageItemView = HomeAssuageGriefImageItemView(mContext, bean?.smallAttach as List<String>, homeEvent)
            homeModuleAssuageGriefViewChildLayout.addView(homeAssuageGriefImageItemView, 1)
        } else {
            if (null != homeAssuageGriefImageItemView) {
                homeModuleAssuageGriefViewChildLayout.removeView(homeAssuageGriefImageItemView)
            }
        }

        /**
         * 评论
         */
        initComment(bean)

    }

    private fun setFollowType(boolean: Boolean) {
        if (boolean) {
            homeModuleAssuageGriefItemViewFollow.visibility = View.VISIBLE
            homeModuleAssuageGriefItemViewUnFollow.visibility = View.GONE
        } else {
            homeModuleAssuageGriefItemViewFollow.visibility = View.GONE
            homeModuleAssuageGriefItemViewUnFollow.visibility = View.VISIBLE
        }
    }

    private fun initComment(bean: HomeAskBean.DataBean) {
        if (bean?.commentsCount > 0) {
            homeModuleAssuageGriefViewComment.visibility = View.VISIBLE

            var index: Int = 0
            var commentBean = bean?.comments!![0]

            if (null != commentBean.name && commentBean.name!!.isNotEmpty())
                setPartTextColor(homeModuleAssuageGriefViewHotViewComment, commentBean.name,
                        0, commentBean.name?.length!!, Color.parseColor("#1DA1F2"))

            // userType为2 ，专家
            if (commentBean.userType == 2) {
                setImage(mContext, homeModuleAssuageGriefViewHotViewComment, "vip",
                        R.drawable.home_assuage_grief_item_user_type_v,
                        RxImageTool.dp2px(13f),
                        RxImageTool.dp2px(13f))
            }

            setAppendPartTextColor(homeModuleAssuageGriefViewHotViewComment, "：",
                    0,
                    1
                    , Color.parseColor("#1DA1F2"))

            MoonUtil.identifyFaceExpression(mContext, homeModuleAssuageGriefViewHotViewCommentContent,
                    commentBean.content, ImageSpan.ALIGN_BOTTOM)

            var emptyString = ""
            if (null != commentBean.name && commentBean.name!!.isNotEmpty()) {
                if (commentBean.userType == 2) {
                    emptyString += "缩"
                }
                for (index in 0 until commentBean.name!!.length) {
                    emptyString += commentBean.name!![index]
                }
                emptyString += "缩"
            }

            val span = SpannableStringBuilder(emptyString + homeModuleAssuageGriefViewHotViewCommentContent.text)
            span.setSpan(ForegroundColorSpan(Color.TRANSPARENT), 0, emptyString.length,
                    Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
            homeModuleAssuageGriefViewHotViewCommentContent.text = span

        }
    }

    fun setPartTextColor(textView: TextView, text: String?,
                         start: Int, end: Int, colorId: Int) {
        var ss: SpannableString = SpannableString(text)
        ss.setSpan(ForegroundColorSpan(colorId), start, end,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        textView.text = ss
    }

    fun setAppendPartTextColor(textView: TextView, text: String?,
                               start: Int, end: Int, colorId: Int) {
        var ss: SpannableString = SpannableString(text)
        ss.setSpan(ForegroundColorSpan(colorId), start, end,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        textView.append(ss)
    }

    fun setImage(context: Context, textView: TextView, bitmapText: String, resId: Int, width: Int, height: Int) {
        var ss: SpannableString = SpannableString(bitmapText)
        var drawable: Drawable = context.resources.getDrawable(resId)
        drawable.setBounds(0, 0, width, height)
        var imageSpan: ImageSpan = ImageSpan(drawable, ImageSpan.ALIGN_BASELINE)
        ss.setSpan(imageSpan, 0, bitmapText.length,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        textView.append(ss)
    }
}