package com.yidianling.consultant.modular.singlton

import android.annotation.SuppressLint
import android.app.Activity
import androidx.appcompat.app.AppCompatActivity
import com.ydl.webview.H5Params
import com.ydl.webview.NewH5Activity
import com.ydl.ydlcommon.data.PlatformDataManager
import com.ydl.ydlcommon.data.http.ThrowableConsumer
import com.ydl.ydlcommon.utils.ActivityManager
import com.ydl.ydlcommon.utils.LogUtil
import com.ydl.ydlcommon.utils.Utils
import com.ydl.ydlcommon.utils.YdlBuryPointUtil
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.ydl.ydlnet.YDLHttpUtils.Companion.obtainApi
import com.yidianling.consultant.ConsultAssistantCenterActivity
import com.yidianling.consultant.ExpertSearchActivity
import com.yidianling.consultant.constants.ConsultBIConstants
import com.yidianling.consultant.dialog.ConsultAssistantDialog
import com.yidianling.consultant.model.SearchApi
import com.yidianling.consultant.router.ConsultantIn
import com.yidianling.home.api.event.HomeModuleTabEvent
import com.yidianling.user.api.listener.LoginCallBackListener
import de.greenrobot.event.EventBus
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers

/**
 * Created by xj on 2019/11/14.
 */
class ConsultAssistantDialogUtils private constructor() {

    companion object {
        val INSTANCE by lazy { ConsultAssistantDialogUtils() }
        var isSHowDesc = true
        var REALATION_EDUCATION = false//是否跳转亲子教育字段，接口加ffrom2="learning"
    }

    var consultAssistantDialogFromHomePage: ConsultAssistantDialog? = null // 首页展示的dialog
    var consultAssistantDialogFromMine: ConsultAssistantDialog? = null // 我的展示的dialog
    var consultAssistantFragmentDialog: ConsultAssistantDialog? = null //咨询师列表fragment页面展示的dialog
    var expertSearchPageHasShown: Boolean = false // 专家咨询列表fragment页面是否已经展示
    var consultAssistantActivityDialog: ConsultAssistantDialog? = null //咨询师列表activity页面展示的dialog
    var confideListDialog: ConsultAssistantDialog? = null //倾诉列表activity页面展示的dialog
    var expertSearchActivityPageHasShown: Boolean = false // 专家咨询列表activity页面是否已经展示

    //    var ASSISTANT_DIALOG_SP_TAG = "assistant_dialog_sp_tag" // 是否展示左侧文本的缓存key
    var minWidth = 0 // 最小宽度


    /**
     *判断是否符合代码展示逻辑
     * origin 展示请求来源    首页 home_index 咨询列表 doctor_list
     * fromActivity 默认不是来自于咨询师列表activity
     */
    fun fitRequest(activity: Activity, origin: String, fromActivity: Boolean = false) {
        when (origin) {
            "home_index" -> {
                shouldShowDialog(activity, origin)
            }
            "doctor_list" -> {
                if (!ConsultantIn.isLogin() || (ConsultantIn.getUserImpl()
                        .getUserInfo()?.user_type == 1 && ConsultantIn.isLogin())
                ) {
                    shouldShowDialog(activity, origin, fromActivity = fromActivity)
                }
            }
            "mine_index" -> {
                if (ConsultantIn.isLogin() &&
                    ConsultantIn.getUserImpl().getUserInfo()?.user_type == 1
                ) {
                    shouldShowDialog(activity, origin)
                }
            }
        }

    }

    /**
     * 判断是否符合接口展示逻辑
     */
    @SuppressLint("CheckResult")
    private fun shouldShowDialog(
        activity: Activity,
        origin: String,
        fromActivity: Boolean = false
    ) {

        // 请求接口判断导医咨询助理按钮是否展示
        SearchApi.getSearchApi().getConsultAssistantRequest(origin)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                if (it.data) {
                    if (origin == "home_index") {
                        showFromYdlHome(activity)
                    } else if (origin == "doctor_list") {
                        show(activity, origin, fromActivity)
                    } else if (origin == "mine_index") {
                        showFromMine(activity)
                    }
                }
            }
    }

    //////////////////////////////////////  首页的展示隐藏逻辑 代码块start  ///////////////////////////////////////////////////

    /**
     * 首页页展示
     */
    fun showFromYdlHome(activity: Activity) {
        if (!activity.isFinishing) {
            if (consultAssistantDialogFromHomePage == null) {
                consultAssistantDialogFromHomePage = ConsultAssistantDialog(
                    activity,
                    object : ConsultAssistantDialog.OnConsultAssistantClickListener {
                        override fun onClickAction() {
                            if (Utils.isFastClick()) {
                                return@onClickAction
                            }
                            if (ConsultantIn.getUserImpl().isLogin()){
                                //获取用户uid
                                ActionCountUtils.count("main_page|main_daoyi_entry_click")
                                YdlBuryPointUtil.sendClick("home_page_assistant_click")
                                getConsultAssistantUid("", activity, 1)
                            }else{
                                ConsultantIn.getUserImpl().loginByOneKeyLoginCallBack(activity,true,object :LoginCallBackListener{
                                    override fun loginSuccess() {
                                        //获取用户uid
                                        ActionCountUtils.count("main_page|main_daoyi_entry_click")
                                        YdlBuryPointUtil.sendClick("home_page_assistant_click")
                                        getConsultAssistantUid("", activity, 1)
                                    }
                                    override fun notLogin() {
                                    }
                                })
                            }
                        }
                    })
            }
            consultAssistantDialogFromHomePage?.show()
        }
    }

    /**
     * 首页隐藏
     */
    fun hideFromHomePage() {
        consultAssistantDialogFromHomePage?.hide()
    }

    //////////////////////////////////////  首页的展示隐藏逻辑 代码块end  ///////////////////////////////////////////////////

    //////////////////////////////////////  倾诉列表页展示隐藏逻辑 代码块start  ///////////////////////////////////////////////////
    /**
     * 倾诉列表页展示
     */
    fun showFromConfideListHome(activity: Activity) {
        if (!activity.isFinishing) {
            confideListDialog = ConsultAssistantDialog(
                activity,
                object : ConsultAssistantDialog.OnConsultAssistantClickListener {
                    override fun onClickAction() {
                        if (Utils.isFastClick()) {
                            return@onClickAction
                        }
                        if (ConsultantIn.getUserImpl().isLogin()){
                            //获取用户uid
                            jumpToDyOrH5(activity)
                        }else{
                            ConsultantIn.getUserImpl().loginByOneKeyLoginCallBack(activity,true,object :LoginCallBackListener{
                                override fun loginSuccess() {
                                    //获取用户uid
                                    jumpToDyOrH5(activity)
                                }
                                override fun notLogin() {
                                }
                            })
                        }

                    }

                })
            confideListDialog?.show()
        }
    }
    /**
     * 倾诉列表页导医跳转，oppo vivo 跳转99元3小时活动
     * */
    private fun jumpToDyOrH5(activity: Activity) {
        val channelName = PlatformDataManager.getRam().getChannelName()
        if (channelName.contains("oppo") || channelName.contains("vivo")) {
            //oppo vivo
            NewH5Activity.start(activity, H5Params("https://m.ydl.com/zx/activity/lowPrice", null))
        } else {
            //去导医
            getConsultAssistantUid("", activity, 17)
        }
    }

    /**
     * 倾诉列表页隐藏
     */
    fun hideFromConfideListPage() {
        confideListDialog?.hide()
    }

    //////////////////////////////////////  倾诉列表页展示隐藏逻辑 代码块end  ///////////////////////////////////////////////////

    //////////////////////////////////////  我的展示隐藏逻辑 代码块start  ///////////////////////////////////////////////////

    /**
     * 我的页展示
     */
    fun showFromMine(activity: Activity) {
        if (!activity.isFinishing) {
            if (consultAssistantDialogFromMine == null) {
                consultAssistantDialogFromMine = ConsultAssistantDialog(
                    activity,
                    object : ConsultAssistantDialog.OnConsultAssistantClickListener {
                        override fun onClickAction() {
                            if (Utils.isFastClick()) {
                                return@onClickAction
                            }
                            getConsultAssistantUid("", activity, 4)
                        }

                    })
            }
            consultAssistantDialogFromMine?.show()
        }
    }

    /**
     * 我的隐藏
     */
    fun hideFromMine() {
        consultAssistantDialogFromMine?.hide()
    }

    //////////////////////////////////////  我的展示隐藏逻辑 代码块end  ///////////////////////////////////////////////////


    //////////////////////////////////////  咨询师列表页面的展示隐藏逻辑 代码块start  ///////////////////////////////////////////////////
    /**
     * 咨询师列表页展示
     */
    fun show(activity: Activity, origin: String, fromActivity: Boolean = false) {
        // 来自于fragment咨询师列表
        if (!fromActivity) {
            if (!expertSearchPageHasShown) {
                expertSearchPageHasShown = true
                showDialog(origin, activity)
            } else {
                showDialog(origin, activity)
            }
        } else {// 来自于activity咨询师列表
            if (!expertSearchActivityPageHasShown) {
                expertSearchActivityPageHasShown = true
                showDialog(origin, activity, true)
            } else {
                showDialog(origin, activity, true)
            }
        }
    }

    /**
     * 咨询师列表页展示浮层
     */
    fun showDialog(origin: String, activity: Activity, fromActivity: Boolean = false) {
        if (!fromActivity) {
            if (!activity.isFinishing) {
                if (consultAssistantFragmentDialog == null) {
                    consultAssistantFragmentDialog = ConsultAssistantDialog(
                        activity,
                        object : ConsultAssistantDialog.OnConsultAssistantClickListener {
                            override fun onClickAction() {
                                if (Utils.isFastClick()) {
                                    return@onClickAction
                                }
                                ActionCountUtils.count("app_consult_list_page|app_consult_list_daoyi_entry_click")
                                YdlBuryPointUtil.sendClick("assistant_list_click")

                                if (ConsultantIn.getUserImpl().isLogin()){
                                    //获取用户uid
                                    getConsultAssistantUid(origin, activity, 6)
                                }else{
                                    ConsultantIn.getUserImpl().loginByOneKeyLoginCallBack(activity,true,object :LoginCallBackListener{
                                        override fun loginSuccess() {
                                            //获取用户uid
                                            getConsultAssistantUid(origin, activity, 6)
                                        }
                                        override fun notLogin() {
                                        }
                                    })
                                }
                            }

                        })
                }
                consultAssistantFragmentDialog?.show()
            }
        } else {
            if (!activity.isFinishing) {
                if (consultAssistantActivityDialog == null) {
                    consultAssistantActivityDialog = ConsultAssistantDialog(
                        activity,
                        object : ConsultAssistantDialog.OnConsultAssistantClickListener {
                            override fun onClickAction() {
                                if (Utils.isFastClick()) {
                                    return@onClickAction
                                }
                                ActionCountUtils.count("app_consult_list_page|app_consult_list_daoyi_entry_click")
                                YdlBuryPointUtil.sendClick("assistant_list_click")
                                // 咨询师列表页面且未登录情况下，跳转登录页面
                                if (ConsultantIn.loginByOneKeyLogin(activity, true)) {
                                    //获取用户uid
                                    getConsultAssistantUid(origin, activity, 6)
                                }
                            }

                        })
                }
                consultAssistantActivityDialog?.show()
            }
        }
    }


    /**
     * 咨询师列表页Fragment隐藏
     */
    fun hide() {
        consultAssistantFragmentDialog?.dismiss()
    }

    /**
     * 咨询师列表页Fragment隐藏
     */
    fun hideAssistantActivity() {
        consultAssistantActivityDialog?.dismiss()
    }

    /**
     * 释放本单例所有资源(咨询师列表fragmnet在MainActivity，
     * 且在MainActivity销毁的时候，会先执行咨询师列表fragmnet
     * 的ondeatroy，所以这边直接在该专家咨询列表碎片执行该方法）
     */
    fun resetStatus() {
        consultAssistantDialogFromHomePage?.dismiss()
        consultAssistantDialogFromMine?.dismiss()
        consultAssistantFragmentDialog?.dismiss()
        consultAssistantActivityDialog?.dismiss()

        expertSearchPageHasShown = false
        expertSearchActivityPageHasShown = false
        consultAssistantDialogFromHomePage = null
        consultAssistantDialogFromMine = null
        consultAssistantFragmentDialog = null
        consultAssistantActivityDialog = null
    }

    /**
     * 咨询师列表activity页面使用的重置本单例关于专家咨询列表页面得状态
     */
    fun expertSearchResetStatus() {
        //页面关闭后重置亲子列表状态
        REALATION_EDUCATION = false
        consultAssistantActivityDialog?.dismiss()

        expertSearchActivityPageHasShown = false
        consultAssistantActivityDialog = null
    }

    //////////////////////////////////////  咨询师列表页面的展示隐藏逻辑 代码块end  ///////////////////////////////////////////////////

    @SuppressLint("CheckResult")
    fun getConsultAssistantUid(origin: String, activity: Activity, location: Int) {
        if (origin == "doctor_list") {
            // 请求接口获取咨询助理的uid
            if (REALATION_EDUCATION) {
                getConsultAssistantUid(location, activity, "learning")
            } else {
                getConsultAssistantUid(location, activity, null)
            }

        } else {
            // 请求接口获取咨询助理的uid
            getConsultAssistantUid(location, activity, null)
        }
        ActionCountUtils.count(
            ConsultBIConstants.POSITION_DAOYI_ADVERTISEMENT_CLICK,
            location.toString()
        )

    }

    @SuppressLint("CheckResult")
    private fun getConsultAssistantUid(location: Int, activity: Activity, ffrom: String?) {
        obtainApi(SearchApi::class.java).getChatRouteConfig(location)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(Consumer {

                if (it.data == 100L && (location <= 17)) {
                    //跳转咨询tab栏目
                    if (location == 1 || location == 4 || location == 6 || location == 3) {
                        if (activity is ExpertSearchActivity && !activity.isFinishing) {
                            activity.finish()
                        }
                        EventBus.getDefault().post(HomeModuleTabEvent(2))
                    } else {
                        if (activity.componentName.toString()
                                .contains("CourseListContainerActivity")
                        ) {
                            ActivityManager.getInstance()
                                .getSecondTaskActivity()?.finish()
                            activity.finish()
                        } else {
                            if (!activity.isFinishing) {
                                activity.finish()
                            }
                        }
                        EventBus.getDefault().post(HomeModuleTabEvent(2))
                    }
                } else if (it.data == 0L) {
                    //去前置信息收集页
                    ConsultantIn.startP2PSession(
                        activity as AppCompatActivity,
                        location,
                        ffrom
                    )
                }
                if (activity is ConsultAssistantCenterActivity && !activity.isFinishing) activity.finish()
            }, object : ThrowableConsumer() {
                override fun accept(msg: String) {
                    if (activity is ConsultAssistantCenterActivity && !activity.isFinishing) activity.finish()
                }
            }
            )
    }

    // 判定是否展示左侧的描述文本
    fun canShowDesc(): Boolean {
//        if (TextUtils.isEmpty(SharedPreferencesEditor.getString(ASSISTANT_DIALOG_SP_TAG))) {
//            //如果没有缓存，则展示
//            return true
//        } else if (System.currentTimeMillis() - SharedPreferencesEditor.getString(
//                ASSISTANT_DIALOG_SP_TAG
//            ).toLong() > 24 * 60 * 60 * 1000
//        ) {
//            //如果缓存时间超过一天，则展示
//            return true
//        }
        return isSHowDesc
    }

    fun setDescHide() {
        consultAssistantDialogFromHomePage?.setDescHide()
        consultAssistantDialogFromMine?.setDescHide()
        consultAssistantActivityDialog?.setDescHide()
        consultAssistantFragmentDialog?.setDescHide()
    }
}