import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.net.Uri
import android.os.Handler
import android.text.TextUtils
import com.channel.ydl_flutter_base.base.BaseFlutterFragment
import com.lzf.easyfloat.permission.PermissionUtils
import com.ydl.course.event.ScrollStatusChangeEvent
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.config.YDLConstants
import com.ydl.ydlcommon.data.PlatformDataManager
import com.ydl.ydlcommon.modular.ModularServiceManager
import com.ydl.ydlcommon.modular.ModularServiceManager.provide
import com.yidianling.common.tools.LogUtil
import com.yidianling.common.tools.RxDeviceTool
import com.yidianling.common.tools.ToastUtil
import com.yidianling.consultant.api.IConsultantService
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 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 JUMPROUTERURL: String = "jumpRouterUrl"
        const val GETASSIANSTGUIDEDATA: String = "getAssianstGuideData"
        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 appEnv = BaseApp.instance.getGlobalConfig().appEnv
                var isDevelopment = 0

                if (YDLConstants.ENV_TEST == appEnv) {
                    isDevelopment = 1
                } else if (YDLConstants.ENV_NEW_TEST == appEnv) {
                    isDevelopment = 2
                }
                val loginBean = ModularServiceManager.getPlatformUserService()?.getUser()
                val mMap = mutableMapOf<String, Any>()
                var uid = loginBean?.userId ?: ""
                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()
                    )
                result.success(mMap)
            }
            GETASSIANSTGUIDEDATA -> {
                val mMap = mutableMapOf<String, Any>()
                val listData =
                    provide(IConsultantService::class.java)
                        .getGuideImage(7)
                if (listData?.size ?: 0 > 0) {
                    mMap["pic"] = listData!![0].pic
                    mMap["linkUrl"] = listData!![0].linkUrl
                } else {
                    mMap["pic"] = ""
                    mMap["linkUrl"] = ""
                }
                result.success(mMap)
            }
            JUMPROUTERURL -> {
                val jumpUrl: String? = methodCall.arguments.toString()
                provide(IConsultantService::class.java).jumpConsultAssistant(mFragment!!.activity as Activity, 7)

            }
            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!!.requireActivity())
                        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"
                                )
                            ) {
                                CourseIn.loginByOneKeyLogin(mFragment!!.requireActivity(),true)
                            } else {
                                MyCourseActivity.start(mFragment!!.activity)
                            }

                        }
                        jumpUrl.contains("course/myCourse") -> MyCourseActivity.start(mFragment!!.activity)
                        jumpUrl.contains("course/specialList") -> //跳转专题列表页
                            mFragment!!.requireActivity().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!!.requireActivity())
                    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!!.requireActivity())
                AudioPlayer.get().stopPlayer()
                CourseSendPlugin.sendMsg(false)
                mFragment!!.activity?.finish()
            }
        }
    }

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


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

            if (PlayerFloatHelper.isShow(mFragment!!.requireActivity())) {
                PlayerFloatHelper.hide()
                PlayerFloatHelper.removeView(mFragment!!.requireActivity())
                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!!.requireActivity())) {

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