package com.channel.ydl_flutter_base.plugin

import android.app.Activity
import android.text.TextUtils
import com.channel.ydl_flutter_base.base.BaseFlutterFragment
import com.channel.ydl_flutter_base.event.MainScrollEnableEvent
import com.ydl.burypointlib.BuryPointHelper
import com.ydl.burypointlib.MD5Util
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.YdlBuryPointUtil
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 == cacheAppEnv || YDLConstants.ENV_AUTO_TEST == appEnv) {
                        isDevelopment = 1
                    } else if (YDLConstants.ENV_NEW_TEST == cacheAppEnv) {
                        isDevelopment = 2
                    }
                }

                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
                        val property = field.get(ownerClass)
                        if (property is Boolean && property) {
                            var activity: Activity? = mActivity
                            if (mActivity == null && mFragment != null) {
                                activity = mFragment?.activity!!
                            }
                            activity?.let {
                                BuryPointHelper.showEditDialog(
                                    activity,
                                    MD5Util.md5(clickPath),
                                    null
                                )
                            }
                        }
                    } catch (e: Exception) {
                        LogUtil.e("flutter click exception:$e")
                    }

                    YdlBuryPointUtil.sendClick(MD5Util.md5(clickPath))
                }
            }

            ACTION_PUSH_EVENT_TRACKING_PV -> {
                val map = methodCall.arguments as HashMap<*, *>
                val pvPath = map["path"] as String
                if (!TextUtils.isEmpty(pvPath)) {
                    YdlBuryPointUtil.sendPv(pvPath)
                }
            }
            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>
    }
}