package com.yidianling.consultant.modular.singlton

import android.annotation.SuppressLint
import android.app.Activity
import android.content.SharedPreferences
import android.support.v7.app.AppCompatActivity
import android.text.TextUtils
import com.ydl.ydlcommon.data.http.ThrowableConsumer
import com.ydl.ydlcommon.utils.SharedPreferencesEditor
import com.ydl.ydlcommon.utils.YdlBuryPointUtil
import com.ydl.ydlcommon.utils.remind.ToastHelper
import com.yidianling.common.tools.ToastUtil
import com.yidianling.consultant.ConsultAssistantCenterActivity
import com.yidianling.consultant.dialog.ConsultAssistantDialog
import com.yidianling.consultant.model.SearchApi
import com.yidianling.consultant.router.ConsultantIn
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import java.util.*

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

    companion object {
        val INSTANCE by lazy { ConsultAssistantDialogUtils() }
    }

    var consultAssistantDialogFromHomePage: 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)
                }
            }
        }

    }

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

//        if (origin == "home_index") {
//            showFromYdlHome(activity)
//        } else if (origin == "doctor_list") {
//            show(activity, fromActivity)
//        }

        // 请求接口判断导医咨询助理按钮是否展示
        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, fromActivity)
                    }
                }
            }
    }

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

    /**
     * 首页页展示
     */
    fun showFromYdlHome(activity: Activity) {
        if (!activity.isFinishing) {
            if (consultAssistantDialogFromHomePage == null) {
                consultAssistantDialogFromHomePage = ConsultAssistantDialog(
                    activity,
                    object : ConsultAssistantDialog.OnConsultAssistantClickListener {
                        override fun onClickAction() {
                            //获取用户uid
                            YdlBuryPointUtil.sendClick("home_page_assistant_click")
                            getConsultAssistantUid(activity)
                        }

                    })
            }
            consultAssistantDialogFromHomePage?.show()
        }
    }

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

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

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

    /**
     * 咨询师列表页展示浮层
     */
    fun showDialog(activity: Activity, fromActivity: Boolean = false) {
        if (!fromActivity) {
            if (!activity.isFinishing) {
                if (consultAssistantFragmentDialog == null) {
                    consultAssistantFragmentDialog = ConsultAssistantDialog(
                        activity,
                        object : ConsultAssistantDialog.OnConsultAssistantClickListener {
                            override fun onClickAction() {
                                YdlBuryPointUtil.sendClick("assistant_list_click")
                                // 咨询师列表页面且未登录情况下，跳转登录页面
                                if (!ConsultantIn.isLogin()) {
                                    ConsultantIn.toLogin(activity)
                                } else {
                                    //获取用户uid
                                    getConsultAssistantUid(activity)
                                }
                            }

                        })
                }
                consultAssistantFragmentDialog?.show()
            }
        } else {
            if (!activity.isFinishing) {
                if (consultAssistantActivityDialog == null) {
                    consultAssistantActivityDialog = ConsultAssistantDialog(
                        activity,
                        object : ConsultAssistantDialog.OnConsultAssistantClickListener {
                            override fun onClickAction() {
                                YdlBuryPointUtil.sendClick("assistant_list_click")
                                // 咨询师列表页面且未登录情况下，跳转登录页面
                                if (!ConsultantIn.isLogin()) {
                                    ConsultantIn.toLogin(activity)
                                } else {
                                    //获取用户uid
                                    getConsultAssistantUid(activity)
                                }
                            }

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


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

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

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

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

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

        expertSearchActivityPageHasShown = false
        consultAssistantActivityDialog = null
    }

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

    @SuppressLint("CheckResult")
    fun getConsultAssistantUid(activity: Activity) {
        // 请求接口获取咨询助理的uid
        SearchApi.getSearchApi().getConsultAssistantUidRequest()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe( Consumer {
                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 false
    }

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