package com.yidianling.consultant.modular

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Rect
import android.text.TextUtils
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ScreenUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.ydl.webview.H5JsBean
import com.ydl.ydlcommon.base.BaseApp
import com.ydl.ydlcommon.data.http.RxUtils
import com.ydl.ydlcommon.utils.SharedPreferencesEditor
import com.ydl.ydlcommon.utils.remind.HttpErrorUtils
import com.yidianling.consultant.ExpertSearchActivity
import com.yidianling.consultant.ExpertSearchFragment
import com.yidianling.consultant.OnBottomWordListener
import com.yidianling.consultant.api.IConsultantService
import com.yidianling.consultant.bean.GuideBean
import com.yidianling.consultant.bean.Keyworks
import com.yidianling.consultant.data.ConsultantDataManager
import com.yidianling.consultant.model.SearchApi
import com.yidianling.consultant.modular.singlton.ConsultAssistantDialogUtils
import com.yidianling.consultant.modular.utils.ConsultAssistantEntryUtils
import com.yidianling.consultant.preview.GPreviewBuilder
import com.yidianling.consultant.preview.UserViewInfo
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers


/**
 * Created by xj on 2019/11/14.
 */

@Route(path = "/consultant/ConsultantService")
class ConsultantServiceImp : IConsultantService {

    override fun init(context: Context?) {
    }

    override fun expertSearchIntent(
        activity: Activity,
        category: String,
        showType: Int,
        isInitShowHot: Boolean
    ): Intent {
        return ExpertSearchActivity.newIntent(activity, category, showType, isInitShowHot)
    }

    override fun getHotSearch(): MutableList<Keyworks> {
        return ConsultantDataManager.getRam().getHotSearch();
    }

    override fun setHotSearch(hotSearch: MutableList<Keyworks>) {
        return ConsultantDataManager.getRam().setHotSearch(hotSearch);
    }

    /**
     * 首页咨询助理入口
     */
    override fun showConsultAssistantDialog(activity: Activity) {
        ConsultAssistantDialogUtils.INSTANCE.fitRequest(activity, "home_index")
    }

    override fun hideConsultAssistantDialog() {
        ConsultAssistantDialogUtils.INSTANCE.hideFromHomePage()
    }

    override fun showConsultAssistantMineDialog(activity: Activity) {
        ConsultAssistantDialogUtils.INSTANCE.fitRequest(activity, "mine_index")
    }

    override fun hideConsultAssistantMineDialog() {
        ConsultAssistantDialogUtils.INSTANCE.hideFromMine()
    }

    override fun startExpertSearchActivity(
        mContext: Context,
        category: String,
        categoryName: String,
        showType: Int
    ) {
        ExpertSearchActivity.start(mContext, category, categoryName, showType)
    }

    override fun startExpertSearchActivity(mContext: Context, category: String) {
        ExpertSearchActivity.start(mContext, category)
    }

    override fun getExpertSearchFragment(): Fragment {
        return ExpertSearchFragment()
    }

    override fun getGuideImage(source: Int): List<GuideBean>? {
        val dataString = SharedPreferencesEditor.getString("guide_data")
        return if (TextUtils.isEmpty(dataString)) {
            null
        } else {
            val gson = Gson()
            val map: java.util.HashMap<String, List<GuideBean>> =
                gson.fromJson(
                    dataString,
                    object : TypeToken<java.util.HashMap<String, List<GuideBean>>>() {}.type
                )
            map[source.toString()]
        }
    }

    @SuppressLint("CheckResult")
    override fun requestGuideData() {
        SearchApi.getSearchApi().getGuideData()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                if (it.data != null && it.data.isNotEmpty()) {
                    SharedPreferencesEditor.putString("guide_data", Gson().toJson(it.data))
                }
            }, {})
    }

    override fun jumpConsultAssistant(activity: Activity, location: Int) {
        ConsultAssistantEntryUtils.jumpConsultAssistant(activity,location,null)
    }

    override fun dueToTypeJumpAutoOrGuide(
        activity: Activity,
        location: Int,
        doctorId: Int,
        url: String
    ) {
        ConsultAssistantEntryUtils.getTypeJump(activity, location, doctorId, url)
    }

    override fun showConfideListDialog(activity: Activity) {
        ConsultAssistantDialogUtils.INSTANCE.showFromConfideListHome(activity)
    }

    @SuppressLint("CheckResult")
    override fun getbottomWord(type: Int, listener: OnBottomWordListener) {
        val map = hashMapOf("type" to type)
        SearchApi.getSearchApi()
            .searchFunctionWordApi(map)
            .compose(RxUtils.resultJavaData())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ resp ->
                listener.onBottomWord(resp)
            }, { t ->
                HttpErrorUtils.handleError(BaseApp.getApp(), t)
            })
    }

    override fun resourceToPreview(dataList: List<H5JsBean.MediaInfo>?, params: H5JsBean.H5JsCmd.Params, activity: Activity) {
        val mThumbViewInfoList: MutableList<UserViewInfo> = ArrayList()
        dataList?.let {
            for (mediaInfo in it) {
                val userViewInfo =
                    UserViewInfo(mediaInfo.cover, mediaInfo.url, mediaInfo.sourcesType)
                val bounds = Rect()
                bounds.left = ScreenUtils.getScreenWidth() / 2
                bounds.top = ScreenUtils.getScreenHeight() / 2
                bounds.right = ScreenUtils.getScreenWidth() / 2
                bounds.bottom = ScreenUtils.getScreenHeight() / 2
                userViewInfo.bounds = bounds
                mThumbViewInfoList.add(userViewInfo)
            }

            GPreviewBuilder.form(activity)
                .setData(mThumbViewInfoList)
                .setCurrentIndex(params.preview_index)
                .setFullscreen(true)
                .setToUid(params.info?.toUid.toString() + "")
                .setDoctorId(params.info?.doctorId)
                .setType(GPreviewBuilder.IndicatorType.Dot)
                .start()
        }
    }

    override fun resetConsultAssistantDialogStatus() {
        ConsultAssistantDialogUtils.INSTANCE.resetStatus()
    }

}