package com.zj365.health.adapter

import android.text.Html
import android.text.Spannable
import android.text.SpannableString
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter
import com.chad.library.adapter.base.entity.MultiItemEntity
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.tamsiree.rxkit.RxTimeTool
import com.xty.base.utils.UserInfoDefin
import com.xty.common.MyImageGetter
import com.xty.common.weight.CenterImageSpan
import com.xty.common.weight.VisceraView
import com.zj365.health.R
import com.zj365.health.model.ReportMultiItemEntity
import com.xty.network.model.ReportBean
import java.lang.StringBuilder

class Health24HourAdapter<T : MultiItemEntity> : BaseMultiItemQuickAdapter<T, BaseViewHolder>() {
    var recycle: RecyclerView? = null

    init {
        addItemType(0, R.layout.item_status_0)
        addItemType(1, R.layout.item_status_1)
        addItemType(2, R.layout.item_status_2)
        addItemType(3, R.layout.item_status_2)
    }

    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        super.onAttachedToRecyclerView(recyclerView)
        recycle = recyclerView
    }

    override fun convert(holder: BaseViewHolder, item: T) {
        var reportBean = (item as ReportMultiItemEntity).bean
        when (item.itemType) {
            //头部健康状态星级评分报告时间信息设置
            0 -> {
                reportBean?.let { setHealthStatuAndStarInfo(holder, it) }
                //目前不用服务器时间，改为当前时间取整十分的时间
                var time = RxTimeTool.getCurrentDateTime("mm").toInt()
                var sPrefix = String.format("%02d", time / 10 * 10)  //当前时间对应的整分钟数
                var nowTimeStr = RxTimeTool.getCurrentDateTime("MM-dd HH") + ":${sPrefix}" //整点时间
                holder.setText(
                    R.id.mTvTime,
                    "${RxTimeTool.getYestoryDate("MM-dd HH")}:${sPrefix} 至 $nowTimeStr"
                )
            }
            //12器官健康状态信息
            1 -> {

                reportBean?.let {
                    it.healthy?.result?.let { it1 ->
                        it.user?.sex?.let { it2 ->
                            setBody(
                                holder, it1,
                                it2
                            )
                        }
                    }
                    setStatus(holder, it.organ)
                }
            }
            //富文本中医分析信息
            2 -> {
                var sb = StringBuilder()
                reportBean?.let {
                    if (!it.analysis.TcmAnalysis.isNullOrEmpty()) {
                        it.analysis.TcmAnalysis!!.forEach { it ->
                            sb.append(it.dictName).append("\n")
                            sb.append(it.content).append("\n")
                        }
                    } else {
                        sb.append("暂无数据")
                    }
                }
                holder.setText(R.id.mTitle, "中医分析")


                var tv = holder.getView<TextView>(R.id.mContent)
                var getter = MyImageGetter(context, tv)
                tv.text = Html.fromHtml(sb.toString().trim(), getter, null)
            }

            //富文本西医分析信息
            3 -> {
                var sb = StringBuilder()
                reportBean?.let {
                    if (!it.analysis.WmAnalysis.isNullOrEmpty()) {
                        it.analysis.WmAnalysis?.forEachIndexed { index, bean ->
                            if (bean.dictName != "考虑症状") {
                                sb.append(
                                    String.format(
                                        context.getString(R.string.analysis_desc),
                                        bean.dictName,
                                        bean.name
                                    )
                                ).append("\n")
                                sb.append(
                                    String.format(
                                        context.getString(R.string.analysis_name),
                                        bean.name
                                    )
                                ).append("\n")
                                sb.append(bean.content).append("\n")
                            }
                        }

                        it.analysis.WmAnalysis?.forEachIndexed { index, bean ->
                            if (bean.dictName == "考虑症状") {
                                sb.append(
                                    String.format(
                                        context.getString(R.string.analysis_agree),
                                        "${bean.dictName}${bean.name}？"
                                    )
                                ).append("\n")
                                sb.append(bean.content).append("\n")
                            }

                        }
                    } else {
                        sb.append("身体健康，请继续保持")
                    }

                }


                holder.setText(R.id.mTitle, "西医分析")
                var tv = holder.getView<TextView>(R.id.mContent)
                var getter = MyImageGetter(context, tv)
                tv.text = Html.fromHtml(sb.toString().trim(), getter, null)
            }

        }

        if (holder.layoutPosition == 3) {
            holder.itemView.post {
                recycle?.let {
                    var needHeight = it.height
                    if (holder.itemView.height < needHeight) {
                        val layoutParams = holder.itemView.layoutParams as ViewGroup.LayoutParams
                        layoutParams.height = needHeight
                        holder.itemView.layoutParams = layoutParams
                    }
                }
            }
        }
    }

    /**
     * 设置健康状态以及星级评价
     */
    private fun setHealthStatuAndStarInfo(holder: BaseViewHolder, reportBean: ReportBean) {
        var statusInt = if (reportBean.healthy == null) 0 else reportBean.healthy.result
        val mHealthStatus = holder.getView<ImageView>(R.id.mHealthStatus)
        mHealthStatus.setImageResource(UserInfoDefin.healthIcon[statusInt + 1])
        holder.getView<TextView>(R.id.mTvStatus).apply {
            var statusInt = if (reportBean.healthy == null) 0 else reportBean.healthy.result
            tag = statusInt
            var star = if (reportBean.star.isNullOrEmpty()) 0 else Integer.valueOf(reportBean.star)
            append("\t")
            var selectStarImage = UserInfoDefin.getStarImage(context, statusInt)
            selectStarImage?.setBounds(
                0,
                0,
                selectStarImage.minimumWidth,
                selectStarImage.minimumHeight
            )

            var unSelectStarImage = context.getDrawable(R.mipmap.icon_insufficient)
            unSelectStarImage?.setBounds(
                0,
                0,
                unSelectStarImage.minimumWidth,
                unSelectStarImage.minimumHeight
            )

            for (i in 1..5) {
                val spanStr = SpannableString("custom$i")
                var span =
                    (if (star >= i) selectStarImage else unSelectStarImage)?.let { starDrawable ->
                        CenterImageSpan(starDrawable)
                    }
                spanStr.setSpan(span, 0, spanStr.length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
                append(spanStr)
            }

        }
        holder.getView<TextView>(R.id.mDesc).apply {
            var statusInt = if (reportBean.healthy == null) 0 else reportBean.healthy.result
            tag = statusInt

            var star = if (reportBean.star.isNullOrEmpty()) 0 else Integer.valueOf(reportBean.star)

            text = UserInfoDefin.getHealthArray(context)[statusInt + 1]
            setTextColor(
                ContextCompat.getColor(
                    context,
                    UserInfoDefin.healthCol[statusInt + 1]
                )
            )
        }
    }

    private fun setBody(holder: BaseViewHolder, statusInt: Int, sex: String) {
        //健康状态-1 建模中 0数据不足 1健康 2亚健康 3疾病
        var bodyImgResId = if (statusInt == 2) {
            if (sex == "1") R.mipmap.ic_male_body_warning else R.mipmap.ic_female_body_warning
        } else if (statusInt == 3) {
            if (sex == "1") R.mipmap.ic_male_body_disease else R.mipmap.ic_female_body_disease
        } else if (statusInt == 0) {
            if (sex == "1") R.mipmap.ic_male_body_none_data else R.mipmap.ic_female_body_none_data
        } else {
            if (sex == "1") R.mipmap.ic_male_body_health else R.mipmap.ic_female_body_health
        }
        holder.getView<ImageView>(R.id.mBody)
            .setImageResource(bodyImgResId)
    }

    private fun setStatus(holder: BaseViewHolder, organ: ReportBean.Organ) {
        //器官状态设置
        //心脏
        holder.getView<VisceraView>(R.id.mHeart)
            .setInfo(getHealthStatus(organ.heart.model), UserInfoDefin.heartIcon)
        //胃
        holder.getView<VisceraView>(R.id.mStomach)
            .setInfo(getHealthStatus(organ.stomach.model), UserInfoDefin.stomachIcon)
        //肺
        holder.getView<VisceraView>(R.id.mLung)
            .setInfo(getHealthStatus(organ.lungs.model), UserInfoDefin.lungIcon)
        //肾
        holder.getView<VisceraView>(R.id.mKidney)
            .setInfo(getHealthStatus(organ.kidney.model), UserInfoDefin.kidneyIcon)
        //肝
        holder.getView<VisceraView>(R.id.mLiver)
            .setInfo(getHealthStatus(organ.liver.model), UserInfoDefin.liverIcon)
        //脾脏
        holder.getView<VisceraView>(R.id.mSpleen)
            .setInfo(getHealthStatus(organ.spleen.model), UserInfoDefin.spleenIcon)
        //大肠
        holder.getView<VisceraView>(R.id.mLarge)
            .setInfo(getHealthStatus(organ.largeIntestine.model), UserInfoDefin.largeIcon)
        //小肠
        holder.getView<VisceraView>(R.id.mSmall)
            .setInfo(getHealthStatus(organ.smallIntestine.model), UserInfoDefin.smallIcon)
        //淋巴
        holder.getView<VisceraView>(R.id.mLymph)
            .setInfo(getHealthStatus(organ.lymph.model), UserInfoDefin.lymphIcon)
        //胆囊
        holder.getView<VisceraView>(R.id.mGallbladder)
            .setInfo(getHealthStatus(organ.cholecyst.model), UserInfoDefin.gallIcon)
        //膀胱
        holder.getView<VisceraView>(R.id.mBladder)
            .setInfo(getHealthStatus(organ.bladder.model), UserInfoDefin.bladderIcon)
        //心包
        holder.getView<VisceraView>(R.id.mPericardium).setInfo(
            getHealthStatus(organ.pericardium.model),
            UserInfoDefin.pericardiumIcon
        )
    }

    //获取健康状态
    private fun getHealthStatus(bean: ReportBean.ChildStatus?): Int {
        return if (bean == null) {
            0
        } else {
            if (bean.sumNoEnough == -1) {
                0
            } else {
                bean.idHealth + 1
            }
        }
    }

}