package com.sinata.bc_chat

import android.Manifest
import android.app.Activity
import android.app.Dialog
import android.content.ActivityNotFoundException
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.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.bc_chat.bc_base.ImService.ImRongService
import com.bc_chat.bc_base.config.RouteConfig
import com.bc_chat.bc_base.contract.MainContract
import com.bc_chat.bc_base.entity.ApkVersion
import com.bc_chat.bc_base.entity.FriendApplyRecordBean
import com.bc_chat.bc_base.entity.NavEntity
import com.bc_chat.bc_base.entity.User
import com.bc_chat.bc_base.entity.group.Group
import com.bc_chat.bc_base.entity.wallet.NoticeEntity
import com.bc_chat.bc_base.presenter.MainPresenter
import com.bc_chat.bc_base.utils.*
import com.bc_chat.contacts.ContactListFragment.Companion.tips_message_add
import com.bc_chat.contacts.ContactListFragment.Companion.tips_message_clear
import com.sinata.bc_chat.databinding.ActivityMainBinding
import com.sinata.bc_chat.fragment.Nav1Fragment
import com.sinata.bc_chat.fragment.Nav2Fragment
import com.sinata.bc_chat.fragment.NoticeDialogFragment
import com.sinata.bc_chat.utils.GsonUtil
import com.sinata.bc_chat.utils.MainTab
import com.sinata.bc_chat.utils.NavDataUtil
import com.sinata.bc_chat.utils.ReminderId
import com.sinata.download.DownloadLibrary
import com.sinata.download.entity.Version
import com.sinata.download.utils.Logger
import com.sinata.download.utils.Utils
import com.sinata.download.utils.VersionUpdateUtils
import com.zhaohaoting.framework.abs.AbsV4Fragment
import com.zhaohaoting.framework.abs.BaseNoActionBarActivity
import com.zhaohaoting.framework.abs.contract.BaseContract
import com.zhaohaoting.framework.ui.dialog.CustomDialog
import com.zhaohaoting.framework.utils.NotifyHelper
import com.zhaohaoting.framework.utils.Preferences
import com.zhaohaoting.framework.utils.ToastUtils
import com.zhaohaoting.framework.utils.observer.Observer
import com.zhaohaoting.framework.utils.observer.ObserverManager
import io.rong.imkit.RongIM
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation
import org.jetbrains.anko.bundleOf
import org.jetbrains.anko.find
import org.json.JSONException
import org.json.JSONObject

/**
 * 消息提醒应建立消息管理类统一处理
 * 此处先简单处理
 */
@Route(path = RouteConfig.MAIN_ACTIVITY)
class MainActivity : BaseNoActionBarActivity<MainPresenter>(), MainContract.View,
        VersionUpdateUtils.TipsDialogProvider {


    private val binding by lazy {
        rootDataBinding as ActivityMainBinding
    }
    private var bundle: Bundle = bundleOf("select " to 0, "new_msg" to false) //select选中tab  new_msg是否有新消息
    private var inflater: LayoutInflater? = null
    private var apkLocalPath = ""

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent)
        parseIntent()
    }

    private fun parseIntent() {
        val action = intent.getStringExtra("action")
        if (Const.Action.DISSOLUTION_GROUP.equals(action)) {
            setSelectPage(MainTab.CHAT.reminderId)
        }
//        else if (Const.Action.CIRCLE_LIKE.equals(action)) {
//            setSelectPage(MainTab.CIRCLE.reminderId)
//            val circleFragment = getChildFragment<AbsV4Fragment<BaseContract.BasePresenter>>(MainTab.CIRCLE.reminderId)
//            bundle.putInt("select", 1)
//            bundle.putBoolean("new_msg", true)
//            circleFragment?.arguments = bundle
//        }
    }

    private fun pushResult() {
        ObserverManager.getInstance().notifyObserver(Const.Action.NOTICE_START_MAIN, "1")
        if ("rong".equals(intent.data?.scheme) && intent.data?.getQueryParameter("isFromPush") != null) {
            if (intent.data?.getQueryParameter("isFromPush").equals("true")) {
                val options = intent.getStringExtra("options") // 获取 intent 里携带的附加数据
                try {
                    val jsonObject = JSONObject(options)
                    if (jsonObject.has("appData")) {   // appData 对应的是客户端 sendMessage() 时的参数 pushData
                        val appDataString = jsonObject.getString("appData")
                        val appData = JSONObject(appDataString)
                        val extra = appData.getJSONObject("extra")
                        val type = extra.optString("type")
                        when (type) {
                            Const.PushMethod.DISS_GROUP -> {//解散群
                                val groupId = extra.optString("groupId")
                                RongIM.getInstance().clearMessages(
                                        Conversation.ConversationType.GROUP,
                                        groupId,
                                        object : RongIMClient.ResultCallback<Boolean>() {
                                            override fun onSuccess(aBoolean: Boolean?) {
                                                RongIM.getInstance()
                                                        .removeConversation(Conversation.ConversationType.GROUP, groupId, null)
                                            }

                                            override fun onError(errorCode: RongIMClient.ErrorCode) {}
                                        })
                                setSelectPage(MainTab.CHAT.reminderId)
                            }
//                            Const.PushMethod.FOLLOW_LIST -> {
//                                setSelectPage(MainTab.CIRCLE.reminderId)
//                                val circleFragment =
//                                    getChildFragment<AbsV4Fragment<BaseContract.BasePresenter>>(MainTab.CIRCLE.reminderId)
//                                bundle.putInt("select", 1)
//                                bundle.putBoolean("new_msg", true)
//                                circleFragment?.arguments = bundle
//                                MessageHelper.instance.isFllowTopic = true
//                            }
                            Const.PushMethod.TOPIC_COMMENT -> {
                                val intent = Intent()
                                intent.action = "com.bc_chat.circle.activity.TopicDetailsActivity"
                                intent.putExtra("cid", extra.getString("cid"))
                                intent.putExtra("commentId", extra.getString("commentId"))
                                intent.putExtra("selection", extra.getString("type"))
                                startActivity(intent)
                                MessageHelper.instance.isNewComment = true
                            }
                            Const.PushMethod.TOPIC_CHILD_COMMENT -> {
                                val intent = Intent()
                                intent.action = "com.bc_chat.circle.activity.TopicDetailsActivity"
                                intent.putExtra("cid", extra.getString("cid"))
                                intent.putExtra("commentId", extra.getString("commentId"))
                                intent.putExtra("selection", extra.getString("type"))
                                startActivity(intent)
                                MessageHelper.instance.isChildNewComment = true
                            }
                        }
                    }
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
            }
        }
    }

    override fun initPresenter(): MainPresenter = MainPresenter(this)

    override fun onInit() {
        Preferences.saveBoolean("isShow", false)
        setLightMode(resources.getColor(R.color.title_bg_color), false, false)
        inflater = LayoutInflater.from(this)
        initData()
        DownloadLibrary.setApkDownLoadListener { localPath ->
            apkLocalPath = localPath
            Utils.startInstall(this, localPath, 9999)
        }
        judgePermission(
                1,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.READ_CONTACTS,
                Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CALL_PHONE
        )
        parseIntent()
        if (!NotifyHelper.checkNotify(this)) {
            CustomDialog.Builder(this)
                    .setMessage("检测到您未开启通知推送")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("开启") { dialog, which ->
                        NotifyHelper.toSystemNotify(this)
                    }.create().show()
        }
        pushResult()
    }

    private fun initData() {
        presenter.userInfoTask(AppConfig.instance.getUser().userId)
        presenter.isSetPayKey()
        presenter.getLastestNotice()
        presenter.getNavData()
        presenter.applyFriendList(1, 1000)
        ObserverManager.getInstance().registerObserver(Const.ObserverKey.UN_READ_CHANGE, unReadChangeObserver)
        ObserverManager.getInstance().registerObserver(Const.ObserverKey.TOPIC_CHILD_COMMENT, newMsgObserver)
        ObserverManager.getInstance().registerObserver(Const.ObserverKey.TOPIC_COMMENT, newMsgObserver)
        ObserverManager.getInstance().registerObserver(Const.ObserverKey.FOLLOW_TOPIC, newMsgObserver)
        ObserverManager.getInstance().registerObserver(Const.ObserverKey.SCANNER_QRCODE, qrcodeObserver)
        ObserverManager.getInstance().registerObserver(Const.ObserverKey.NEW_FRIEND, newFriendObserver)
    }

    private fun getTabItemView(tab: MainTab): View? {
        val view = inflater?.inflate(R.layout.home_tab_layout, null)
        val tabView = view?.findViewById<TextView>(R.id.tabView)
        val tabIcon = view?.findViewById<ImageView>(R.id.tab_icon)
        tabIcon?.setImageResource(tab.resIcon)
        tabView?.text = tab.resName
        return view
    }

    private fun <T : AbsV4Fragment<*>> getChildFragment(tag: Int): T? {
        return supportFragmentManager.findFragmentByTag(tag.toString()) as T?
    }

    override fun userInfoSuccess(user: User?) {
        val currentUser = AppConfig.instance.getUser()
        if (!user?.userId.equals(currentUser.userId)) {
            //获取到的用户资料不是自己
            // 走加好友流程
            if (user?.is_myFriend == 0) {
                ARouter.getInstance().build(RouteConfig.ADD_FRIEND_ACTIVITY).withParcelable("userInfo", user)
                        .navigation()
            } else {
                ARouter.getInstance().navigation(ImRongService::class.java).startConversation(
                        this,
                        Conversation.ConversationType.PRIVATE,
                        user!!.userId,
                        user.nickname!!,
                        null
                )
            }
            return
        }
        currentUser.city = user?.city
        currentUser.introduction = user?.introduction
        currentUser.is_block = user?.is_block
        currentUser.is_report = user?.is_report
        currentUser.phone = user?.phone
        currentUser.nickname = user?.nickname
        currentUser.province = user?.province
        currentUser.photo = user?.photo
        ARouter.getInstance().navigation(ImRongService::class.java)
                .setCurrentUserInfo(currentUser.userId, currentUser.accessToken)
    }

    override fun userInfoFailure(e: Exception) {
    }

    override fun groupinfoSuccess(groupInfo: Group) {
        if ("1".equals(groupInfo.isInGroup)) {//如果已经在群里面
            ARouter.getInstance().navigation(ImRongService::class.java).startConversation(
                    this,
                    Conversation.ConversationType.GROUP,
                    groupInfo.groupId!!,
                    groupInfo.group_name!!,
                    null
            )
        } else {
            val currentUser = AppConfig.instance.getUser()
            presenter.addGroupMember(
                    groupInfo.groupId!!,
                    groupInfo.group_name!!,
                    currentUser.nickname!!,
                    currentUser.userId
            )
        }
        return
    }

    override fun groupinfoFailure(exception: Exception) {
    }

    override fun addGroupSuccess(groupId: String, groupName: String) {
        ARouter.getInstance().navigation(ImRongService::class.java)
                .startConversation(this, Conversation.ConversationType.GROUP, groupId, groupName, null)
    }

    override fun isSetPayKeySuccess(isSet: Boolean) {
        Preferences.setIsSetPayPwd(isSet);
    }

    override fun getLastestNoticeSuccess(noticeEntity: NoticeEntity?) {
        val dialogFragment = NoticeDialogFragment()
        dialogFragment.setNoticeEntity(noticeEntity)
        dialogFragment.isCancelable = false
        dialogFragment.show(supportFragmentManager, null)
    }

    override fun getNavDataSuccess(dataList: List<NavEntity>?) {
        if (dataList != null && dataList.size > 0) {
            var navJsonStr = GsonUtil.gsonString(dataList)
            Preferences.setNavJson(navJsonStr)
            showNav(dataList);
        }
    }

    override fun getNavDataFailed() {
        showNav(NavDataUtil.getNavData())
    }

    override fun applyFriendListSuccess(data: List<FriendApplyRecordBean>?) {
        if (NavDataUtil.isShowTipsMsg(data)) {
            ObserverManager.getInstance().notifyObserver(Const.ObserverKey.NEW_FRIEND, "add")
        }
    }

    private fun showNav(dataList: List<NavEntity>) {
        var nav1Name = ""
        var nav2Name = ""
        if (dataList.size == 1) {
            Nav1Fragment.homeUrl = dataList[0].url;
            nav1Name = dataList[0].title
        } else if (dataList.size == 2) {
            Nav1Fragment.homeUrl = dataList[0].url;
            Nav2Fragment.homeUrl = dataList[1].url;
            nav1Name = dataList[0].title
            nav2Name = dataList[1].title
        }

        binding.tabhost.setup(this, supportFragmentManager, R.id.contentPanel)
        for (tab in MainTab.values()) {
            if (tab.reminderId == ReminderId.NAV1) {
                if (!TextUtils.isEmpty(nav1Name)) {
                    tab.resName = nav1Name
                }
            } else if (tab.reminderId == ReminderId.NAV2) {
                if (!TextUtils.isEmpty(nav2Name)) {
                    tab.resName = nav2Name
                }
            }
            val tabSpec = binding.tabhost.newTabSpec(tab.reminderId.toString()).setIndicator(getTabItemView(tab))
            binding.tabhost.addTab(tabSpec, tab.clz, null)
            binding.tabhost.tabWidget.dividerDrawable = null
        }
        binding.tabhost.setOnTabChangedListener {
            if (it.equals(MainTab.NAV2.reminderId.toString())) {
                //跳转浏览器打开
                try {
                    val intent = Intent()
                    intent.action = Intent.ACTION_VIEW
                    intent.data = Uri.parse(Nav2Fragment.homeUrl)
                    startActivity(intent)
                } catch (e: ActivityNotFoundException) {
                    ToastUtils.show("手机还没有安装支持打开此网页的应用!")
                }
            }
        }
    }

    private fun setSelectPage(tag: Int) {
        binding.tabhost.setCurrentTabByTag(tag.toString())
    }

    private var firstTime: Long = 0

    override fun onBackPressed() {
        hideSoftInput()
        val intent = Intent(Intent.ACTION_MAIN)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        intent.addCategory(Intent.CATEGORY_HOME)
        startActivity(intent)
    }

    /**
     * 接收消息回调
     */
    private val unReadChangeObserver = Observer<Int> { key, var1 ->
        when (key) {
            Const.ObserverKey.UN_READ_CHANGE -> {
                runOnUiThread {
                    if (binding.tabhost.tabWidget != null) {
                        val view1 = binding.tabhost.tabWidget.getChildTabViewAt(0)
                        if (view1 != null) {
                            val view = view1.find<TextView>(R.id.tv_msg_count)
                            if (var1 > 0) {
                                view.visible()
                                if (var1 > 99) {
                                    view.text = "99+"
                                } else {
                                    view.text = var1.toString()
                                }
                            } else {
                                view.gone()
                            }
                        }
                    }
                }
            }
        }
    }

    private val newMsgObserver = Observer<String> { key, var1 ->
        when (key) {
            Const.ObserverKey.TOPIC_CHILD_COMMENT, Const.ObserverKey.TOPIC_COMMENT, Const.ObserverKey.FOLLOW_TOPIC -> {
                val view1 = binding.tabhost.tabWidget.getChildTabViewAt(3)
                if (view1 != null) {
                    view1.find<TextView>(R.id.tv_new_msg).visible()
                }
                if (key == Const.ObserverKey.TOPIC_CHILD_COMMENT) {
                    MessageHelper.instance.isChildNewComment = true
                }
                if (key == Const.ObserverKey.TOPIC_COMMENT) {
                    MessageHelper.instance.isNewComment = true
                }
                if (key == Const.ObserverKey.FOLLOW_TOPIC) {
                    MessageHelper.instance.isFllowTopic = true
                }
                if (Const.ObserverKey.FOLLOW_TOPIC.equals(key)) {
//                    val circleFragment =
//                        getChildFragment<AbsV4Fragment<BaseContract.BasePresenter>>(MainTab.CIRCLE.reminderId)
//                    bundle.putInt("select", -1)
//                    bundle.putBoolean("new_msg", true)
//                    circleFragment?.arguments = bundle
                }
            }
        }
    }

    override fun requestPermissionSuccess(requestCode: Int) {
        presenter.getUpdateVerson(false)
    }

    override fun getVersionUpdateDialog(
            version: Version?,
            confirmClickListener: DialogInterface.OnClickListener?,
            cancelClickListener: DialogInterface.OnClickListener?
    ): Dialog {
        return CustomDialog.Builder(this)
                .setTitle(getString(R.string._has_new_version, version?.releaseCode))
                .setMessage(
                        getString(
                                R.string.version_content_tip1_,
                                if (version?.tipsData == null) "" else version.tipsData
                        )
                )
                .setNegativeButton(R.string.talk_later, cancelClickListener)
                .setPositiveButton(R.string.immediately_update, confirmClickListener)
                .create()
    }

    override fun getForceUpdateDialog(version: Version?, onClickListener: DialogInterface.OnClickListener?): Dialog {
        return CustomDialog.Builder(this)
                .setTitle(getString(R.string._has_new_version, version?.releaseCode))
                .setMessage(
                        getString(
                                R.string.version_content_tips_,
                                if (version?.tipsData == null) "" else version.tipsData
                        )
                )
                .setPositiveButton(R.string.immediately_update, onClickListener)
                .setCancelable(false)
                .create()
    }

    override fun getUpdateVersonFailure(e: Exception) {
    }

    override fun getUpdateVersonSuccess(verson: ApkVersion) {
        verson?.let {
            val versionUpdateUtils = VersionUpdateUtils(this, false, this)
            versionUpdateUtils.checkNewVersion(
                    Version.Builder().setMandatory(it.mandatory == 2).setReleaseCode(
                            it.version
                    ).setUrl(verson.url).setTipsData(it.content).build()
            )
        }
    }

    override fun onResume() {
        super.onResume()
        loginIM()
    }

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

    /**
     * 登录融云
     */
    private fun loginIM() {
        val user = AppConfig.instance.getUser()
        ARouter.getInstance().navigation(ImRongService::class.java)
                .loginIM(user.userId, user.accessToken, Observer { key, var1 ->
                    if (key.equals(Const.ObserverKey.USER_LOGIN)) {
                        if (var1) {
                            getUnreadMsgCount()
                        } else {
                            ToastUtils.show("无法连接聊天服务器")
                        }
                    }
                })
    }

    /**
     * 识别二维码
     */
    private val qrcodeObserver = Observer<String> { key, var1 ->
        parseQrCode(var1)
    }

    private val newFriendObserver = Observer<String> { key, var1 ->
        runOnUiThread {
            if (binding.tabhost.tabWidget != null) {
                val view1 = binding.tabhost.tabWidget.getChildTabViewAt(1)
                if (view1 != null) {
                    val view = view1.find<TextView>(R.id.tv_new_msg)
                    if (var1.equals(tips_message_add)) {
                        view.visible()
                        Preferences.saveBoolean("isShow", true)
                    } else if (var1.equals(tips_message_clear)) {
                        view.gone()
                    } else {
                        view.gone()
                    }
                }
            }
        }
    }

    /**
     * 获取未读
     */
    private fun getUnreadMsgCount() {
        ARouter.getInstance().navigation(ImRongService::class.java).getUnreadMsgCount()
    }

    /**
     * 由于Arouter 不能使用frangment回传
     * 故此使用宿主activity的onActivityResult分发
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return
        if (requestCode == 9999) {
            Utils.installApk(this, apkLocalPath)
        }
        when (requestCode) {
            in 10..19 -> {
                getChildFragment<AbsV4Fragment<BaseContract.BasePresenter>>(ReminderId.CHAT)?.onActivityResult(
                        requestCode,
                        resultCode,
                        data
                )
            }
            in 20..29 -> {
                getChildFragment<AbsV4Fragment<BaseContract.BasePresenter>>(ReminderId.CONTACT)?.onActivityResult(
                        requestCode,
                        resultCode,
                        data
                )
            }
            in 30..39 -> {
                getChildFragment<AbsV4Fragment<BaseContract.BasePresenter>>(ReminderId.MINE)?.onActivityResult(
                        requestCode,
                        resultCode,
                        data
                )
            }
//            in 40..41 -> {
//                getChildFragment<AbsV4Fragment<BaseContract.BasePresenter>>(ReminderId.NAV1)?.onActivityResult(
//                        requestCode,
//                        resultCode,
//                        data
//                )
//            }
            Const.RequestCode.SCANNER -> {
                //二维码
//                type=bc_chat&userId=${user.userId}&nickname=${user.nickname}&phone=${user.phone}&photo=${user.photo}
                if (data == null) return
                val result = data.getStringExtra("result")
                parseQrCode(result)
            }
        }
    }

    private fun parseQrCode(result: String?) {
        if (!result.isNullOrEmpty()) {
            val uri = Uri.parse(result)
            if (uri == null) {
                ToastUtils.show("无法识别")
                return
            }
            Logger.e("MainActivity", uri.toString())
            val source = uri.getQueryParameter("source")
            if (Const.QR_CODE_URL_SOURCE.equals(source)) {
                val type = uri.getQueryParameter("type")
                if (Const.QrType.USER_TYPE.equals(type)) {
                    val userId = uri.getQueryParameter("id")
                    presenter.userInfoTask(userId)
                } else if (Const.QrType.GROUP_TYPE.equals(type)) {
                    val groupId = uri.getQueryParameter("id")
                    val name = uri.getQueryParameter("name")
                    presenter.groupinfoTask(groupId!!, name)
                } else {
                    ToastUtils.show("无法识别")
                }
            } else {
                if (result.startsWith("http") || result.startsWith("https")) {
                    val intent = Intent()
                    intent.action = "android.intent.action.VIEW"
                    val content_url = Uri.parse(result)
                    intent.data = content_url
                    startActivity(intent)
                }
            }
        } else {
            ToastUtils.show("无法识别")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        ObserverManager.getInstance().unregisterObserver(Const.ObserverKey.UN_READ_CHANGE, unReadChangeObserver)
        ObserverManager.getInstance().unregisterObserver(Const.ObserverKey.TOPIC_CHILD_COMMENT, newMsgObserver)
        ObserverManager.getInstance().unregisterObserver(Const.ObserverKey.TOPIC_COMMENT, newMsgObserver)
        ObserverManager.getInstance().unregisterObserver(Const.ObserverKey.FOLLOW_TOPIC, newMsgObserver)
        ObserverManager.getInstance().unregisterObserver(Const.ObserverKey.SCANNER_QRCODE, qrcodeObserver)
        ObserverManager.getInstance().unregisterObserver(Const.ObserverKey.NEW_FRIEND, newFriendObserver)
    }

}
