package com.zxhl.main.page.activity

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.app.Activity
import android.media.MediaPlayer
import android.net.Uri
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.animation.LinearInterpolator
import android.widget.ImageView
import byc.imagewatcher.ImageWatcher
import byc.imagewatcher.ImageWatcherHelper
import byc.imagewatcher.OnImageLikeClickListener
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.zxhl.cms.AppContext
import com.zxhl.cms.common.base.BaseActivity
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.net.model.box.HomeListEntity
import com.zxhl.cms.net.model.chat.ChatMessageChargeOrNotEntity
import com.zxhl.cms.net.model.chat.ChatStausEvent
import com.zxhl.cms.net.model.chat.DistanceEntity
import com.zxhl.cms.utils.*
import com.zxhl.cms.widget.*
import com.zxhl.main.R
import com.zxhl.main.page.`interface`.ReportListener
import com.zxhl.main.page.contract.UserDetailContract
import com.zxhl.main.page.presenter.UserDetailPresenter
import com.zxhl.main.page.view.DialogUtils
import kotlinx.android.synthetic.main.activity_layout_user_detail.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @detail : 国内版用户详情(暂时未使用)
 */
class UserDetailActivity : BaseActivity(), UserDetailContract.View,
    ImageWatcher.OnPictureLongPressListener {
    private var mPresenter: UserDetailPresenter? = null
    private var userId: String? = ""
    private var detailfree: String? = ""
    private var voiceUrl: String? = ""
    private var like: String = "0"
    private var follow: String = "0"
    private var iwHelper: ImageWatcherHelper? = null
    private var mMediaPlayer: MediaPlayer? = null
    var chatname: String? = ""
    var isTranslucentStatus = false
    var chatStaus: Int? = 0
    override fun onClick(v: View?) {

    }

    override fun before() {
        super.before()
        setStatusBarBackground(AppContext.get().resources.getColor(R.color.transparent))
    }

    override fun layoutID(): Int {
        return R.layout.activity_layout_user_detail
    }

    override fun init() {
        mMediaPlayer = MediaPlayer()
        userId = intent?.data?.getQueryParameter("userId") ?: ""
        detailfree = intent?.data?.getQueryParameter("detailfree") ?: ""
        iwHelper =
            ImageWatcherHelper.with(this, GlideSimpleLoader()) // 一般来讲， ImageWatcher 需要占据全屏的位置
                .setTranslucentStatus(if (!isTranslucentStatus) Utils.calcStatusBarHeight(AppContext.get()) else 0) // 如果不是透明状态栏，你需要给ImageWatcher标记 一个偏移值，以修正点击ImageView查看的启动动画的Y轴起点的不正确
                .setErrorImageRes(R.mipmap.error_picture) // 配置error图标 如果不介意使用lib自带的图标，并不一定要调用这个API
                .setOnPictureLongPressListener(this)
                .setOnStateChangedListener(object : ImageWatcher.OnStateChangedListener {
                    override fun onStateChangeUpdate(
                        imageWatcher: ImageWatcher,
                        clicked: ImageView,
                        position: Int,
                        uri: Uri,
                        animatedValue: Float,
                        actionTag: Int
                    ) {
                        Log.e(
                            "IW",
                            "onStateChangeUpdate [$position][$uri][$animatedValue][$actionTag]"
                        )
                    }

                    override fun onStateChanged(
                        imageWatcher: ImageWatcher,
                        position: Int,
                        uri: Uri,
                        actionTag: Int
                    ) {
                        if (actionTag == ImageWatcher.STATE_ENTER_DISPLAYING) {
                            Log.e("MXL", "点击大图")
                            //  Toast.makeText(getApplicationContext(), "点击了图片 [" + position + "]" + uri + "", Toast.LENGTH_SHORT).show();
                        } else if (actionTag == ImageWatcher.STATE_EXIT_HIDING) {
                            //  Toast.makeText(getApplicationContext(), "退出了查看大图", Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .setIndexProvider(CustomDotIndexProvider()) //自定义页码指示器（默认数字）
                .setLoadingUIProvider(CustomLoadingUIProvider()) // 自定义LoadingUI
        mPresenter = UserDetailPresenter(this)
        mPresenter?.getUserInfo(userId, detailfree.toString())
        id_img_back?.setOnClickListener {
            finish()
        }
        id_img_gengduo?.setOnClickListener {
            DialogUtils.showReport(this, object : ReportListener {
                override fun report(pos: Int) {
                    JumpUtils.ReportJump(userId)
                }

            })
        }
        id_img_like?.setOnClickListener {
            if (TextUtils.equals(like, "0")) {
                like(userId.toString())
                //    mPresenter?.likeUser(userId, "0")
                //     like = "1"
            } else {
                playAnimation()
//                like = "0"
//               id_img_like?.setImageResource(R.drawable.icon_chaojixihuan_default)
            }
        }
        id_tv_chakan_juli?.setOnClickListener {
            EventUtils.onEvent("DetailDistanceCheck", userId.toString())
            viewDistance(userId.toString())
        }
        id_tv_follow?.setOnClickListener {
            EventUtils.onEvent("DetailButtonFollow", follow)
            if (TextUtils.equals(follow, "0")) {
                mPresenter?.followUser(userId)
                follow = "1"
                id_tv_follow?.text = "已关注"
                id_tv_follow?.setBackgroundResource(R.drawable.shape_cccccc_r25)
            } else {
                DialogUtils.showCanleFollow(this, View.OnClickListener {
                    mPresenter?.followUser(userId)
                    follow = "0"
                    id_tv_follow?.text = "关注"
                    id_tv_follow?.setBackgroundResource(R.drawable.shape_aa60ff_r25)
                })

            }
        }
        id_ll_voice?.setOnClickListener {
            EventUtils.onEvent("DetailAudioPlay", userId.toString())
            playSound(voiceUrl)
        }
        id_tv_chat?.setOnClickListener {
            EventUtils.onEvent("DetailButtonChat", "userId${userId}")
//            JumpUtils.startC2CChatActivity(chatStaus!!, userId, chatname)
            JumpUtils.VideoCallDemoJump()
        }
        EventBus.getDefault().register(this)
    }

    fun playSound(url: String?) {
        try {
            if (mMediaPlayer!!.isPlaying) {
                mMediaPlayer!!.stop()
            }
            mMediaPlayer?.reset()
            mMediaPlayer?.isLooping = false
            mMediaPlayer?.setDataSource(this, Uri.parse(url))
            mMediaPlayer?.prepareAsync()
            mMediaPlayer?.setOnPreparedListener {
                mMediaPlayer?.start()
                id_img_voice?.setImageResource(R.drawable.icon_bofang)
            }
            mMediaPlayer?.setOnCompletionListener {
                id_img_voice?.setImageResource(R.drawable.icon_bofang_2)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun playAnimation() {
        var animatorSet = AnimatorSet()
        var durin: Long = 300
        id_img_heart_gif.visibility = View.VISIBLE
        Glide.with(AppContext.get()).asGif().load(R.drawable.heart)
            .into(id_img_heart_gif)
        animatorSet.play(
            alphaAni(id_img_like, 0F, 1F, durin, 0)
        )
            .with(scaleAni(id_img_like, "scaleX", 1f, 1.14f, durin, 0))
            .with(scaleAni(id_img_like, "scaleY", 1f, 1.14f, durin, 0))
            .with(scaleAni(id_img_like, "scaleX", 1.14f, 1F, durin, 0))
            .with(scaleAni(id_img_like, "scaleY", 1.14f, 1F, durin, 0))
            .with(scaleAni(id_img_like, "scaleX", 1f, 1.14f, durin, 0))
            .with(scaleAni(id_img_like, "scaleY", 1f, 1.14f, durin, 0))
            .with(scaleAni(id_img_like, "scaleX", 1.14f, 1F, durin, 0))
            .with(scaleAni(id_img_like, "scaleY", 1.14f, 1F, durin, 0))
        animatorSet.start()
        animatorSet.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator?) {
                MainLooper.get()
                    ?.postDelayed(Runnable {
                        id_img_heart_gif.visibility = View.GONE
                    }, 1000)

            }
        })
        id_img_like?.setImageResource(R.drawable.icon_like_click_user)
    }

    var distanceFree: Int = 0
    fun viewDistance(userId: String) {
        ChatMessageChargeUtils.getChatMessageChargeOrNot(
            "" + ChatMessageChargeUtils.MESSAGE_LOOK_DISTANCE,
            userId,
            object : ChatCallback<ChatMessageChargeOrNotEntity> {
                override fun onResult(result: ChatMessageChargeOrNotEntity?) {
                    if (result?.charge!! <= 0) {
                        distanceFree = 0
                        mPresenter?.getDistance(distanceFree, userId)
                    } else {
                        distanceFree = 1
                        ChatDialogUtils.showMemberChargeTip(
                            mActivity as Activity,
                            result,
                            "开启会员解锁无限查看距离权限",
                            "星币解锁当前用户距离",
                            object : ChatDialogUtils.ChatDialogCallBackParams {
                                override fun confirm(type: Int) {
                                    //兑换
                                    if (type == 0) {
                                        if (SettingPreference.getUserInfoData() != null
                                            && SettingPreference.getUserInfoData().starBalance < result.charge
                                        ) {
                                            ChatDialogUtils.showMemberTrip(
                                                mActivity as Activity,
                                                object : ChatDialogUtils.ChatDialogCallBack {
                                                    override fun confirm() {
                                                        JumpUtils.starCoinpayJump()
                                                    }

                                                    override fun cancel() {}
                                                })
                                        } else {
                                            mPresenter?.getDistance(distanceFree, userId)
                                        }

                                    } else {
                                        JumpUtils.payJump()
                                    }
                                }

                                override fun cancel() {}
                            })
                        return
                    }
                }


                override fun onError(code: String?, errorMsg: String?) {
                    if (TextUtils.isEmpty(errorMsg)) {
                        return
                    }
                    Utils.showToast(context, errorMsg)
                }
            })

    }

    private var photolist: MutableList<String>? = ArrayList()
    override fun setUserInfo(result: HomeListEntity) {

        chatStaus = result?.chatStatus
        chatname = result?.nickname

        if (result.picturesList?.isNullOrEmpty() == false) {
            id_ll_user_photo?.visibility = View.VISIBLE
            id_img_top_bg?.setLoadImageUrl(result.picturesList?.get(0), false)
            photolist?.clear()
            if (result.picturesList?.size!! > 8) {
                for (index in result.picturesList!!.indices) {
                    if (index < 8) {
                        photolist?.add(result.picturesList!![index])
                    }
                }
            }
        } else {
            id_ll_user_photo?.visibility = View.GONE
            id_img_top_bg?.setLoadImageUrl(result?.headImage, false)
        }
        if (TextUtils.isEmpty(result?.distance)) {
            id_tv_chakan_juli.visibility = View.VISIBLE
            id_tv_distance?.visibility = View.GONE
        } else {
            id_tv_chakan_juli.visibility = View.GONE
            id_tv_distance?.text = "${result?.distance}km"
            id_tv_distance?.visibility = View.VISIBLE
        }
        follow = result?.hasFollows.toString()
        like = result?.hasLikes.toString()
        if (TextUtils.equals(like, "0")) {
            //未喜欢
            id_img_like?.setImageResource(R.drawable.icon_like_default_user)
        } else {
            //已喜欢
            id_img_like?.setImageResource(R.drawable.icon_like_click_user)
        }
        if (TextUtils.equals(follow, "0")) {
            //未关注
            id_tv_follow?.text = "关注"
            id_tv_follow?.setBackgroundResource(R.drawable.shape_aa60ff_r25)
        } else {
            id_tv_follow?.text = "已关注"
            id_tv_follow?.setBackgroundResource(R.drawable.shape_cccccc_r25)
        }
        if (!TextUtils.isEmpty(result.headImage)) {
            Glide.with(this).load(result.headImage)
                .apply(RequestOptions.bitmapTransform(CircleCrop()))
                .into(id_img_head)
        } else {
            id_img_head.setImageResource(R.drawable.icon_user_photo_default)
        }
//        if (TextUtils.equals(result.onlineStatus, "1")) {
//            id_img_online?.visibility = View.VISIBLE
//        } else {
//            id_img_online?.visibility = View.GONE
//        }
        id_tv_nick_name?.text = "${result?.nickname}"
        id_tv_user_age?.text = "${result?.age ?: ""}岁"
        if (!TextUtils.isEmpty(result?.height)) {
            id_tv_user_height?.visibility = View.VISIBLE
            id_tv_user_height?.text = "${result?.height ?: ""}"
        } else {
            id_tv_user_height?.visibility = View.GONE
        }

        if (!TextUtils.isEmpty(result?.weight)) {
            id_tv_user_weight?.visibility = View.VISIBLE
            id_tv_user_weight?.text = "${result?.weight ?: ""}"
        } else {
            id_tv_user_weight?.visibility = View.GONE
        }
        if (!TextUtils.isEmpty(result.pageTag)) {
            id_tv_ren_zheng?.visibility = View.VISIBLE
            id_tv_ren_zheng?.text = "${result.pageTag ?: ""}"
        } else {
            id_tv_ren_zheng?.visibility = View.GONE
        }

        id_tv_desc?.text = "${result.description ?: ""}"
        id_tv_zhiye?.text = "${result.occupation ?: ""}"
        id_tv_xingzuo?.text = "${result.constellation ?: ""}"
        id_tv_voice_time?.text = "${result?.voiceTime}"
        if (TextUtils.equals(result?.sex, "2")) {
            id_tv_sex?.text = "女"
        } else {
            id_tv_sex?.text = "男"
        }

        id_tv_age?.text = "${result.age ?: ""}"
        id_tv_height?.text = "${result.height ?: ""}"
        id_tv_address?.text = "${result.province ?: ""}"
        // id_tv_xingzuo?.text="${result?.age}"
        //id_tv_zhiye?.text="${result?.sex}"
        voiceUrl = result.voice
        if (TextUtils.isEmpty(voiceUrl)) {
            id_ll_voice.visibility = View.GONE
        } else {
            id_ll_voice.visibility = View.VISIBLE
        }
        id_layout_nine?.setAdapter(
            NineImageAdapter(
                this,
                RequestOptions().centerCrop(),
                DrawableTransitionOptions.withCrossFade(),
                result.picturesList
            )
        )

        id_layout_nine?.setOnImageClickListener(object :
            NineGridView.OnImageClickListener {
            override fun onImageClick(position: Int, view: View?) {
                if (iwHelper != null) {
                    EventUtils.onEvent("DetailImageClick", "" + result?.picturesList!![position])
                    iwHelper?.show(
                        view as ImageView?, id_layout_nine?.getImageViews(),
                        getImageUriList(result?.picturesList),
                        imgLikeList,//like数据
                        object : OnImageLikeClickListener {
                            override fun onImageLikeClick(position: Int, view: View?) {
                                //点击喜欢
                                //走接口更改like状态
                                Log.e("MXL", "点击喜欢" + position)
                                //  iwHelper?.updateLikeStatus(position, true)
                            }
                        }
                    )
                }
            }
        })
    }

    val imgLikeList: MutableList<String> = ArrayList()

    override fun followSuc() {

    }

    override fun likeSuc() {
        like = "1"
        playAnimation()
        SettingPreference.setLikeUserId(userId)
    }

    override fun distanceSuc(reslut: DistanceEntity?) {
        if (TextUtils.isEmpty(reslut?.distance)) {
            id_tv_chakan_juli.visibility = View.VISIBLE
            id_tv_distance?.visibility = View.GONE
        } else {
            id_tv_chakan_juli.visibility = View.GONE
            id_tv_distance?.text = "${reslut?.distance}km"
            id_tv_distance?.visibility = View.VISIBLE
        }
    }

    override fun distanceFail() {

    }

    fun getImageUriList(files: List<String?>?): List<Uri>? {
        val imageUriList: MutableList<Uri> = ArrayList()
        if (files != null && files.size > 0) {
            for (str in files) {
                imageUriList.add(Uri.parse(str))
            }
        }
        return imageUriList
    }

    override fun onPictureLongPress(v: ImageView?, uri: Uri?, pos: Int) {
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(chatStausEvent: ChatStausEvent) {
        chatStaus = chatStausEvent.chatstatus?.toInt()
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        if (mMediaPlayer != null) {
            mMediaPlayer?.stop()
            mMediaPlayer?.release()
        }
    }

    override fun onBackPressed() {
        if (!iwHelper!!.handleBackPressed()) {
            super.onBackPressed()
        }
    }

    fun scaleAni(
        view: View,
        propertyName: String,
        from: Float,
        to: Float,
        time: Long,
        delayTime: Long
    ): ObjectAnimator {
        val ani = ObjectAnimator.ofFloat(view, propertyName, from, to)
        ani.interpolator = LinearInterpolator()
        ani.startDelay = delayTime
        ani.duration = time
        return ani
    }

    fun alphaAni(view: View, from: Float, to: Float, time: Long, delayTime: Long): ObjectAnimator {
        val ani = ObjectAnimator.ofFloat(view, "alpha", from, to)
        ani.interpolator = LinearInterpolator()
        ani.duration = time
        ani.startDelay = delayTime
        return ani
    }

    private var likeFree: String = "0"

    //超级喜欢
    fun like(userId: String) {
        ChatMessageChargeUtils.getChatMessageChargeOrNot(
            "" + ChatMessageChargeUtils.MESSAGE_SUPER_LOVE,
            userId,
            object : ChatCallback<ChatMessageChargeOrNotEntity> {
                override fun onResult(result: ChatMessageChargeOrNotEntity?) {
                    if (result?.charge!! <= 0) {
                        likeFree = "0"
                        mPresenter?.likeUser(userId, likeFree)
                    } else {
                        likeFree = "1"
                        if (SettingPreference.getUserInfoData() != null && SettingPreference.getUserInfoData().memberType == 1) {
                            MemberDialogUtils.showMemberChargeTip(
                                mActivity as Activity,
                                result,
                                "今日赠送超级喜欢已经用完",
                                "星币解锁本次超级喜欢",
                                object : ChatDialogUtils.ChatDialogCallBackParams {
                                    override fun confirm(type: Int) {
                                        //兑换
                                        if (type == 0) {
                                            if (SettingPreference.getUserInfoData() != null
                                                && SettingPreference.getUserInfoData().starBalance < result.charge
                                            ) {
                                                ChatDialogUtils.showMemberTrip(
                                                    mActivity as Activity,
                                                    object : ChatDialogUtils.ChatDialogCallBack {
                                                        override fun confirm() {
                                                            JumpUtils.starCoinpayJump()
                                                        }

                                                        override fun cancel() {}
                                                    })
                                            } else {
                                                mPresenter?.likeUser(userId, likeFree)
                                            }

                                        } else {
                                            JumpUtils.payJump()
                                        }
                                    }

                                    override fun cancel() {}
                                })
                            return
                        } else {
                            if (SettingPreference.getUserInfoData() != null
                                && SettingPreference.getUserInfoData().starBalance >= result.charge
                            ) {
                                mPresenter?.likeUser(userId, likeFree)
                            } else {
                                ChatDialogUtils.showMemberChargeTip(
                                    mActivity as Activity,
                                    result,
                                    "开启会员每日都会赠送超级喜欢哦",
                                    "星币解锁本次超级喜欢",
                                    object : ChatDialogUtils.ChatDialogCallBackParams {
                                        override fun confirm(type: Int) {
                                            //兑换
                                            if (type == 0) {
                                                if (SettingPreference.getUserInfoData() != null
                                                    && SettingPreference.getUserInfoData().starBalance < result.charge
                                                ) {
                                                    ChatDialogUtils.showMemberTrip(
                                                        mActivity as Activity,
                                                        object :
                                                            ChatDialogUtils.ChatDialogCallBack {
                                                            override fun confirm() {
                                                                JumpUtils.starCoinpayJump()
                                                            }

                                                            override fun cancel() {}
                                                        })
                                                } else {
                                                    mPresenter?.likeUser(userId, likeFree)
                                                }

                                            } else {
                                                JumpUtils.payJump()
                                            }
                                        }

                                        override fun cancel() {}
                                    })
                            }
                            return
                        }
                    }

                }


                override fun onError(code: String?, errorMsg: String?) {
                    if (TextUtils.isEmpty(errorMsg)) {
                        return
                    }
                    Utils.showToast(context, errorMsg)
                }
            })
    }

}