package com.channel.ydl_flutter_base.plugin

import android.text.TextUtils
import com.channel.ydl_flutter_base.base.BaseFlutterFragment
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.modular.ModularServiceManager
import com.ydl.ydlcommon.utils.SharedPreferencesEditor
import com.ydl.ydlcommon.utils.YDLCacheUtils
import com.ydl.ydlcommon.utils.YdlBuryPointUtil
import com.yidianling.common.tools.RxDeviceTool
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 {
        const val CHANNEL: String = "lib/common/channel"
        const val GETPUBLICPARAMAS: String = "getPublicParamas"
        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

        //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: Boolean = false
                if (!TextUtils.isEmpty(cacheAppEnv)) {
                    isDevelopment = YDLConstants.ENV_TEST == cacheAppEnv
                } else {
                    isDevelopment = YDLConstants.ENV_TEST == appEnv || YDLConstants.ENV_AUTO_TEST == 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
                        val property = field.get(ownerClass)
                        if (property is Boolean && property) {
                            BuryPointHelper.showEditDialog(mActivity, MD5Util.md5(clickPath), null)
                        }
                    } catch (e: Exception) {

                    }

                    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>()
                //TODO haorui 添加主题色定义
                //mMap["platform_main_theme"] = "#ff0000"
                result.success(mMap)
            }
        }
    }
}