package com.ydl.confide.home.event

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentActivity
import com.alibaba.fastjson.JSON
import com.ydl.confide.api.ConfideRoute
import com.ydl.confide.home.ConfideBottomSheetDialogFragment
import com.ydl.confide.home.ConfideHomeActivity
import com.ydl.confide.home.adapter.ConfideHomeAdapter
import com.ydl.confide.home.bean.ConfideHomeAllFiltersBean
import com.ydl.confide.home.bean.ConfideHomeBodyBean
import com.ydl.confide.home.bean.ConfideHomeFiterItemBean
import com.ydl.confide.home.config.IConfideHomeConfig
import com.ydl.confide.home.contract.IConfideHomeContract
import com.ydl.confide.home.popwindow.ConfideHomeGoodPopupWindow
import com.ydl.confide.home.popwindow.ConfideHomeSexAgePopupWindow
import com.ydl.confide.home.popwindow.ConfideHomeSortPopupWindow
import com.ydl.confide.home.util.ConfideHomeUtils
import com.ydl.confide.home.widget.ConfideHomeFilterView
import com.ydl.confide.router.PhoneCallIn
import com.ydl.media.audio.AudioPlayer
import com.ydl.media.audio.model.Music
import com.ydl.media.view.PlayerFloatHelper
import com.ydl.media.view.PlayerFloatView
import com.ydl.ydl_router.manager.YDLRouterManager
import com.ydl.ydl_router.manager.YDLRouterParams
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.base.config.HttpConfig
import com.ydl.ydlcommon.modular.route
import com.ydl.ydlcommon.router.IYDLRouterConstant
import com.ydl.ydlcommon.utils.remind.ToastHelper
import com.yidianling.common.tools.ToastUtil
import com.yidianling.im.api.bean.IMRequestCallback


/**
 * @author yuanwai
 * @描述:倾诉首页事件处理类
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/8/10
 */
class ConfideHomeEventImpl(context: Context, var confideHomeView: IConfideHomeContract.View) : IConfideHomeEvent {

    private var mContext: Context? = null
    private var floatViewClickListener: PlayerFloatView.FloatViewPlayListener? = null

    init {
        mContext = context
    }

    /**
     * 跳转我的
     */
    override fun jumpMine() {
        ConfideHomeUtils.buildJumpMine(mContext!!)
    }

    /**
     * banner点击事件
     * @param linkUrl 跳转地址
     * @param position 点击索引
     * @param title banner 标题
     */
    override fun bannerClick(linkUrl: String?, position: Int?, title: String?) {
        link(linkUrl)
    }

    /**
     * 最近倾诉--继续倾诉
     */
    override fun latelyConfideClick(linkUrl: String?) {

        link(linkUrl)
    }

    /**
     * 最近倾诉--更多
     */
    override fun latelyConfideMore(linkUrl: String?) {
        link(linkUrl)
    }

    /**
     * 分类点击事件
     * @param linkUrl
     */
    override fun categoryClick(linkUrl: String?) {

        link(linkUrl)
    }

    /**
     * 为你推荐--向TA倾诉
     * @param linkUrl 跳转地址
     */
    override fun recommendClick(linkUrl: String?) {
        link(linkUrl)
    }

    /**
     * 为你推荐--更多
     * @param linkUrl 跳转地址
     */
    override fun recommendMoreClick(linkUrl: String?) {
        link(linkUrl)
    }

    /**
     * 听声寻人--向TA倾诉
     * @param linkUrl 跳转地址
     */
    override fun soundClick(linkUrl: String?) {
        link(linkUrl)
    }

    /**
     * 听声寻人--更多
     * @param linkUrl 跳转地址
     */
    override fun soundMoreClick(linkUrl: String?) {
        link(linkUrl)
    }

    /**
     * 最佳倾诉榜单--点我倾诉
     * @param linkUrl 跳转地址
     */
    override fun consultantClick(doctorId: String?, confideId: String?, uid: String?,listenFree : Boolean?, expertUrl:String?) {
        doctorId?.let { doctorId ->
            confideId?.let {confideId ->
                ConfideBottomSheetDialogFragment()
                    .showBottomSheetDialog(
                        mContext as FragmentActivity,
                        HttpConfig.MH5_URL + ConfideRoute.h5ConfideIntro(confideId),
                        doctorId, uid = uid, listenFree = listenFree ?: false,expertUrl = expertUrl?:""
                    )
            }
        }
    }


    override fun videoShowClick(index: Int, data: List<ConfideHomeBodyBean>?) {
        val dataJson = if (data != null) JSON.toJSONString(data) else null
        AudioPlayer.get().playOrPause()
        PlayerFloatHelper.updatePlayState()
        route(mContext, ConfideRoute.R_VIDEO_SHOW, "initPos" to index, "initData" to dataJson)
    }

    /**
     * 最佳倾诉榜单--更多情感恋爱专家
     * @param linkUrl 跳转地址
     */
    override fun consultantMoreClick(linkUrl: String?) {
        link(linkUrl)
    }

    /**
     * 播放音频文件
     * @param type   当前模块数据类型
     * @param index 当前的模块里的数据索引位置
     * @param playUrl 播放地址
     */
    override fun playVoice(type: Int?, index: Int?, playUrl: String?) {

        val mu = Music()
        mu.path = playUrl
        AudioPlayer.get().singlePlay(mu)
        umengPlayVoice(type)
        confideHomeView.updataPlayStatu(type, index!!, 0, true)
        initCache(type, index!!, 0, playUrl)
        initConfidePlayerListener()
    }

    override fun playVoice(type: Int?, index: Int?, recommendId: Int, playUrl: String?, name: String?,confideIcon:String?) {
        val mu = Music()
        mu.title = name
        mu.path = playUrl
        mu.coverPath=confideIcon
        AudioPlayer.get().singlePlay(mu)
        if (PlayerFloatHelper.isShow()) {
            if (AudioPlayer.get().playMode.value() == 1) {
                PlayerFloatHelper.removeView()

                PlayerFloatHelper.show(mContext!!)
            } else {
                PlayerFloatHelper.setPlayingState(mContext!!)
            }

        } else {
            mContext?.let { PlayerFloatHelper.show(it) }
        }

        umengPlayVoice(type)
        confideHomeView.updataPlayStatu(type, index!!, recommendId, true)
        initCache(type, index!!, recommendId, playUrl)
        initConfidePlayerListener()
    }

    private fun initConfidePlayerListener() {
        if (floatViewClickListener == null) {
            floatViewClickListener = object : PlayerFloatView.FloatViewPlayListener {
                override fun onStartClick() {
                    confideHomeView.updataPlayStatu(cacheType, cacheIndex!!, cacheSubIndex, true)
                }

                override fun onPlayFinish() {
                    confideHomeView.updataPlayStatu(9999, 0, 0, false)
                }

                override fun onPauseClick() {
                    confideHomeView.updataPlayStatu(9999, 0, 0, false)
                }

            }

            PlayerFloatHelper.addClickListener(floatViewClickListener as PlayerFloatView.FloatViewPlayListener);
        }
    }

    private fun initCache(type: Int?, index: Int?, sub_index: Int, playUrl: String?) {
        cachePlayUrl = playUrl
        cacheType = type
        cacheIndex = index
        cacheSubIndex = sub_index
    }

    //友盟统计埋点
    private fun umengPlayVoice(type: Int?) {
        when (type) {
            //为你推荐
            IConfideHomeConfig.TYPE_RECOMMEND -> {
            }
            //听声寻人
            IConfideHomeConfig.TYPE_SOUND -> {
            }
        }
    }

    /**
     * 播放缓存变量 用于重播使用
     */
    private var cachePlayUrl: String? = null
    private var cacheType: Int? = -1
    private var cacheIndex: Int? = -1
    private var cacheSubIndex: Int = -1

    override fun rePlayVoice() {
        if (TextUtils.isEmpty(cachePlayUrl)) {
            return
        }
        AudioPlayer.get().playOrPause()
        confideHomeView.updataPlayStatu(cacheType, cacheIndex!!, cacheSubIndex, true)
    }

    /**
     * 暂停播放音频文件
     */
    override fun pauseVoice() {
        AudioPlayer.get().playOrPause()
        PlayerFloatHelper.updatePlayState()
        //因为9999 类型不存在 所以就能把状态全部置为暂停状态了 偷个懒
        confideHomeView.updataPlayStatu(9999, 0, 0, false)
    }

    override fun destoryPlayer() {
        PlayerFloatHelper.removeResetView()
        floatViewClickListener?.let { PlayerFloatHelper.removeClickListener(it) };
    }

    /**
     * 私聊
     */
    override fun toChatForMsg(doctorId: String?) {
        if (null != mContext && mContext is Activity) {
            if (!PhoneCallIn.loginByOneKeyLogin(mContext as Activity, true)) {
                return
            }
        }
        if (mContext is AppCompatActivity && !TextUtils.isEmpty(doctorId)) {
            PhoneCallIn.startChat(mContext as AppCompatActivity, doctorId!!, 0x001, 0)
        }
        PhoneCallIn.getImService().createTextMessage(doctorId, "你好，我想找你倾诉，请尽快上线私聊我，我在等你。", object :
            IMRequestCallback<Void> {
            override fun onSuccess(aVoid: Void?) {
                (mContext as BaseActivity).dismissProgressDialog()
                ToastHelper.show("发送成功")
            }

            override fun onFailed(i: Int) {
                (mContext as BaseActivity).dismissProgressDialog()
                var message = "发送失败"
                if (i == 7101) {
                    message = "您已被对方拉黑！"
                }
                ToastHelper.show(message)
            }

            override fun onException(throwable: Throwable?) {
                (mContext as BaseActivity).dismissProgressDialog()
                ToastHelper.show("发送异常")
            }
        })
    }

    private fun link(linkUrl: String?) {
        if (null == linkUrl || linkUrl.isEmpty()) {
            return
        }
        if (linkUrl!!.startsWith("app")) {
            var uri = Uri.parse(linkUrl)
            //app://listen/list    列表
            //app://listen/lately  最近倾诉列表
            //因为android本地 没有最近倾诉列表 故都跳转 倾诉列表
            if ("listen" == uri.host) {
                var tabIndex = uri.getQueryParameter("type")
                if (TextUtils.isEmpty(tabIndex)) {
                    val intent1 = Intent(mContext, ConfideHomeActivity::class.java)
                    mContext?.startActivity(intent1)
                } else {
                    val intent1 = Intent(mContext, ConfideHomeActivity::class.java)
                    mContext?.startActivity(intent1)
                }
            }
        } else if (linkUrl.startsWith("http")) {
            YDLRouterManager.router(IYDLRouterConstant.ROUTER_H5_H5,
                    YDLRouterParams().putExtra(IYDLRouterConstant.EXTRA_URL, linkUrl), "")
        } else {
            YDLRouterManager.router(linkUrl)
        }
    }

    /**
     * 显示综合排序弹窗
     * @param v_line_top      显示弹窗的位置
     * @param filterView      隐藏的筛选栏View
     * @param bodyBean        数据bean
     * @param allFiltersBean  已选择的筛选bean
     * @param mConfideAdapter section适配器
     */
    override fun showSortPopupWindow(v_line_top: View, filterView: ConfideHomeFilterView, bodyBean: ConfideHomeBodyBean?, allFiltersBean: ConfideHomeAllFiltersBean, mConfideAdapter: ConfideHomeAdapter) {
        if (null == bodyBean) {
            return
        }
        var sortPopup: ConfideHomeSortPopupWindow? = null
        if (bodyBean.group != null && !bodyBean.group!!.isEmpty() && null != bodyBean.group!![0].data && !bodyBean.group!![0].data!!.isEmpty()) {
            ConfideHomeUtils.synchroTextDrawable(mContext!!, 1, IConfideHomeConfig.FILTER_STATUS_OPEN, filterView, mConfideAdapter)
            sortPopup = ConfideHomeSortPopupWindow(mContext!!, bodyBean.group!![0].data!!, allFiltersBean!!.selectSort!!, object : ConfideHomeSortPopupWindow.OnSortItemSelectedListener {
                override fun onSortItemSelected(sortItem: ConfideHomeFiterItemBean) {

                    //更改小图标
                    ConfideHomeUtils.synchroTextDrawable(mContext!!, 1, IConfideHomeConfig.FILTER_STATUS_NORMAL, filterView, mConfideAdapter)
                    allFiltersBean.selectSort = sortItem
                    confideHomeView.recommendList(1)
                    sortPopup!!.dismiss()
                }
            })

            sortPopup.setOnDismissListener {
                ConfideHomeUtils.synchroTextDrawable(mContext!!, 1, IConfideHomeConfig.FILTER_STATUS_NORMAL, filterView, mConfideAdapter)
            }
            if (sortPopup!!.selectedSort != allFiltersBean.selectSort) {
                sortPopup!!.selectedSort = allFiltersBean.selectSort!!
                sortPopup!!.notifyDataSetChanged()
            }
            sortPopup!!.showAsDropDown(v_line_top)
        } else {
            ToastUtil.toastShort("数据初始化失败，请重新下拉刷新")
        }
    }

    /**
     * 显示性别年龄弹窗
     * @param v_line_top      显示弹窗的位置
     * @param filterView      隐藏的筛选栏View
     * @param bodyBean        数据bean
     * @param allFiltersBean  已选择的筛选bean
     * @param mConfideAdapter section适配器
     */
    override fun showSexAgePopupWindow(v_line_top: View, filterView: ConfideHomeFilterView, bodyBean: ConfideHomeBodyBean?, allFiltersBean: ConfideHomeAllFiltersBean, mConfideAdapter: ConfideHomeAdapter) {
        if (null == bodyBean || ((null == bodyBean.group || bodyBean.group!!.isEmpty()) && (null == bodyBean.group!![0].data || bodyBean.group!![0].data!!.isEmpty()))) {
            ToastUtil.toastShort( "数据初始化失败，请重新下拉刷新")
            return
        }
        val sexData = ArrayList<ConfideHomeFiterItemBean>()
        if (null != bodyBean.group!![0].data) {
            sexData.addAll(bodyBean.group!![0].data!!)
        }
        val ageData = ArrayList<ConfideHomeFiterItemBean>()
        if (1 < bodyBean.group!!.size && null != bodyBean.group!![1].data) {
            ageData.addAll(bodyBean.group!![1].data!!)
        }
        val categoryPopup = ConfideHomeSexAgePopupWindow(mContext!!, sexData, ageData, allFiltersBean)
        ConfideHomeUtils.synchroStyle(mContext!!, 2, IConfideHomeConfig.FILTER_STATUS_OPEN, filterView, mConfideAdapter)
        categoryPopup!!.setOnDismissListener {
            if (allFiltersBean.selectSex!!.id != "-1" || allFiltersBean.selectAgeData!!.size > 0) {
                ConfideHomeUtils.synchroTextColor(mContext!!, 2, IConfideHomeConfig.FILTER_STATUS_FILTERED, filterView, mConfideAdapter)
            } else {
                ConfideHomeUtils.synchroTextColor(mContext!!, 2, IConfideHomeConfig.FILTER_STATUS_NORMAL, filterView, mConfideAdapter)
            }
        }
        categoryPopup!!.onGoodSelectedListener = object : ConfideHomeSexAgePopupWindow.OnSexAgeSelectedListener {
            override fun onSexAgeSelected(sexData: ConfideHomeFiterItemBean, ageData: ArrayList<ConfideHomeFiterItemBean>) {
                var ageBuild = StringBuilder()
                if (ageData != null) {
                    for (data in ageData) {
                        ageBuild.append("${data.name};")
                    }
                }

                ConfideHomeUtils.synchroTextColor(mContext!!, 2, IConfideHomeConfig.FILTER_STATUS_OPEN, filterView, mConfideAdapter)
                allFiltersBean.selectSex!!.name = sexData.name
                allFiltersBean.selectSex!!.id = sexData.id
                allFiltersBean.selectAgeData!!.clear()
                allFiltersBean.selectAgeData!!.addAll(ageData)
                confideHomeView.recommendList(1)
                categoryPopup.dismiss()
            }
        }
        categoryPopup!!.showAsDropDown(v_line_top)
    }

    /**
     * 显示擅长方向弹窗
     * @param v_line_top      显示弹窗的位置
     * @param filterView      隐藏的筛选栏View
     * @param bodyBean        数据bean
     * @param allFiltersBean  已选择的筛选bean
     * @param mConfideAdapter section适配器
     */
    override fun showGoodPopupWindow(v_line_top: View, filterView: ConfideHomeFilterView, bodyBean: ConfideHomeBodyBean?, allFiltersBean: ConfideHomeAllFiltersBean, mConfideAdapter: ConfideHomeAdapter) {
        if (bodyBean != null && null != bodyBean.group && !bodyBean.group!!.isEmpty() && null != bodyBean.group!![0].data && !bodyBean.group!![0].data!!.isEmpty()) {
            val categoryPopup = ConfideHomeGoodPopupWindow(mContext!!, bodyBean.group!![0].data!!, allFiltersBean.selectGoodData!!)
            ConfideHomeUtils.synchroStyle(mContext!!, 3, IConfideHomeConfig.FILTER_STATUS_OPEN, filterView, mConfideAdapter)
            categoryPopup!!.setOnDismissListener {
                if (allFiltersBean.selectGoodData!!.size > 1 || (allFiltersBean.selectGoodData!!.size == 1 && allFiltersBean!!.selectGoodData!![0] != bodyBean.group!![0].data!![0])) {
                    ConfideHomeUtils.synchroTextColor(mContext!!, 3, IConfideHomeConfig.FILTER_STATUS_FILTERED, filterView, mConfideAdapter)
                } else {
                    ConfideHomeUtils.synchroTextColor(mContext!!, 3, IConfideHomeConfig.FILTER_STATUS_NORMAL, filterView, mConfideAdapter)
                }
            }
            categoryPopup!!.onGoodSelectedListener = object : ConfideHomeGoodPopupWindow.OnGoodSelectedListener {
                override fun onGoodSelected(selectedGoodsList: ArrayList<ConfideHomeFiterItemBean>) {
                    var ageBuild = StringBuilder()
                    if (selectedGoodsList != null) {
                        for (data in selectedGoodsList) {
                            ageBuild.append("${data.name};")
                        }
                    }

                    ConfideHomeUtils.synchroTextColor(mContext!!, 3, IConfideHomeConfig.FILTER_STATUS_OPEN, filterView, mConfideAdapter)
                    allFiltersBean.selectGoodData.clear()
                    allFiltersBean.selectGoodData.addAll(selectedGoodsList)
                    confideHomeView.recommendList(1)
                    categoryPopup.dismiss()
                }
            }
            categoryPopup!!.showAsDropDown(v_line_top)
        } else {
            ToastUtil.toastShort("数据初始化失败，请重新下拉刷新")
        }
    }
}