package com.channel.ydl_flutter_base.plugin

import android.content.SharedPreferences
import android.text.TextUtils
import com.channel.ydl_flutter_base.BuildConfig
import com.channel.ydl_flutter_base.base.BaseFlutterFragment
import com.ydl.ydlcommon.base.BaseApp
import com.ydl.ydlcommon.data.PlatformDataManager
import com.ydl.ydlcommon.modular.ModularServiceManager
import com.ydl.ydlcommon.utils.SharedPreferencesEditor
import com.yidianling.common.tools.RxDeviceTool
import io.flutter.app.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
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"

        //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 ?: ""
                mMap["isDevelopment"] = false
                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)
            }
        }
    }
}