package com.ydl.component

//import com.ydl.confide.home.ConfideHomeActivity
//import com.ydl.confide.home.ConfideHomeActivity
//import com.yidianling.consultant.ExpertSearchActivity.Companion.HOT_SEARCH_DOCTOR_NAME
//import com.yidianling.consultant.api.IConsultantService
import android.Manifest
import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.net.Uri
import android.os.IBinder
import android.os.Process
import android.provider.Settings
import android.util.Log
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.tbruyelle.rxpermissions2.RxPermissions
import com.umeng.analytics.MobclickAgent
import com.ydl.audioim.YDLavManager
import com.ydl.component.music.FragmentContainerActivity
import com.ydl.component.mvp.DemoPresenter
import com.ydl.media.audio.PlayService
import com.ydl.ydlcommon.modular.ModularServiceManager
import com.ydl.ydlcommon.mvp.lce.BaseLceActivity
import com.ydl.ydlcommon.utils.ActivityManager.Companion.finishAll
import com.yidianling.common.tools.ToastUtil
import com.yidianling.fm.api.service.IFMService
import com.yidianling.user.ui.collect.CollectSexAndBirthActivity
import com.yidianling.user.widget.SecretDescriptionDialog
import com.yidianling.user.widget.SecretDescriptionDialog.OnSecretDescriptionDialogListener
import com.yidianling.user.widget.SecretDialog
import com.yidianling.user.widget.SecretDialog.OnSecretDialogListener
import kotlinx.android.synthetic.main.activity_main.*
import com.ydl.ydlcommon.utils.ResUtil.getResources
import com.alibaba.fastjson.serializer.AwtCodec.support
import android.support.v4.app.SupportActivity
import android.support.v4.app.SupportActivity.ExtraData
import com.ydl.component.mvp.DemoContract



/**
 * Created by haorui on 2019-09-01 .
 * Des:
 */
@Route(path = "/main/main")
class MainActivity : BaseLceActivity<DemoContract.View, DemoContract.Presenter>(),
    DemoContract.View {
    private var secretDescriptionDialog: SecretDescriptionDialog? = null
    private var serviceConnection: ServiceConnection? = null
    private var secretDialog: SecretDialog? = null
    protected var playService: PlayService? = 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() {

//        YDLavManager.instances.init(this, "3387e9b251f3491e9221a9877e8f7830")

        bindService()
        reLoadData()
        requestPermission()
        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()
        }
        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("1193016")
//            startActivity(Intent(this, ConfideHomeActivity::class.java))
        }
        bt_to_muse.setOnClickListener {

            //            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")
            startActivity(Intent(this, TestAppActivity::class.java))
        }

        bt_to_test.setOnClickListener {
            val dialog = SecretDescriptionDialog(this@MainActivity,
                "感谢您信任并使用壹点灵APP，\\n\n" +
                        "我们深知个人隐私的重要性，为了您更好的使用本APP，希望您着重关注：\\n\\n1. 为向您提供交易相关基本功能，我们会收集、使用必要的信息;\\n\n" +
                        "2. 基于您的明示授权，我们可能会获取您的位置(为您提供附近的咨询师等)、设备号信息(以保障您账号与交易安全)等信息，您有权拒绝或取消授权;\\n\n" +
                        "3. 我们会采业界先进的安全措施保护您的信息安全;\\n\n" +
                        "4. 未经您同意，我们不会从第三方处获取、共享或向其提供您的信息;\\n\n" +
                        "5. 您可以查询、更正、删除您的个人信息。",
                object : SecretDescriptionDialog.OnSecretDescriptionDialogListener {
                    override fun onCancel() {
                        val secretDialog = SecretDialog(
                            this@MainActivity,
                            object : SecretDialog.OnSecretDialogListener {
                                override fun onCancel() {
                                    ToastUtil.toastShort("onCancel")
                                }

                                override fun onSure() {
                                    ToastUtil.toastShort("nextStep")
                                }
                            })
                        secretDialog?.show()
                    }

                    override fun onSure() {
                        ToastUtil.toastShort("nextStep")
                    }
                }
            )
            dialog.show()
        }

    }

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


    @SuppressLint("CheckResult")
    private fun requestPermission() {
        val rxPermissions = RxPermissions(this)
        rxPermissions.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
            .subscribe { permission ->
                if (permission.granted) {
                    ToastUtil.toastShort("Permission Success")
                } else if (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()
        intent.setClass(this, PlayService::class.java!!)
        serviceConnection = PlayServiceConnection()
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
    }

    override fun onResume() {
        super.onResume()
        MobclickAgent.onResume(this)

//        ModularServiceManager.provide(IConsultantService::class.java)
//            .
//            (this)
    }

    override fun onPause() {
        super.onPause()

//        ModularServiceManager.provide(IConsultantService::class.java).hideConsultAssistantDialog()
    }


    override fun onDestroy() {
        if (serviceConnection != null) {
            unbindService(serviceConnection)
        }
        super.onDestroy()
    }

    private inner class PlayServiceConnection : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            playService = (service as PlayService.PlayBinder).service
        }

        override fun onServiceDisconnected(name: ComponentName) {
            Log.e(javaClass.simpleName, "service disconnected")
        }
    }


    private fun showEnsureDialog() {
        secretDialog = SecretDialog(this, object : OnSecretDialogListener {
            override fun onCancel() {
                secretDialog!!.dismiss()
//                finishAll()
//                Process.killProcess(Process.myPid())
//                System.exit(0)
            }

            override fun onSure() {
                secretDialog!!.dismiss()
            }
        })
        secretDialog!!.setCanceledOnTouchOutside(false)
        secretDialog!!.show()
    }

}
