package com.yidianling.dynamic.activity

import `in`.srain.cube.views.ptr.PtrDefaultHandler
import `in`.srain.cube.views.ptr.PtrFrameLayout
import `in`.srain.cube.views.ptr.header.MaterialHeader
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import android.text.style.ImageSpan
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.widget.ImageView
import butterknife.ButterKnife
import com.ydl.ydl_image.module.GlideApp
import com.ydl.ydlcommon.adapter.BaseRecyclerAdapter
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.base.config.YDLConstants
import com.ydl.ydlcommon.bean.StatusBarOptions
import com.ydl.ydlcommon.utils.MoonUtil
import com.ydl.ydlcommon.view.BaseViewHolder
import com.yidianling.common.tools.ToastUtil
import com.yidianling.dynamic.R
import com.yidianling.dynamic.common.net.DynamicApiUtils
import com.yidianling.dynamic.members.MembersActivity
import com.yidianling.dynamic.model.Command
import com.yidianling.dynamic.model.TrendsInfoBean
import com.yidianling.dynamic.model.TrendsReplyBean
import com.yidianling.dynamic.router.DynamicIn
import com.yidianling.dynamic.thank.ThankActivity
import com.yidianling.dynamic.trendsDetail.TrendsDetailActivity
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.dynamic_activity_trends_reply_info.*
import java.util.*

/**
 * 动态回复详情
 * Created by hgw on 2017/3/30.
 */

class TrendsReplyInfoActivity : BaseActivity() {

    private var icoAdapter: BaseRecyclerAdapter<TrendsInfoBean.ZanImg>? = null//头像适配器

    private var infoBean: TrendsReplyBean? = null

    private var reply_id: String? = null//评论id
    private var aid: String? = null//为空则是回复详情，否则为点赞详情
    internal var header: MaterialHeader? = null

    override fun getStatusViewOptions(): StatusBarOptions {
        return StatusBarOptions(isAddStatusView = true, statusBarDarkMode = true)
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.dynamic_activity_trends_reply_info)
        ButterKnife.bind(this)

        val bundle = intent.getBundleExtra(YDLConstants.BUNDLE)
        reply_id = bundle.getString(REPLY_ID)
        aid = bundle.getString(AID)
        if (reply_id == null || reply_id == "") {
            ToastUtil.toastShort("评论id错误")
            finish()
            return
        }

        if (aid == null || aid == "") {
            lin_comment!!.visibility = GONE
        }

        initView()
        getData()
    }

    private fun initView() {
        //下拉刷新
        // header
        header = MaterialHeader(this)
        val colors = resources.getIntArray(R.array.ydl_colors)
        header!!.setColorSchemeColors(colors)
        header!!.layoutParams = PtrFrameLayout.LayoutParams(-1, -2)
        val padding = resources.getDimension(R.dimen.dynamic_default_dis_size).toInt()
        header!!.setPadding(0, padding, 0, padding)
        header!!.setPtrFrameLayout(store_house_ptr_frame)
        store_house_ptr_frame!!.headerView = header
        //        storeHousePtrFrame.setPtrHandler(this);
        store_house_ptr_frame!!.addPtrUIHandler(header)
        store_house_ptr_frame!!.setPtrHandler(object : PtrDefaultHandler() {

            override fun onRefreshBegin(frame: PtrFrameLayout) {
                //开始刷新
                store_house_ptr_frame!!.postDelayed(
                    { store_house_ptr_frame!!.refreshComplete() },
                    1500
                )
                getData()
            }

        })
        //点赞列表
        recy_ico_list!!.layoutManager =
            LinearLayoutManager(
                this,
                LinearLayoutManager.HORIZONTAL,
                false
            )
        icoAdapter = object :
            BaseRecyclerAdapter<TrendsInfoBean.ZanImg>(this, ArrayList(), R.layout.dynamic_item_circleimg) {
            override fun convert(
                mContext: Context,
                holder: BaseViewHolder,
                bean: TrendsInfoBean.ZanImg,
                position: Int
            ) {
                val img = holder.getView<ImageView>(R.id.img_ico)
                if (position == 7) {
                    GlideApp.with(mContext).load(R.drawable.dynamic_newsfeed_zan_more).into(img)
                } else if (position > 7) {

                } else {
                    GlideApp.with(mContext).load(bean.head)
                        .error(resources.getDrawable(R.drawable.dynamic_head_place_hold_pic)).into(img)
                }
                img.setOnClickListener {
                    //点击头像进入会员主页
                    if (position >= 7) {
                        //跳转赞过的人全部列表--h5
                        //最多显示6个头像，最后添加一个更多图标
                        ToastUtil.toastShort("全部列表")
                    } else {
                        val intent =
                            Intent(this@TrendsReplyInfoActivity, MembersActivity::class.java)
                        //                            intent.putExtra("user_id", bean.uid + "");
                        val bundle = Bundle()
                        bundle.putString("user_id", bean.uid.toString() + "")
                        intent.putExtra("bundle", bundle)
                        startActivity(intent)
                    }
                }
            }
        }
        recy_ico_list!!.adapter = icoAdapter
        initClick()
    }

    internal fun initClick() {
        image_back.setOnClickListener {
            finish()
        }
        item_trend_user_head.setOnClickListener {
            //跳转评论用户主页
            val intent = Intent(this, MembersActivity::class.java)
            //            intent.putExtra("user_id", infoBean.getInfo().getUid() + "");
            val bundle = Bundle()
            bundle.putString("user_id", infoBean!!.info.uid.toString() + "")
            intent.putExtra("bundle", bundle)
            startActivity(intent)
        }

        item_trend_user_head_rel.setOnClickListener {
            //跳转回复用户主页
            val intent1 = Intent(this, MembersActivity::class.java)
            //            intent1.putExtra("user_id", infoBean.getComment().getUid() + "");
            val bundle = Bundle()
            bundle.putString("user_id", infoBean!!.comment.uid.toString() + "")
            intent1.putExtra("bundle", bundle)
            startActivity(intent1)
            
        }

        text_chat.setOnClickListener {
            //私聊
            DynamicIn.startChat(this, infoBean!!.comment.uid.toString() + "")
            
        }

        img_comment_zan.setOnClickListener {
            //赞
            zan("3", infoBean!!.comment.id.toString() + "")
        }
        iv_shang.setOnClickListener {
            //赏
            val intent2s = Intent(this@TrendsReplyInfoActivity, ThankActivity::class.java)
            intent2s.putExtra("answerId", infoBean!!.comment.uid)
            startActivity(intent2s)
        }

        img_comment_share.setOnClickListener {
            //回复 跳转主贴进行回复
            try {
                TrendsDetailActivity.start(
                    this,
                    infoBean!!.info.active_id,
                    2,
                    infoBean!!.comment.id,
                    infoBean!!.comment.name,
                    true
                )
            } catch (e: Exception) {
                e.printStackTrace()
            }

            finish()
        }
        text_recver.setOnClickListener {
            //回到主贴
            TrendsDetailActivity.start(
                this,
                infoBean!!.info.active_id,
                false,
                false,
                false,
                false,
                0
            )
        }
      
    }

    fun update(bean: TrendsReplyBean?) {
        if (bean == null) return
        if (lin_content!!.visibility == View.GONE) {
            lin_content!!.visibility = View.VISIBLE
        }
        if (bean.comment.is_delete == 1) {
            //回复已删除，隐藏点赞等按钮
            item_recommend_trend_zan_rel!!.visibility = GONE
        } else {
            item_recommend_trend_zan_rel!!.visibility = VISIBLE
        }

        GlideApp.with(this).load(bean.info.header).circleCrop()
            .error(R.drawable.dynamic_head_place_hold_pic).into(item_recommend_trend_user_head!!)
        //        if (bean.getInfo().getgetGender() == 1) {
        //            //男
        //            Glide.with(this).load(R.mipmap.male).into(imgSex);
        //        } else {
        //            //女
        //            Glide.with(this).load(R.mipmap.female).into(imgSex);
        //        }
        text_userName!!.text = bean.info.name
        text_time!!.text = bean.info.time_str
        //        textContent.setText(bean.getInfo().getContent());
        MoonUtil.identifyFaceExpression(
            this@TrendsReplyInfoActivity,
            text_content,
            bean.info.content,
            ImageSpan.ALIGN_BOTTOM
        )
        item_recommend_trend_zannum_tv!!.text = "赞 " + bean.info.zan_count
        if (bean.info.zan_count <= 0) {
            //隐藏赞列表
            recy_ico_list!!.visibility = GONE
        } else {
            val zanl = bean.members
            if (zanl.size > 7) {
                for (i in 0 until bean.members.size) {
                    if (i > 6) {
                        zanl.removeAt(i)
                    }
                }
            }
            icoAdapter!!.updateData(zanl)
        }
        text_talk_num!!.text = bean.info.total_comments.toString() + "个评论"

        if (aid != null && aid != "") {
            if (infoBean!!.comment.user_type == 2) {//1用户2专家3助理
                //咨询师
                text_zixunshi!!.visibility = VISIBLE//显示咨询师标志
                text_chat!!.visibility = VISIBLE//显示私聊按钮
                iv_shang!!.visibility = VISIBLE//显示赏按钮
            } else {
                //用户
                text_zixunshi!!.visibility = GONE//隐藏咨询师标志
                text_chat!!.visibility = GONE//隐藏私聊按钮
                iv_shang!!.visibility = GONE//隐藏赏按钮
            }
            GlideApp.with(this).load(infoBean!!.comment.header).circleCrop()
                .into(item_recommend_trend_user_head_iv!!)
            text_reply_userName!!.text = infoBean!!.comment.name
            comment_sex_iv!!.setImageResource(if (infoBean!!.comment.gender == 1) R.drawable.dynamic_male else R.drawable.dynamic_female)
            text_reply_time!!.text = infoBean!!.comment.time_str
            //            textCommentContent.setText(infoBean.getComment().getContent());
            MoonUtil.identifyFaceExpression(
                this@TrendsReplyInfoActivity,
                text_comment_content,
                infoBean!!.comment.content,
                ImageSpan.ALIGN_BOTTOM
            )
            //是否已赞
            if (infoBean!!.comment.is_zan == 1) {
                //已赞
                img_comment_zan!!.setImageDrawable(resources.getDrawable(R.drawable.dynamic_reply_zan_sel))
            } else {
                img_comment_zan!!.setImageDrawable(resources.getDrawable(R.drawable.dynamic_reply_zan))
            }
        }
    }

    //请求数据
    private fun getData() {
        val cmd = Command.TrendsReplyInfo(reply_id, aid)
        showProgressDialog(null)
        DynamicApiUtils.trendsReplyInfo(cmd)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ resp ->
                dismissProgressDialog()
                store_house_ptr_frame!!.cancelLongPress()
                //如果被删除，则显示相应提示
                if (resp.code !== 0) {
                    rela_nullTip!!.visibility = VISIBLE
                    store_house_ptr_frame!!.visibility = GONE
                    tv_null_tip!!.setText(resp.msg)
                } else {
                    val trendsInfoBean = resp.data
                    if (trendsInfoBean != null) {
                        infoBean = trendsInfoBean
                        update(trendsInfoBean)
                    }
                }
            }, { throwable ->
                dismissProgressDialog()
                DynamicApiUtils.handleError(this, throwable)
            })

    }

    /**
     * //点赞
     *
     * @param type1 1用户，2动态，3回复
     * @param id1   动态id,回复id,用户uid
     */
    fun zan(type1: String, id1: String) {
        //业务类型：1访问用户，2动态，3话题
        val cmd = Command.ZanAction(type1, id1)
        DynamicApiUtils.zanAction(cmd)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ resp ->
                if (resp.code === 0) {
                    if (type1 == "1") {

                    } else if (type1 == "2") {
                        //主贴点赞成功
                    } else if (type1 == "3") {
                        //评论点赞成功
                        if (infoBean!!.comment.is_zan == 1) {
                            infoBean!!.comment.is_zan = 2
                            img_comment_zan!!.setImageDrawable(resources.getDrawable(R.drawable.dynamic_reply_zan))
                        } else {
                            infoBean!!.comment.is_zan = 1
                            img_comment_zan!!.setImageDrawable(resources.getDrawable(R.drawable.dynamic_reply_zan_sel))
                        }
                    }
                } else {
                    ToastUtil.toastShort(resp.msg)
                }
            }, { throwable -> DynamicApiUtils.handleError(this, throwable) })
    }

    override fun layoutResId(): Int {
        return 0
    }

    override fun initDataAndEvent() {

    }

    companion object {

        private val REPLY_ID = "reply_id"
        private val AID = "aid"

        fun newIntent(activity: Activity, replyId: String, aid: String): Intent {
            val intent = Intent(activity, TrendsReplyInfoActivity::class.java)
            val bundle = Bundle()
            bundle.putString(REPLY_ID, replyId)
            bundle.putString(AID, aid)
            intent.putExtra(YDLConstants.BUNDLE, bundle)
            return intent
        }
    }
}
