import android.app.AlertDialog
import android.content.Intent
import android.net.Uri
import android.os.Handler
import android.text.TextUtils
import com.lzf.easyfloat.permission.PermissionUtils
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_flutter.flutter.base.BaseFlutterFragment
import com.ydl.ydl_router.manager.YDLRouterManager
import com.ydl.ydlcommon.base.BaseApp
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.common.tools.ToastUtil
import com.yidianling.course.CourseConstants
import com.yidianling.course.bean.ScrollStatusChangeEvent
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 com.yidianling.course.widget.VideoFloatHelper
import de.greenrobot.event.EventBus
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"
        const val REQUESTDATACOMPLETE: String = "requestDataComplete"
        const val REQUESTDATAERROR: String = "requestDataError"
        const val REQUESTSCROLLFOCUS: String = "requestScrollFocus"
        const val RELEASESCROLLFOCUS: String = "releaseScrollFocus"
        const val IOSPOP: String = "iosPop"

        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>()
                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()
                    )
                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)
                        PlayerFloatHelper.hide()
                        PlayerFloatHelper.removeView(mFragment!!.activity!!)
                        AudioPlayer.get().stopPlayer()
                        CourseSendPlugin.sendMsg(false)
                        return
                    }
                    when {
                        jumpUrl!!.contains("user/login") -> {
                            //TODO flutter 登录状态判断需要更改
                            val loginBean =
                                ModularServiceManager.getPlatformUserService()?.getUser()
                            if (loginBean == null || TextUtils.isEmpty(loginBean.userId) || TextUtils.equals(
                                    loginBean.userId,
                                    "0"
                                )
                            ) {
                                mFragment!!.startActivity(CourseIn.loginWayIntent(mFragment!!.activity!!))
                            } else {
                                MyCourseActivity.start(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)
                    }
                    PlayerFloatHelper.hide()
                    PlayerFloatHelper.removeView(mFragment!!.activity!!)
                    AudioPlayer.get().stopPlayer()
                    CourseSendPlugin.sendMsg(false)
                }
            }
            PLAYCOURSEFILE -> {
                var fileInfo: Map<*, *> = methodCall.arguments as Map<*, *>
                LogUtil.e("播放地址：$fileInfo")
                playMedia(fileInfo)
            }
            PAUSECOURSEPLAY -> {
                if (AudioPlayer.get().isPlaying) {
                    AudioPlayer.get().playPause()
                    PlayerFloatHelper.updatePlayState()
                }
            }
            REQUESTDATACOMPLETE -> {
                LogUtil.e("数据加载完成了")
            }
            REQUESTDATAERROR -> {
                LogUtil.e("接口数据请求失败")
            }
            REQUESTSCROLLFOCUS -> {
                EventBus.getDefault().post(ScrollStatusChangeEvent(false))
            }
            RELEASESCROLLFOCUS -> {
                EventBus.getDefault().post(ScrollStatusChangeEvent(true))
            }
            IOSPOP -> {
                PlayerFloatHelper.hide()
                PlayerFloatHelper.removeView(mFragment!!.activity!!)
                AudioPlayer.get().stopPlayer()
                CourseSendPlugin.sendMsg(false)
                mFragment!!.activity.finish()
            }
        }
    }

    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) {
            music.path = url
            val hashMap = HashMap<String, String>()
            hashMap["course_id"] = fileInfo["courseId"].toString()
            AudioPlayer.get().singlePlay(music)
            PlayerFloatHelper.show(
                mFragment!!.activity,
                playTypeEnum = PlayTypeEnum.PLAY_TYPE_COURSE,
                playData = hashMap
            )
            VideoFloatHelper.dismissFloat(mFragment!!.activity)
        }
        if (demoType == 2) {
            VideoFloatHelper.setVideoInfo(
                fileInfo["courseId"].toString(),
                fileInfo["url"].toString(),
                false
            )
            checkPermission()

            if (PlayerFloatHelper.isShow(mFragment!!.activity!!)) {
                PlayerFloatHelper.hide()
                PlayerFloatHelper.removeView(mFragment!!.activity!!)
                AudioPlayer.get().stopPlayer()
            }
        }

        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()
                CourseSendPlugin.sendMsg(false)
            }

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


    /**
     * 检测浮窗权限是否开启，若没有给与申请提示框（非必须，申请依旧是EasyFloat内部内保进行）
     */
    private fun checkPermission() {
        if (PermissionUtils.checkPermission(mFragment!!.activity)) {

            VideoFloatHelper.showVideoFloat(mFragment!!.activity)
        } else {
            AlertDialog.Builder(mFragment!!.activity)
                .setMessage("使用浮窗功能，需要您授权悬浮窗权限。")
                .setPositiveButton("去开启") { _, _ ->
                    VideoFloatHelper.showVideoFloat(mFragment!!.activity)
                }
                .setNegativeButton("取消") { _, _ ->
                    ToastUtil.toastLong(
                        mFragment!!.activity,
                        "App正常工作需要内部存储使用权限，请开启"
                    )
                }
                .show()
        }
    }
}