package com.yidianling.home.event

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import android.text.TextUtils
import android.view.View
import com.alibaba.android.arouter.launcher.ARouter
import com.ydl.media.audio.AudioPlayer
import com.ydl.media.audio.model.Music
import com.ydl.media.view.PlayTypeEnum
import com.ydl.media.view.PlayerFloatHelper
import com.ydl.webview.H5Params
import com.ydl.webview.NewH5Activity
import com.ydl.ydl_router.manager.YDLRouterManager
import com.ydl.ydl_router.manager.YDLRouterParams
import com.ydl.ydl_router.util.YDLRouterParamsUrls
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.base.config.HttpConfig
import com.ydl.ydlcommon.bean.ShareData
import com.ydl.ydlcommon.data.PlatformRamImpl
import com.ydl.ydlcommon.modular.ModularServiceManager
import com.ydl.ydlcommon.router.IYDLRouterConstant
import com.ydl.ydlcommon.utils.LogUtil
import com.ydl.ydlcommon.utils.Utils
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.ydl.ydlcommon.utils.remind.ToastHelper
import com.ydl.ydlcommon.view.dialog.CommonDialog
import com.yidianling.home.R
import com.yidianling.home.api.event.HomeModuleTabEvent
import com.yidianling.home.constants.HomeBIConstants
import com.yidianling.home.constract.IHomeContract
import com.yidianling.home.model.bean.*
import com.yidianling.im.api.bean.IMRequestCallback
import com.yidianling.im.api.service.IImService
import com.yidianling.tests.api.service.ITestsApiService
import com.yidianling.user.api.service.IUserService
import de.greenrobot.event.EventBus
import org.json.JSONObject

open class HomeBaseImpl : IHomeBaseEvent {

    val HOT_SEARCH_DOCTOR_NAME = "hot_search_doctor_name"
    override fun consultItemClick(linkUrl: String?, doctorId: String) {
        if (Utils.isFastClick()) {
            //防止连击
            return
        }
        ActionCountUtils.count(HomeBIConstants.YDL_USER_EXPERT_INTRODUCTION_CLICK, doctorId)

        if (null == linkUrl || linkUrl.isEmpty()) {
            return
        }
        if (linkUrl.startsWith("http")) {
            YDLRouterManager.router(
                IYDLRouterConstant.ROUTER_H5_H5,
                YDLRouterParams().putExtra(IYDLRouterConstant.EXTRA_URL, linkUrl), ""
            )
        } else {
            YDLRouterManager.router(linkUrl)
        }
    }

    override fun consultChatClick(doctorId: String?) {
        if (Utils.isFastClick()) {
            //防止连击
            return
        }
        ActionCountUtils.count(
            HomeBIConstants.YDL_USER_PRIVATE_CHAT_CLICK, doctorId
                ?: ""
        )

        if (!ModularServiceManager.provide(IUserService::class.java).loginByOneKeyLogin(mContext as Context,true)) {
            //跳转登录
            return
        }
        if (mContext is AppCompatActivity && !TextUtils.isEmpty(doctorId)) {
            //私聊
            YDLRouterManager.router(
                IYDLRouterConstant.ROUTER_CHAT_PRIVATE,
                YDLRouterParams()
                    .putExtra(IYDLRouterConstant.EXTRA_TOUID, doctorId!!)
                    .putExtra(IYDLRouterConstant.EXTRA_USERTYPE, "1")
            )
        }
    }

    fun jumpToLogin() {
        ARouter.getInstance().build("/user/login")
            .navigation()
    }

    /**
     * 获取咨询列表数据
     * 最终调用
     * @see com.yidianling.home.ui.fragment.YdlHomeFragment.getConsultData
     *
     * @param type 倾述类型
     * @param selectPosition 选中的position
     */
    override fun getConsultData(type: HomeHeaderBean.ConsultCategoryDateBean, selectPosition: Int) {
        ActionCountUtils.count(
            HomeBIConstants.YDL_USER_CONSULT_TYPE_CLICK, type.name
                ?: ""
        )
        mHomeView!!.getConsultData(type.id.toString(), selectPosition)
    }


    private var headerView: View? = null
    var mContext: Context? = null
    var mHomeView: IHomeContract.View? = null
    var COURSE_DETAIL_H5 = HttpConfig.WEB_URL + "fe-app-yidianling/course/Detail/"


    constructor(context: Context, homeView: IHomeContract.View) {
        mContext = context
        this.mHomeView = homeView
    }

    override fun onPageScroll(view_rl_top_bg: View): RecyclerView.OnScrollListener? {
        return object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (headerView == null) headerView = recyclerView.getChildAt(0)
                val top = headerView?.top
                val height = Math.abs(top!!)
                var per = height.toFloat() / 500
                //最大比例为1
                if (per > 1f) {
                    per = 1f
                }
                val alpha = (per * 255).toInt()
                LogUtil.i("Tag", "alpha=$alpha--per=$per")
                view_rl_top_bg.background.mutate().alpha = alpha
            }
        }
    }


    override fun serviceCallClick() {
        try {
            if (Utils.isFastClick()) {
                //防止连击
                return
            }
            ActionCountUtils.count(HomeBIConstants.YDL_USER_TELEPHONE_CUSTOMER_SERVICE_CLICK)
            val tel =
                if (PlatformRamImpl.getInstance().getGlobalInfo() == null) "400-765-1010" else PlatformRamImpl.getInstance().getGlobalInfo()!!.info.tel
            var con = "\n400-765-1010\n早8:30-凌晨2:00"
            if (PlatformRamImpl.getInstance().getGlobalInfo() != null && PlatformRamImpl.getInstance().getGlobalInfo()!!.info != null) {
                con =
                    PlatformRamImpl.getInstance().getGlobalInfo()?.info?.tel + "\n" + PlatformRamImpl.getInstance().getGlobalInfo()?.info?.work_time

            }
            val dialog = CommonDialog(mContext)
                .setTitle("欢迎致电壹点灵客服热线")
                .setMessage(con)
                .setLeftOnclick("取消") { v1 ->

                }.setRightClick("拨打") { v12 ->
                    val phoneIntent = Intent(
                        Intent.ACTION_DIAL,
                        Uri.parse("tel:$tel")
                    )
                    mContext?.startActivity(phoneIntent)
                }
            dialog.setMessageOnclick {

            }
            dialog.show()
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    override fun searchTvClick(text: String) {
        if (Utils.isFastClick()) {
            //防止连击
            return
        }
        var doctorName =
            if (text != mContext?.resources?.getString(R.string.home_search_hint) && text != mContext?.resources?.getString(
                    R.string.platform_search
                )
            ) text else ""

        ARouter.getInstance()
            .build("/consult/hot_search")
            .withString(HOT_SEARCH_DOCTOR_NAME, doctorName)
            .navigation()
    }

    override fun consultMoreClick() {
        if (Utils.isFastClick()) {
            //防止连击
            return
        }
        EventBus.getDefault().post(
            HomeModuleTabEvent(
                2
            )
        )
        ActionCountUtils.count(HomeBIConstants.YDL_USER_CONSULT_MORE_CLICK)
    }


    override fun bannerClick(banner: HomeHeaderBean.FocusListBean) {
        ActionCountUtils.count(HomeBIConstants.YDL_USER_BANNER_CLICK, banner.focId.toString())
        linkTo(banner.linkUrl.toString())
    }


    override fun categoryClick(data: HomeHeaderBean.AskCategoryDataBean) {
//        linkTo(data.url.toString())
        if (Utils.isFastClick()) {
            //防止连击
            return
        }
        ActionCountUtils.count(
            HomeBIConstants.YDL_USER_CONSULT_CLASSIFICATION_CLICK,
            data.cateId.toString(),
            data.cateTitle
                ?: ""
        )
        goExpertSearch(data)
    }

    private fun goExpertSearch(data: HomeHeaderBean.AskCategoryDataBean) {
        if (!TextUtils.isEmpty(data.url) && data.url!!.endsWith("?")) {
            data.url = data.url!!.substring(0, data.url!!.length - 1)
        }
        if ("全部类别" == data.cateTitle || "全部分类" == data.cateTitle) {
            /*YDLRouterManager.router(
                IYDLRouterConstant.ROUTER_H5_H5,
                YDLRouterParams().putExtra(
                    IYDLRouterConstant.EXTRA_URL,
                    HttpConfig.H5_URL + "experts/cates"
                )
            )*/
            //因心理咨询迁移新系统，跳转咨询列表页
            EventBus.getDefault().post(HomeModuleTabEvent(2))
        } else {
            //跳转咨询频道页 服务入口
            YDLRouterManager.router(
                IYDLRouterConstant.ROUTER_CONSULT_LIST,
                YDLRouterParams().putExtra(
                    IYDLRouterConstant.EXTRA_CATEID,
                    data.cateId.toString()
                ).putExtra(
                    IYDLRouterConstant.EXTRA_CATETITLE, data.cateTitle!!
                ).putExtra(
                    IYDLRouterConstant.EXTRA_SHOWTYPE, "0"
                )
            )
        }
    }

    override fun linkTo(linkUrl: String) {
        if (Utils.isFastClick()) {
            //防止连击
            return
        }
        YDLRouterManager.router(linkUrl)
    }

    override fun reservationExpertsClick() {
        if (Utils.isFastClick()) {
            //防止连击
            return
        }
        EventBus.getDefault().post(
            HomeModuleTabEvent(
                2
            )
        )
        ActionCountUtils.count(HomeBIConstants.YDL_USER_CONSULT_CLICK)
    }

    override fun nowConfideClick() {
        if (Utils.isFastClick()) {
            //防止连击
            return
        }
        ActionCountUtils.count(HomeBIConstants.YDL_USER_TALK_IN_TIME_CLICK)

        //倾诉首页 ydl-user://confide/home
        YDLRouterManager.router(IYDLRouterConstant.ROUTER_CONFIDE_HOME)
    }

    override fun psychologyClassClick() {
        if (Utils.isFastClick()) {
            //防止连击
            return
        }
        //课程频道页 ydl-user://course/home
//        YDLRouterManager.router(IYDLRouterConstant.ROUTER_COURSE_HOME)
        //埋点
        ActionCountUtils.count(HomeBIConstants.YDL_USER_PSYCHOLOGICAL_CLASSROOM_CLICK)

        ARouter.getInstance().build("/course/home").navigation()
    }

    override fun psychologyTestClick() {
        if (Utils.isFastClick()) {
            //防止连击
            return
        }
        ActionCountUtils.count(HomeBIConstants.YDL_USER_PSYCHOLOGICAL_TEST_CLICK)
        //测评频道首页 ydl-user://ceshi/home
//        YDLRouterManager.router(IYDLRouterConstant.ROUTER_TEST_HOME)
        ARouter.getInstance().build("/ceshi/home").navigation()
    }

    override fun confideMoreClick() {
        if (Utils.isFastClick()) {
            //防止连击
            return
        }
        ActionCountUtils.count(HomeBIConstants.YDL_USER_LISTEN_MORE_CLICK)

        //倾诉首页 ydl-user://qingshu/home
        YDLRouterManager.router(IYDLRouterConstant.ROUTER_CONFIDE_HOME)
    }

    /**
     * 倾述咨询师点击
     * @param linkUrl 跳转地址
     */
    override fun confideClick(linkUrl: String?, doctorId: Int) {
        if (Utils.isFastClick()) {
            //防止连击
            return
        }
        if (null == linkUrl || linkUrl.isEmpty()) {
            return
        }

        ActionCountUtils.count(
            HomeBIConstants.YDL_USER_LISTENER_INTRODUCTION_CLICK,
            doctorId.toString()
        )

        if (linkUrl.startsWith("http")) {
            YDLRouterManager.router(
                IYDLRouterConstant.ROUTER_H5_H5,
                YDLRouterParams().putExtra(IYDLRouterConstant.EXTRA_URL, linkUrl), ""
            )
        } else {
            YDLRouterManager.router(linkUrl)
        }
    }

    /**
     * 私聊
     */
    override fun toChatForMsg(doctorId: String?) {
        if (Utils.isFastClick()) {
            //防止连击
            return
        }
        if (!ModularServiceManager.provide(IUserService::class.java).loginByOneKeyLogin(mContext as Context,true)) {
            //判断登录状态内部已完成 跳转登录
            return
        }
        if (mContext is AppCompatActivity && !TextUtils.isEmpty(doctorId)) {
            //私聊
            YDLRouterManager.router(
                IYDLRouterConstant.ROUTER_CHAT_PRIVATE,
                YDLRouterParams()
                    .putExtra(IYDLRouterConstant.EXTRA_TOUID, doctorId!!)
                    .putExtra(IYDLRouterConstant.EXTRA_USERTYPE, "1")
            )
        }
        ModularServiceManager.provide(IImService::class.java)
            .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("发送异常")
                }
            })
    }


    override fun courseMreClick() {
        if (Utils.isFastClick()) {
            //防止连击
            return
        }
        //课程频道页 ydl-user://course/home
//        YDLRouterManager.router(IYDLRouterConstant.ROUTER_COURSE_HOME)
        ActionCountUtils.count(HomeBIConstants.YDL_USER_COURSE_MORE_CLICK)
        ARouter.getInstance().build("/course/home").navigation()
    }

    override fun courseItemClick(bean: HomeCourseBean.ListBean) {
        if (Utils.isFastClick()) {
            //防止连击
            return
        }
        ActionCountUtils.count(HomeBIConstants.YDL_USER_COURSE_CLICK, bean.id.toString())

        val h5Params = H5Params(
            COURSE_DETAIL_H5 + bean.id,
            mContext?.getString(R.string.platform_course_detail)
        )
        if (!TextUtils.isEmpty(bean.shareData?.shareUrl)) {
            val shareData = ShareData(
                bean.shareData?.shareUrl,
                bean.shareData?.title,
                bean.shareData?.cover,
                bean.shareData?.desc
            )
            h5Params.shareData = shareData
        }

        NewH5Activity.start(mContext, h5Params)
    }

    override fun askItemFocusClick(position: Int, id: String) {
        if (!ModularServiceManager.provide(IUserService::class.java).loginByOneKeyLogin(mContext as Context,true)) {
            //判断登录状态内部已完成 跳转登录
            return
        }
        //关注用户
        mHomeView?.askFocus(position, id)
    }

    override fun askItemZanClick(position: Int, index: Int, id: String) {
        if (!ModularServiceManager.provide(IUserService::class.java).loginByOneKeyLogin(mContext as Context,true)) {
            //判断登录状态内部已完成 跳转登录
            return
        }
        //问答动态点赞
        mHomeView?.askZan(position, index, id)
    }

    override fun askMoreClick() {
        if (Utils.isFastClick()) {
            //防止连击
            return
        }
        ActionCountUtils.count(HomeBIConstants.YDL_USER_ASK_MORE_CLICK)
        //心事动态频道页（首页--问答） ydl-user://answers/home
        YDLRouterManager.router(IYDLRouterConstant.ROUTER_ANSWERS_HOME)
    }

    override fun fmItemClick(bean: HomeFMBean.ListBean) {
        if (Utils.isFastClick()) {
            //防止连击
            return
        }
        ActionCountUtils.count(HomeBIConstants.YDL_USER_RADIO_CLICK, bean.id.toString())
        //电台详情页面
        YDLRouterManager.router(
            IYDLRouterConstant.ROUTER_FM_DETAIL,
            YDLRouterParams().putExtra(IYDLRouterConstant.EXTRA_ID, bean.id.toString())
        )
    }

    override fun fmPlayClick(fmDetail: HomeFMBean.ListBean) {
        ActionCountUtils.count(HomeBIConstants.YDL_USER_RADIO_PLAY_CLICK, fmDetail.id.toString())

        if (!TextUtils.isEmpty(fmDetail.fmUrl)) {
            val music = Music()
            music.path = fmDetail.fmUrl
            music.album = fmDetail.imageUrl
            music.artist = fmDetail.author
            music.coverPath = fmDetail.imageUrl
            music.title = fmDetail.name
            AudioPlayer.get().singlePlay(music, false)
            PlayerFloatHelper.playingType = PlayTypeEnum.PLAY_TYPE_FM
        }

        PlayerFloatHelper.isCanClick = true
        if (PlayerFloatHelper.isShow(mContext!!)) {
            if (PlayerFloatHelper.playingType != PlayTypeEnum.PLAY_TYPE_FM) {
                PlayerFloatHelper.removeView(mContext!!)

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

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

    override fun fmMoreClick() {
        if (Utils.isFastClick()) {
            //防止连击
            return
        }
        ActionCountUtils.count(HomeBIConstants.YDL_USER_HEART_RADIO_MORE_CLICK)
        //fm列表页  ydl-user://fm/list
        YDLRouterManager.router(IYDLRouterConstant.ROUTER_FM_LIST)
    }

    override fun articleItemClick(bean: HomeArticleBean.Bean?) {
        if (Utils.isFastClick()) {
            //防止连击
            return
        }
        if (bean == null) {
            return
        }

        ActionCountUtils.count(HomeBIConstants.YDL_USER_ARTICLE_CLICK, bean.id.toString())

        YDLRouterManager.router(
            IYDLRouterConstant.ROUTER_H5_H5,
            YDLRouterParams().putExtra(IYDLRouterConstant.EXTRA_URL, bean.gethUrl()!!), ""
        )
    }

    override fun articleMoreClick() {
        if (Utils.isFastClick()) {
            //防止连击
            return
        }
        ActionCountUtils.count(HomeBIConstants.YDL_USER_ARTICLE_MORE_CLICK)

        //文章列表页 ydl-user://article/list
        ARouter.getInstance().build("/article/list").navigation()
//        YDLRouterManager.router(IYDLRouterConstant.ROUTER_ARTICLE_LIST)
    }

    override fun askItemClick(bean: HomeAskBean.DataBean) {
        if (Utils.isFastClick()) {
            //防止连击
            return
        }
        ActionCountUtils.count(HomeBIConstants.YDL_USER_ASK_COMMENT_CLICK, bean.id.toString())
        val bundle = Bundle()
        bundle.putInt("trend_id", bean.id)
        bundle.putInt("comment_count", bean.commentsCount)
        bundle.putBoolean("is_comment", false)

        //动态详情
        ARouter.getInstance().build("/trends/detail")
            .withBundle("bundle", bundle)
            .navigation()
    }

    override fun publishTrendClick() {

        val bundle = Bundle()
        bundle.putString("publish_type", "topic_publish")
        bundle.putString("topic_id", "44")
        bundle.putString("topic_title", "今日打卡")

        //发布动态
        ARouter.getInstance().build("/trend/publish")
            .withBundle("bundle", bundle)
            .navigation()
    }


    /**
     * 获取倾述列表数据
     * 最终调用
     * @see com.yidianling.home.ui.fragment.YdlHomeFragment.getConfideData
     *
     * @param type 倾述类型
     * @param selectPosition 选中的position
     */
    override fun getConfideData(type: HomeHeaderBean.ListenCategoryDateBean, selectPosition: Int) {
        ActionCountUtils.count(
            HomeBIConstants.YDL_USER_LISTEN_TYPE_CLICK, type.name
                ?: ""
        )
        mHomeView!!.getConfideData(type.id.toString(), selectPosition)
    }

    override fun testItemClick(linkUrl: String?) {
        if (Utils.isFastClick()) {
            //防止连击
            return
        }
        if (null == linkUrl || linkUrl.isEmpty()) {
            return
        }
        if (linkUrl.startsWith("app")) {
            val uri = Uri.parse(linkUrl)
            if ("ceshi" == uri.host) {
                val id = uri.getQueryParameter("id")
                ModularServiceManager.provide(ITestsApiService::class.java).testDetailH5(id)
            }
        } else if (linkUrl.startsWith("http")) {
            YDLRouterManager.router(
                IYDLRouterConstant.ROUTER_H5_H5,
                YDLRouterParams().putExtra(IYDLRouterConstant.EXTRA_URL, linkUrl), ""
            )
        } else if (linkUrl.contains("ceshi/detail?")) {
            val routerParamsUrls = YDLRouterParamsUrls(linkUrl)
            val jsonObject = JSONObject(routerParamsUrls.getParams())
            ModularServiceManager.provide(ITestsApiService::class.java)
                .testDetailH5(jsonObject.getString("id").toString())
        } else {
            YDLRouterManager.router(linkUrl)
        }
    }

    override fun testMoreClick() {
        psychologyTestClick()
    }
}