package com.channel.ydl_flutter_base.plugin

import android.text.TextUtils
import com.channel.ydl_flutter_base.base.BaseFlutterFragment
import com.channel.ydl_flutter_base.event.MainScrollEnableEvent
import com.ydl.ydlcommon.base.BaseApp
import com.ydl.ydlcommon.base.config.YDLConstants
import com.ydl.ydlcommon.data.PlatformDataManager
import com.ydl.ydlcommon.data.http.GsonProvider
import com.ydl.ydlcommon.modular.ModularServiceManager
import com.ydl.ydlcommon.router.YdlCommonOut
import com.ydl.ydlcommon.utils.LogUtil
import com.ydl.ydlcommon.utils.SharedPreferencesEditor
import com.ydl.ydlcommon.utils.YDLCacheUtils
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.yidianling.common.tools.RxDeviceTool
import de.greenrobot.event.EventBus
import io.flutter.app.FlutterActivity
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.view.FlutterView

/**
 * Created by xj on 2019/11/19.
 */
class YDLCommonPlugin : MethodChannel.MethodCallHandler {

    constructor()

    private var mActivity: FlutterActivity? = null

    private constructor(activity: FlutterActivity) {
        mActivity = activity
    }

    private var mFragment: BaseFlutterFragment? = null

    private constructor(fragment: BaseFlutterFragment) {
        mFragment = fragment
    }

    companion object {
        var pluginDelegate: CommonPluginDelegate? = null
        const val CHANNEL: String = "lib/common/channel"
        const val GETPUBLICPARAMAS: String = "getPublicParamas"
        const val GET_PACKAGE_AND_FFROM: String = "get_package_and_ffrom" // 获取包名和渠道名，中间用，分割
        const val ACTION_PUSH_EVENT_TRACKING_TAP: String = "action_push_event_tracking_tap"// 点击事件埋点
        const val ACTION_PUSH_EVENT_TRACKING_PV: String = "action_push_event_tracking_pv"//pv埋点
        const val ACTION_ORIGIN_THEME: String = "platform_origin_theme"//马甲包获取应用各个主题色的action
        const val ACTION_GET_SUB_CHANNEL_THEME: String = "action_page_layout_params"//获取子频道主页样式
        const val REQUESTMAINSCROLLFOCUS: String = "requestMainScrollFocus"
        const val RELEASEMAINSCROLLFOCUS: String = "releaseMainScrollFocus"
        const val ACTION_HTTP_BURIED_POINT: String = "action_http_buried_point"
        const val PAGE_GO_BACK: String = "pageGoBack" //返回上一页

        //activity注册
        fun activityRegister(activity: FlutterActivity) {
            MethodChannel(activity.flutterView, CHANNEL).setMethodCallHandler(
                YDLCommonPlugin(
                    activity
                )
            )
        }

        //fragment注册
        fun fragmentRegister(fragment: BaseFlutterFragment, flutterView: FlutterView) {
            MethodChannel(flutterView, CHANNEL).setMethodCallHandler(YDLCommonPlugin(fragment))
        }
    }

    override fun onMethodCall(methodCall: MethodCall, result: MethodChannel.Result) {
        when (methodCall.method) {
            GETPUBLICPARAMAS -> {
                val loginBean = ModularServiceManager.getPlatformUserService()?.getUser()
                val mMap = mutableMapOf<String, Any>()
                var uid = loginBean?.userId ?: ""

                val appEnv = BaseApp.instance.getGlobalConfig().appEnv
                val cacheAppEnv = YDLCacheUtils.getCacheApi()

                var isDevelopment = "0"

                if (!TextUtils.isEmpty(cacheAppEnv)) {
                    if (YDLConstants.ENV_TEST == cacheAppEnv || YDLConstants.ENV_AUTO_TEST == cacheAppEnv) {
                        isDevelopment = "1"
                    } else if (YDLConstants.ENV_NEW_TEST == cacheAppEnv) {
                        isDevelopment = "2"
                    }
                } else {
                    if ( YDLConstants.ENV_TEST == appEnv) {
                        isDevelopment = "1"
                    } else if (YDLConstants.ENV_NEW_TEST == appEnv) {
                        isDevelopment = "2"
                    }
                }
                com.yidianling.common.tools.LogUtil.e("aaaaacommon"+isDevelopment+"环境"+appEnv)

                mMap["isDevelopment"] = isDevelopment

                mMap["uid"] = if (TextUtils.isEmpty(uid)) "0" else uid
                mMap["accessToken"] = loginBean?.token ?: ""
                        ?: ""
                mMap["isFromApp"] = "1"
                mMap["ffrom"] = PlatformDataManager.getRam().getChannelName()
                mMap["version"] = RxDeviceTool.getAppVersionName(BaseApp.getApp())
                mMap["osBuild"] =
                    RxDeviceTool.getBuildMANUFACTURER() + "," + RxDeviceTool.getBuildBrandModel() + "," + RxDeviceTool.getOsBuileVersion() + "," + RxDeviceTool.getAppVersionName(
                        BaseApp.getApp()
                    )
                var res = SharedPreferencesEditor.getString("flutter_proxy_sp_ip")
                mMap["proxyIp"] = if (TextUtils.isEmpty(res)) "" else res
                result.success(mMap)
            }
            ACTION_PUSH_EVENT_TRACKING_TAP -> {
                val map = methodCall.arguments as HashMap<*, *>
                val clickPath = map["path"] as String
                if (!TextUtils.isEmpty(clickPath)) {

                    try {
                        val ownerClass = Class.forName("com.ydl.burypointlib.BuryPointHelper")
                        val field = ownerClass.getDeclaredField("openEdit")
                        field.isAccessible = true

                    } catch (e: Exception) {
                        LogUtil.e("flutter click exception:$e")
                    }
                }
            }

            ACTION_PUSH_EVENT_TRACKING_PV -> {

            }
            ACTION_ORIGIN_THEME -> {
                val mMap = mutableMapOf<String, String>()
                if (pluginDelegate != null) {
                    val appTheme = pluginDelegate?.getAppTheme()
                    appTheme?.let { mMap.putAll(it) }
                }
                LogUtil.i("platform_origin_theme:" + GsonProvider.getGson().toJson(mMap))
                result.success(mMap)
            }
            ACTION_GET_SUB_CHANNEL_THEME -> {
                val mMap = arrayListOf<Any>()

                if (pluginDelegate != null) {
                    if (methodCall.hasArgument("channelName")) {
                        val channelName = methodCall.argument<String>("channelName")
                        LogUtil.i("platform_sub_channel_theme channelName:$channelName")
                        if (!TextUtils.isEmpty(channelName)) {
                            val appTheme = pluginDelegate?.getSubChannelTheme(channelName!!)
                            appTheme?.let { mMap.addAll(it) }
                        }
                    }
                }
                LogUtil.i("platform_sub_channel_theme:" + GsonProvider.getGson().toJson(mMap))
                result.success(mMap)
            }
            REQUESTMAINSCROLLFOCUS -> {
                EventBus.getDefault().post(
                    MainScrollEnableEvent(
                        false
                    )
                )
            }
            RELEASEMAINSCROLLFOCUS -> {
                EventBus.getDefault().post(
                    MainScrollEnableEvent(
                        true
                    )
                )
            }
            GET_PACKAGE_AND_FFROM -> {
                val packageName = YdlCommonOut.getApp().packageName
                val ffrom = PlatformDataManager.getRam().getChannelName()
                result.success("$packageName,$ffrom")
            }
            ACTION_HTTP_BURIED_POINT -> {
                val map = methodCall.arguments as HashMap<*, *>
                val position = map["position"] as String
                val partId = map["partId"] as String
                val sign = map["sign"] as String

                ActionCountUtils.count("$partId|$position", sign)

            }
            PAGE_GO_BACK -> {
                mActivity?.finish()
            }
        }
    }

    interface CommonPluginDelegate {
        fun getAppTheme(): HashMap<String, String>

        fun getSubChannelTheme(channelName: String): ArrayList<Any>
    }
}