import android.content.Intent
import android.net.Uri
import android.os.Handler
import android.text.TextUtils
import com.ydl.media.audio.AudioPlayer
import com.ydl.media.audio.model.Music
import com.ydl.media.view.PlayTypeEnum
import com.ydl.media.view.PlayerFloatHelper
import com.ydl.media.view.PlayerFloatView
import com.ydl.webview.H5Params
import com.ydl.webview.NewH5Activity
import com.ydl.ydl_router.manager.YDLRouterManager
import com.ydl.ydlcommon.base.BaseApp
import com.ydl.ydlcommon.base.flutter.base.BaseFlutterFragment
import com.ydl.ydlcommon.data.PlatformDataManager
import com.ydl.ydlcommon.modular.ModularServiceManager
import com.yidianling.common.tools.LogUtil
import com.yidianling.common.tools.RxDeviceTool
import com.yidianling.course.BuildConfig
import com.yidianling.course.CourseConstants
import com.yidianling.course.courseNew.mine.MyCourseActivity
import com.yidianling.course.course_special_list.activity.CourseSpecialListActivity
import com.yidianling.course.flutterPlugin.CourseSendPlugin
import com.yidianling.course.router.CourseIn
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.view.FlutterView
import org.json.JSONObject

/**
 * @author jiucheng
 * @描述:
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2019/10/18
 */
class CoursePlugin : MethodChannel.MethodCallHandler {
    private var mFragment: BaseFlutterFragment? = null

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

    companion object {
        const val CHANNEL: String = "base/channel/native/get"
        const val GETPUBLICPARAMAS: String = "getPublicParamas"
        const val JUMPURL: String = "jumpUrl"
        const val PLAYCOURSEFILE: String = "playCourseFile"
        const val PAUSECOURSEPLAY: String = "pauseCoursePlay"

        fun register(fragment: BaseFlutterFragment, flutterView: FlutterView) {
            MethodChannel(flutterView, CHANNEL).setMethodCallHandler(CoursePlugin(fragment))
        }
    }

    override fun onMethodCall(methodCall: MethodCall, result: MethodChannel.Result) {
        when (methodCall.method) {
            GETPUBLICPARAMAS -> {
                val loginBean = ModularServiceManager.getPlatformUserService()?.getUser()
                val mMap = mutableMapOf<String, Any>()
                mMap["isDevelopment"] = BuildConfig.DEBUG
                mMap["uid"] = loginBean?.userId ?: 0
                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()
                    )
                result.success(mMap)
            }
            JUMPURL -> {
                var jumpUrl: String? = methodCall.arguments.toString()
                if (!TextUtils.isEmpty(jumpUrl)) {
                    if (jumpUrl!!.startsWith("http")) {
                        val h5Params = H5Params(jumpUrl, "")
                        NewH5Activity.start(mFragment!!.activity, h5Params)
                        return
                    }
                    when {
                        jumpUrl!!.contains("user/login") -> mFragment!!.startActivity(
                            CourseIn.loginWayIntent(
                                mFragment!!.activity!!
                            )
                        )
                        jumpUrl.contains("course/myCourse") -> MyCourseActivity.start(mFragment!!.activity)
                        jumpUrl.contains("course/specialList") -> //跳转专题列表页
                            mFragment!!.activity!!.startActivity(
                                Intent(
                                    mFragment!!.activity,
                                    CourseSpecialListActivity::class.java
                                )
                            )
                        jumpUrl.contains("course/detail") -> {
                            var uri = Uri.parse(jumpUrl)
                            var resultParams = uri.getQueryParameter("params")
                            val jsonObject = JSONObject(resultParams)
                            val h5Params = H5Params(CourseConstants.COURSE_DETAIL_H5 + jsonObject.getString("id"), "课程详情")
                            NewH5Activity.start(mFragment!!.activity, h5Params)
                        }
                        else -> YDLRouterManager.router(jumpUrl)
                    }
                }
            }
            PLAYCOURSEFILE -> {
                var fileInfo: Map<*, *> = methodCall.arguments as Map<*, *>
                LogUtil.e("播放地址：$fileInfo")
                playMedia(fileInfo)
            }
            PAUSECOURSEPLAY -> {
                if (AudioPlayer.get().isPlaying) {
                    AudioPlayer.get().playPause()
                    PlayerFloatHelper.updatePlayState()
                }
            }
        }
    }

    private fun playMedia(fileInfo: Map<*, *>) {
        if (PlayerFloatHelper.isShow(mFragment!!.activity!!)) {
            PlayerFloatHelper.hide()
            PlayerFloatHelper.removeView(mFragment!!.activity!!)
            AudioPlayer.get().stopPlayer()
        } else {
            PlayerFloatHelper.removeView(mFragment!!.activity!!)
        }


        val music = Music()
        music.title = fileInfo["title"].toString()
        music.artist = fileInfo["name"].toString()
        music.coverPath = fileInfo["cover"].toString()
        PlayerFloatHelper.isCanClick = false

        var demoType = fileInfo["demoType"] as Int
        var url = fileInfo["url"].toString()

        if (demoType == 1) {
            PlayerFloatHelper.playingType = PlayTypeEnum.PLAY_TYPE_COURSE
            music.path = url

            PlayerFloatHelper.show(mFragment!!.activity)
            AudioPlayer.get().singlePlay(music)
        }
        if (demoType == 2) {
            //todo   视屏播放
//            YDLMusicHelper.playType = 1
//            YDLMusicHelper.courseVideoUlr = url
//
//            PlayerFloatHelper.show(mFragment!!.activity)
        }

        Handler().postDelayed({ CourseSendPlugin.sendMsg(true) }, 300)

        PlayerFloatHelper.addClickListener(object : PlayerFloatView.FloatViewPlayListener {
            override fun onStartClick() {
                if (!PlayerFloatHelper.isCanClick && PlayerFloatHelper.playingType == PlayTypeEnum.PLAY_TYPE_COURSE) {
                    CourseSendPlugin.sendMsg(true)
                }
            }

            override fun onPlayFinish() {
                PlayerFloatHelper.hide()
                AudioPlayer.get().stopPlayer()
            }

            override fun onPauseClick() {
                if (!PlayerFloatHelper.isCanClick && PlayerFloatHelper.playingType == PlayTypeEnum.PLAY_TYPE_COURSE) {
                    CourseSendPlugin.sendMsg(false)
                }
            }
        })
    }
}