package com.yidianling.consultant.modular.singlton

import android.annotation.SuppressLint
import android.app.Activity
import android.support.v7.app.AppCompatActivity
import com.alibaba.android.arouter.launcher.ARouter
import com.ydl.ydlcommon.data.http.ThrowableConsumer
import com.ydl.ydlcommon.utils.ActivityManager
import com.ydl.ydlcommon.utils.YdlBuryPointUtil
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.yidianling.common.tools.LogUtil
import com.yidianling.common.tools.ToastUtil
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 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 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" -> {
                if (ConsultantIn.isLogin() &&
                    ConsultantIn.getUserImpl().getUserInfo()?.user_type == 1
                ) {
                    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() {
                            //获取用户uid
                            ActionCountUtils.count("main_page|main_daoyi_entry_click")
                            YdlBuryPointUtil.sendClick("home_page_assistant_click")
                            ActionCountUtils.count(ConsultBIConstants.POSITION_DAOYI_ADVERTISEMENT_CLICK, "1")
                            getConsultAssistantUid("",activity,1)
                        }

                    })
            }
            consultAssistantDialogFromHomePage?.show()
        }
    }

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

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


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

    /**
     * 我的页展示
     */
    fun showFromMine(activity: Activity) {
        if (!activity.isFinishing) {
            if (consultAssistantDialogFromMine == null) {
                consultAssistantDialogFromMine = ConsultAssistantDialog(
                    activity,
                    object : ConsultAssistantDialog.OnConsultAssistantClickListener {
                        override fun onClickAction() {
                            //获取用户uid
                            ActionCountUtils.count(ConsultBIConstants.POSITION_DAOYI_ADVERTISEMENT_CLICK, "4")
                            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() {
                                ActionCountUtils.count(ConsultBIConstants.POSITION_DAOYI_ADVERTISEMENT_CLICK, "6")
                                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)
                                }
                            }

                        })
                }
                consultAssistantFragmentDialog?.show()
            }
        } else {
            if (!activity.isFinishing) {
                if (consultAssistantActivityDialog == null) {
                    consultAssistantActivityDialog = ConsultAssistantDialog(
                        activity,
                        object : ConsultAssistantDialog.OnConsultAssistantClickListener {
                            override fun 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?) {
        SearchApi.getSearchApi().getConsultAssistantUidRequest(location, ffrom)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(Consumer {
                if (it.data==100L&&(location<=11)){
                    //跳转咨询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 (null!=activity&&!activity.isFinishing){
                                activity.finish()
                            }
                        }
                        EventBus.getDefault().post(HomeModuleTabEvent(2))
                    }
                }else{
                    if (it.code == "200" && it.data != 0.toLong() && null != activity) {
                        ConsultantIn.startP2PSession(activity as AppCompatActivity, it.data.toString())
                    } else {
                        ToastUtil.toastShort("咨询助理忙碌中，请稍后再试")
                    }
                }
                if (null != activity && activity is ConsultAssistantCenterActivity && !activity.isFinishing) activity.finish()
            }, object : ThrowableConsumer() {
                override fun accept(msg: String) {
                    if (null != activity && 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()
    }
}