package com.ydl.component

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.PixelFormat
import android.media.MediaPlayer
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.text.TextUtils
import android.util.DisplayMetrics
import android.view.*
import android.widget.ImageView
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.tbruyelle.rxpermissions2.RxPermissions
import com.tencent.qcloud.tuicore.calling.trtccalling.model.TRTCCalling
import com.tencent.qcloud.tuicore.calling.videocall.Constant
import com.tencent.qcloud.tuicore.calling.videocall.YDLInvitionActivity
import com.umeng.analytics.MobclickAgent
import com.ydl.audioim.YDLavManager
import com.ydl.component.music.FragmentContainerActivity
import com.ydl.component.mvp.DemoContract
import com.ydl.component.mvp.DemoPresenter
import com.ydl.component.route.PlatformTempCommonRouteImpl
import com.ydl.component.rtc.MDTLoginActivity
import com.ydl.confide.home.ConfideHomeActivity
import com.ydl.ydlcommon.data.http.ThrowableConsumer
import com.ydl.ydlcommon.modular.ModularServiceManager
import com.ydl.ydlcommon.mvp.lce.BaseLceActivity
import com.ydl.ydlcommon.router.YdlCommonRouterManager
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.yidianling.common.tools.LogUtil
import com.yidianling.common.tools.ToastUtil
import com.yidianling.consultant.api.IConsultantService
import com.yidianling.fm.api.service.IFMService
import com.yidianling.home.http.MuseHttp
import com.yidianling.muse.activity.PlayMeditationActivity
import com.yidianling.muse.bean.MeditationPlayModuleBean
import com.yidianling.muse.constants.MuseBIConstants
import com.yidianling.muse.event.MeditationFloatEvent
import com.yidianling.muse.helper.FloatViewTouchListener
import com.yidianling.muse.helper.MediaPlayerManager
import com.yidianling.muse.utils.MediaPlayerTimeUtil
import com.yidianling.tests.home.NewTestHomeActivity
import com.yidianling.user.api.service.IUserService
import com.yidianling.user.ui.collect.CollectSexAndBirthActivity
import com.yidianling.user.ui.login.OneKeyLoginHelp
import de.greenrobot.event.EventBus
import io.feeeei.circleseekbar.CircleSeekBar
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.math.roundToInt


/**
 * Created by haorui on 2019-09-01 .
 * Des:
 */
@Route(path = "/main/main")
class MainActivity : BaseLceActivity<DemoContract.View, DemoContract.Presenter>(),
    DemoContract.View {

    private var mFloatDisposable:Disposable?=null

    override fun getContentViewId(): Int {
        return R.id.lce_content_view
    }

    override fun getStateViewId(): Int {
        return R.id.lce_state_view
    }

    override fun setData(data: String) {
        tv_content.text = data
    }

    override fun createPresenter(): DemoContract.Presenter {
        return DemoPresenter()
    }

    override fun layoutResId(): Int {
        return R.layout.activity_main
    }

    override fun initDataAndEvent() {

        EventBus.getDefault().register(this)
        //线上
//        YDLavManager.instances.init(this, "3387e9b251f3491e9221a9877e8f7830")
        //测试
        YDLavManager.instances.init(this, "13b1536698f64905a1e7e5bb978ba821")

        YdlCommonRouterManager.initYdlCommonRoute(PlatformTempCommonRouteImpl())
        // 初始化一键登录sdk
        OneKeyLoginHelp.sdkInit(
            this,
            OneKeyLoginHelp.YDL_USER_APP,
            2
        )
        bindService()

        initMeditationObserver()

        reLoadData()
        requestPermission()
        bt_mdt.setOnClickListener {
            val intent = Intent(this, MDTLoginActivity::class.java)
            startActivity(intent)
        }

        tv_user.setOnClickListener {
            reLoadData()
        }

        tv_home?.setOnClickListener {
            mPresenter.loadHome()
        }

        bt_to_other.setOnClickListener {
//            ARouter.getInstance().build("/user/login")
//                .withBoolean("bind_phone", false)
//                .withBoolean("isFromGuide", true)
//                .navigation()
            OneKeyLoginHelp.startLogin(this, false)
        }
        bt_to_consultant.setOnClickListener {
            //            ARouter.getInstance()
//                .build("/consult/hot_search")
//                .withString(
//                    HOT_SEARCH_DOCTOR_NAME,
//                    this.resources?.getString(R.string.platform_search_hint)
//                )
//                .navigation()
            FragmentContainerActivity.start(this, "ExpertSearchFragment")
        }
        bt_to_music.setOnClickListener {
            FragmentContainerActivity.start(this)
        }
        bt_to_im.setOnClickListener {
            FragmentContainerActivity.start(this, "NewMultiMessageFragment")
        }
        bt_to_dynamic.setOnClickListener {
            FragmentContainerActivity.start(this, "TrendsHomeFragment")
        }
        bt_to_tests.setOnClickListener {
            startActivity(Intent(this, NewTestHomeActivity::class.java))
            //                                SecretActivity.Companion.startProtocol(this, it.data.getContent());
//             secretDescriptionDialog = SecretDescriptionDialog(
//                this@MainActivity,
//               "122342453653456345674356",
//                object : OnSecretDescriptionDialogListener {
//                    override fun onCancel() {
//                        secretDescriptionDialog!!.dismiss()
//                        showEnsureDialog()
//                    }
//
//                    override fun onSure() {
//                        secretDescriptionDialog!!.dismiss()
//                    }
//                })
//            secretDescriptionDialog!!.setCanceledOnTouchOutside(false)
//            secretDescriptionDialog!!.show()

        }
        bt_to_collect_info.setOnClickListener {
            startActivity(Intent(this, CollectSexAndBirthActivity::class.java))
        }
        bt_to_confide.setOnClickListener {
            YDLavManager.instances.login(
                ModularServiceManager.provide(IUserService::class.java).getUserInfo()?.uid
            )
            startActivity(Intent(this, ConfideHomeActivity::class.java))
        }

        ModularServiceManager.provide(IConsultantService::class.java).requestGuideData()
        bt_to_muse.setOnClickListener {

            ARouter.getInstance().build("/muse/play")
                .navigation()

            val list =
                ModularServiceManager.provide(IConsultantService::class.java).getGuideImage(1)
            list?.forEach {
                LogUtil.e(it.toString())
            }
            //            YDLRouterManager.router(IYDLRouterConstant.ROUTER_MUSE_CENTER,
//                YDLRouterParams().putExtra
//            ("url", "http://video.yidianling.com/2019/05/30/746851e2f335baf5f44499f4fb49d3a9.mp3"))

//            YDLRouterManager.router(
//                IYDLRouterConstant.ROUTER_MUSE,
//                YDLRouterParams().putExtra(
//                    IYDLRouterConstant.MUSIC_URL,
//                    "http://video.yidianling.com/2019/05/30/e6d4a71e8c895f2156a2ff37d93ca3a9.mp3"
//                )
//                    .putExtra(
//                        IYDLRouterConstant.DATA_JSON, "{\n" +
//                                "        \"muses\": [{\n" +
//                                "        \"id\": 6,\n" +
//                                "        \"name\": \"冥想基础介绍-1-什么是冥想?\",\n" +
//                                "        \"audioUrl\":\n" +
//                                "        \"http://video.yidianling.com/2019/05/30/e6d4a71e8c895f2156a2ff37d93ca3a9.mp3\",\n" +
//                                "        \"backgroundUrl\":\n" +
//                                "        \"https://img.yidianling.com/file/2019/06/10/i4qdax82ok2aizq3.png\",\n" +
//                                "        \"effectCode\": 1,\n" +
//                                "        \"category\": 2,\n" +
//                                "        \"playCount\": 929,\n" +
//                                "        \"sort\": 255,\n" +
//                                "        \"isDelete\": 1,\n" +
//                                "        \"createTime\": \"May 30, 2019 4:45:17 PM\",\n" +
//                                "        \"updateTime\": \"Jun 10, 2019 7:14:23 PM\"\n" +
//                                "    }]\n" +
//                                "    }"
//                    )
//            )
        }

        bt_to_fm.setOnClickListener {
            startActivity(ModularServiceManager.provide(IFMService::class.java).fmListIntent(this))
//            YDLRouterManager.router(IYDLRouterConstant.ROUTER_FM_LIST)
        }

        bt_to_course.setOnClickListener {
            ARouter.getInstance().build("/course/home")
                .navigation()
        }
        bt_to_home.setOnClickListener {
            FragmentContainerActivity.start(this, "YdlHomeFragment")
        }
        bt_to_mine.setOnClickListener {
            FragmentContainerActivity.start(this, "MineFragment")
        }

        bt_to_privacy.setOnClickListener {
            startActivity(Intent(this@MainActivity, TestAppActivity::class.java))
        }
    }


    override fun reLoadData() {
        mPresenter.loadHome()
    }


    @SuppressLint("CheckResult")
    private fun requestPermission() {
        val rxPermissions = RxPermissions(this)
        rxPermissions.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
            .subscribe { permission ->
                when {
                    permission.granted -> {
                        ToastUtil.toastShort("Permission Success")
                    }
                    permission.shouldShowRequestPermissionRationale -> {
                        requestPermission()
                    }
                    else -> {
                        ToastUtil.toastLong(
                            this,
                            getString(R.string.platform_need_storage_permission_hint)
                        )
                        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                        val uri = Uri.fromParts("package", packageName, null)
                        intent.data = uri
                        startActivity(intent)
                        finish()
                    }
                }
            }

    }

    private fun bindService() {
        val intent = Intent()
    }

    private fun initMeditationObserver(){
        mFloatDisposable = Observable.interval(500,TimeUnit.MILLISECONDS)
            .filter { true }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                if (!windowIsShow && mToShowWindow){
                    showWindow()
                }else if (windowIsShow && !mToShowWindow){
                    hideFloatWindow()
                }
                mCurrentMeditation?.let { it1 -> updateFloatView(it1) }
            }
    }

    override fun onResume() {
        super.onResume()
        MobclickAgent.onResume(this)
        val trtcCalling = TRTCCalling.sharedInstance(this)
        if (!TextUtils.isEmpty(trtcCalling.mRoomId) && !TextUtils.isEmpty(trtcCalling.mUserId)) {
            val intent = Intent(mContext, YDLInvitionActivity::class.java)
            intent.putExtra(Constant.ROOM_ID, trtcCalling.mRoomId)
            intent.putExtra(Constant.USER_ID, trtcCalling.mUserId)
            intent.putExtra(Constant.INVITE_ID, trtcCalling.mInviteId)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            mContext.startActivity(intent)
        }
    }



    fun onEvent(event: MeditationFloatEvent) {

    }

    @SuppressLint("MissingSuperCall")
    override fun onDestroy() {
        MediaPlayerManager.getInstance(this)?.stop()

        hideFloatWindow()

        mDisposable?.dispose()
        mFloatDisposable?.dispose()

        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }

    private lateinit var mWindowManager: WindowManager
    private var floatRootView: View? = null

    private var ivClose: ImageView? = null
    private var ivCover: ImageView? = null
    private var tvTitle: TextView? = null
    private var ivProgress: CircleSeekBar? = null
    private var ivPlayOrPause: ImageView? = null

    private var mMediaPlayer: MediaPlayer? = null

    private var mTimer = Timer()

    private var mCurrentMeditation: MeditationPlayModuleBean.MeditationDetail? = null

    private var mMeditations = mutableListOf<MeditationPlayModuleBean.MeditationDetail>()

    private var windowIsShow = false

    private var mToShowWindow = false

    private var mUpdate = false

    private var mObservable: Observable<Long>? = null
    private var mObserver: Observer<Long>? = null

    private var currentMediaId:Long? = null

    private var mDisposable:Disposable?=null

    private var currentMeditationIndex = 0

    private fun showWindow() {
        mWindowManager = getSystemService(WINDOW_SERVICE) as WindowManager
        val outMetrics = DisplayMetrics()
        mWindowManager.defaultDisplay.getMetrics(outMetrics)
        var layoutParams = WindowManager.LayoutParams().apply {
            type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            } else {
                WindowManager.LayoutParams.TYPE_PHONE
            }
            flags =
                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
            format = PixelFormat.RGBA_8888
            width = outMetrics.widthPixels - dp2px(32F)
            height = ViewGroup.LayoutParams.WRAP_CONTENT
            gravity = Gravity.LEFT or Gravity.TOP

            x = outMetrics.widthPixels /2 - width / 2
            y = outMetrics.heightPixels - dp2px(140F)
        }
        floatRootView =
            LayoutInflater.from(this).inflate(com.yidianling.muse.R.layout.layout_meditation_play_float_view, null)
        ivClose = floatRootView?.findViewById(com.yidianling.muse.R.id.iv_close)
        ivCover = floatRootView?.findViewById(com.yidianling.muse.R.id.iv_cover)
        tvTitle = floatRootView?.findViewById(com.yidianling.muse.R.id.tv_title)
        ivProgress = floatRootView?.findViewById(com.yidianling.muse.R.id.progress_bar)
        ivPlayOrPause = floatRootView?.findViewById(com.yidianling.muse.R.id.iv_play_status)
        floatRootView?.setOnTouchListener(FloatViewTouchListener(layoutParams, mWindowManager))
        mWindowManager.addView(floatRootView, layoutParams)
        windowIsShow = true
    }

    fun onEventMainThread(event: Any) {
        if (event is com.ydl.ydlcommon.event.MeditationFloatStopEvent){
            mToShowWindow = event.show
            if (event.show!=null && !event.show) {
                if (event.stop == true){
                    try {
                        mMediaPlayer?.stop()
                    }catch (e:Exception){

                    }
                }
            }
        }

        if (event is MeditationFloatEvent){
            mToShowWindow = event.show

            if (event.time!=null){
                if (event.time!! >0){
                    initRxTimeOff(event.time!!)
                }else{
                    mDisposable?.dispose()
                }
            }else{
                if (event.show!=null && !event.show) {
                    if (event.stop == true){
                        try {
                            mMediaPlayer?.stop()
                        }catch (e:Exception){

                        }
                    }
                }
            }
            if (event.show!=null && event.show && event.meditation != null && event.meditations!=null) {
                mCurrentMeditation = event.meditation
                mMeditations.addAll(event.meditations!!)
            }
        }


    }

    private fun updateFloatView(meditation: MeditationPlayModuleBean.MeditationDetail) {

        currentMediaId = meditation.mediaId
        MediaPlayerManager.getInstance(this)?.setMediaId(currentMediaId)

        mMediaPlayer = MediaPlayerManager.getInstance(this)?.getMediaPlayer()
        tvTitle?.setOnClickListener {
            //悬浮窗暂停点击事件
            ActionCountUtils.count(MuseBIConstants.YDL_MUSE_MEDITATION_WINDOW_CLICK,"")

            val intent = Intent(this, PlayMeditationActivity::class.java)
            intent.putExtra("MEDIA_ID", meditation.mediaId)
            intent.putExtra("MEDITATION_ID", meditation.meditationId)
            intent.putExtra("MEDITATION_TYPE", meditation.meditationType)
            intent.putExtra("MEDIA_COVER_URL", meditation.coverImageUrl)
            intent.putExtra("MEDIA_URL", meditation.mediaUrl)

            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            startActivity(intent)
        }
        ivCover?.setOnClickListener {
            //悬浮窗暂停点击事件
            ActionCountUtils.count(MuseBIConstants.YDL_MUSE_MEDITATION_WINDOW_CLICK,"")

            val intent = Intent(this, PlayMeditationActivity::class.java)
            intent.putExtra("MEDIA_ID", meditation.mediaId)
            intent.putExtra("MEDITATION_ID", meditation.meditationId)
            intent.putExtra("MEDITATION_TYPE", meditation.meditationType)
            intent.putExtra("MEDIA_COVER_URL", meditation.coverImageUrl)
            intent.putExtra("MEDIA_URL", meditation.mediaUrl)

            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            startActivity(intent)
        }

        if (mMediaPlayer?.isPlaying == true) {
            ivPlayOrPause?.setImageResource(com.yidianling.muse.R.drawable.icon_meditation_float_play)
        } else {
            ivPlayOrPause?.setImageResource(com.yidianling.muse.R.drawable.icon_meditation_float_pause)
        }

        ivProgress?.maxProcess = mMediaPlayer?.duration ?: 0
        ivProgress?.curProcess = mMediaPlayer?.currentPosition ?: 0

        Glide.with(floatRootView!!)
            .load(meditation.coverImageUrl)
            .into(ivCover!!)

        tvTitle?.text = meditation.title

        ivPlayOrPause?.setOnClickListener {
            if (mMediaPlayer?.isPlaying == true) {
                //悬浮窗暂停点击事件
                ActionCountUtils.count(MuseBIConstants.YDL_MUSE_MEDITATION_WINDOW_PAUSE_CLICK,"")

                MediaPlayerManager.getInstance(this)?.pause()
                if (meditation.meditationId != null && meditation.mediaId != null) {
                    MuseHttp.getInstance().postMeditationPlayRecord(
                        meditationId = meditation.meditationId!!.toInt(),
                        isQuit = 1, mediaId = meditation.mediaId!!,
                        playTime = (ivProgress?.curProcess?.div(1000.00))?.roundToInt() ?: 0,
                        isComplete = 0
                    )
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe({

                        }, {
                            object : ThrowableConsumer() {
                                override fun accept(msg: String) {

                                }
                            }
                        })
                }
            } else {
                //悬浮窗播放点击事件
                ActionCountUtils.count(MuseBIConstants.YDL_MUSE_MEDITATION_WINDOW_PLAY_CLICK,"")
                MediaPlayerManager.getInstance(this)?.play()
            }
            if (mMediaPlayer?.isPlaying == true) {
                ivPlayOrPause?.setImageResource(com.yidianling.muse.R.drawable.icon_meditation_float_play)
            } else {
                ivPlayOrPause?.setImageResource(com.yidianling.muse.R.drawable.icon_meditation_float_pause)
            }
        }

        mTimer.schedule(object : TimerTask() {
            override fun run() {
                ivProgress?.curProcess = mMediaPlayer?.currentPosition ?: 0
            }
        }, 0, 50)

        mMediaPlayer?.setOnCompletionListener {

            val duration = meditation?.duration?.toInt()?:0
            val currentDuration = (mMediaPlayer?.currentPosition?:0)/1000
            if(meditation.mediaId!=null && meditation.meditationId!=null){
                val playTime = (ivProgress?.curProcess?.div(1000.00))?.roundToInt() ?: 0
                if(duration == currentDuration){
                    MediaPlayerTimeUtil.uploadPlayRecord(
                        meditationId = meditation.meditationId.toInt(),
                        mediaId = meditation.mediaId,
                        isQuit = 0,
                        playTime = playTime,
                        isComplete = 1
                    )
                }
            }
            switchSound()
            if (mMediaPlayer?.isPlaying == true) {
                ivPlayOrPause?.setImageResource(com.yidianling.muse.R.drawable.icon_meditation_float_play)
            } else {
                ivPlayOrPause?.setImageResource(com.yidianling.muse.R.drawable.icon_meditation_float_pause)
            }
        }

        ivClose?.setOnClickListener {
            //悬浮窗关闭点击事件
            ActionCountUtils.count(MuseBIConstants.YDL_MUSE_MEDITATION_WINDOW_CLOSE_CLICK,"")

            if(meditation.mediaId!=null && meditation.meditationId!=null){
                val playTime = (ivProgress?.curProcess?.div(1000.00))?.roundToInt() ?: 0
                MediaPlayerTimeUtil.uploadPlayRecord(
                    meditationId = meditation.meditationId.toInt(),
                    mediaId = meditation.mediaId,
                    isQuit = 0,
                    playTime = playTime,
                    isComplete = 0
                )
            }

            MediaPlayerManager.getInstance(this)?.stop()
            hideFloatWindow()
        }

        mUpdate = false

    }

    private fun hideFloatWindow() {
        if (floatRootView != null && floatRootView?.windowToken != null) {
            if (mWindowManager != null) {
                mWindowManager.removeViewImmediate(floatRootView)
            }
        }
        windowIsShow = false
    }

    private fun switchSound() {
        mMeditations?.forEachIndexed { index, meditationDetail ->
            if (meditationDetail.mediaId == mCurrentMeditation?.mediaId) {
                currentMeditationIndex = index
            }
        }
        if (currentMeditationIndex < mMeditations.size - 1) {
            mCurrentMeditation = mMeditations[currentMeditationIndex + 1]
        } else {
            mCurrentMeditation = mMeditations[0]
        }
        mUpdate = true
        updateFloatView(mCurrentMeditation!!)

        initMediaPlayer(mCurrentMeditation!!.mediaUrl)

    }

    private fun initMediaPlayer(path: String) {
        MediaPlayerManager.getInstance(this)?.setAudioPath(path)
        MediaPlayerManager.getInstance(this)
            ?.setOnPreparedListener(object : MediaPlayerManager.OnMediaPlayerManagerListener {
                override fun onPrepared(mediaPlayer: MediaPlayer) {
                    MediaPlayerManager.getInstance(this@MainActivity)?.play()
                }
            })
    }


    private fun dp2px(dp: Float): Int {
        val scale = resources.displayMetrics.density
        return (dp * scale + 0.5f).toInt()
    }

    private fun initRxTimeOff(time: Long) {
        mObservable = Observable.interval(0, 1, TimeUnit.SECONDS)
            .take(time / 1000 + 1)
            .map { t -> time - t * 1000 }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())

        mObserver = object : Observer<Long> {
            override fun onSubscribe(d: Disposable) {
                mDisposable = d
            }

            override fun onNext(t: Long) {

            }

            override fun onError(e: Throwable) {

            }

            override fun onComplete() {
                if (mMediaPlayer?.isPlaying == true) {
                    mMediaPlayer?.stop()
                    ivPlayOrPause?.setImageResource(com.yidianling.muse.R.drawable.icon_meditation_float_pause)
                }
                hideFloatWindow()
            }
        }

        if (mObserver != null && mObserver is Observer<Long>) {
            mObservable?.subscribe(mObserver as Observer<Long>)
        }

        if (mDisposable?.isDisposed == true && mObserver != null && mObserver is Observer<Long>) {
            mObservable?.subscribe(mObserver as Observer<Long>)
        }

    }

}