package com.ydl.audioim.presenter

import android.annotation.SuppressLint
import com.ydl.audioim.BuildConfig
import com.ydl.audioim.contract.IAudioHomeActivityContract
import com.ydl.audioim.http.command.ConnectCommand
import com.ydl.audioim.http.command.NoticePushCommand
import com.ydl.audioim.model.AudioHomeModelImpl
import com.ydl.audioim.utils.AudioLogUtils
import com.ydl.ydl_av.chat.config.YDLChatParam
import com.ydl.ydlcommon.mvp.base.BasePresenter
import com.ydl.ydlcommon.router.YdlCommonRouterManager
import com.ydl.ydlcommon.utils.LogUtil
import com.ydl.ydlcommon.utils.log.AliYunLogConfig
import com.ydl.ydlcommon.utils.log.AliYunRichLogsHelper
import com.ydl.ydlcommon.utils.log.LogHelper
import com.ydl.ydlcommon.utils.remind.ToastHelper
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.util.*

/**
 * @author jiucheng
 * @描述:
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/10/30
 */
class AudioHomePresenterImpl :
    BasePresenter<IAudioHomeActivityContract.View, IAudioHomeActivityContract.Model>(),
    IAudioHomeActivityContract.Presenter {
//    override fun connectStart(param: ConnectStartCommand) {
//        mModel.connectStart(param)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .doOnSubscribe {
//
//                }
//                .doAfterTerminate {
////                    view.dismissProgressView()
//                }
//                .subscribe({
////                    if (isSwitchAxb) {
////                        //切换axb：跳到拨号界面
////                        view.dialPhone()
////                    }
//                }, { e ->
//                    LogUtil.e(e.message)
//                })
//    }

//    override fun connectFinish(param: ConnectFinishCommand) {
//        mModel.connectFinish(param)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .doOnSubscribe {
//                    //通知服务端专家已经接通时，此时用户已在界面通话中，不需要弹进度条
//                    mView.showProgressView()
//                }
//                .doAfterTerminate {
//                    mView.dismissProgressView()
//                }
//                .subscribe({
////                    if (isSwitchAxb) {
////                        //切换axb：跳到拨号界面
////                        view.dialPhone()
////                    }
//                    //挂断逻辑：不管接口调用成功与否，都关闭界面
//                    mView.finishActivity()
//                }, { e ->
//                    LogUtil.e(e.message)
//                    //挂断逻辑：不管接口调用成功与否，都关闭界面
//                    mView.finishActivity()
//                })
//    }


    /**
     * 登录声网
     */
    override fun loginChatNet(signalingToken: String) {
        mView.showProgressView()
        // appId:应用id
        // account：uid
        // token ：由 App ID 和 App Certificate 生成的 SignalingToken (如果不使用token可以设为字符串 _no_need_token)
        // uid：固定填 0
        // deviceID：暂时无用，设置为空
        // retry_time_in_s：登录重试时间，默认为 30 秒
        // retry_count：登录重试次数，默认为 3 次
        val ydlChtat = YDLChatParam()
        ydlChtat.appId = BuildConfig.AGORA_APPID
        ydlChtat.account = YdlCommonRouterManager.getYdlCommonRoute().getUid().toString()
        ydlChtat.token = signalingToken
        ydlChtat.uid = 0
        ydlChtat.deviceID = ""
        ydlChtat.retry_time_in_s = 30
        ydlChtat.retry_count = 3

//        YDLChartManager.instance!!.getChatApi().login(ydlChtat)
    }

    /**
     * 获取axb电话
     */
    @SuppressLint("CheckResult")
    override fun getAXBPhone(cmd: ConnectCommand) {
        mModel.getAXBPhone(cmd)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe { mView.showProgressView() }
            .doAfterTerminate { mView.dismissProgressView() }
            .subscribe({
                if ("200" == it.code) {
                    if (0 == it.data?.dialDetail?.dialStatus ?: -1) {
                        //连接成功
                        if (it.data?.dialDetail?.callConnectType ?: -1 == 1) {
                            //axb
                            mView.switchAXBResponse(it.data?.dialDetail?.phoneNu ?: "")
                            AudioLogUtils.writeAgoraLog(
                                "连接成功,连接状态：${it.data?.dialDetail?.dialStatus}-------Time:${
                                    AudioLogUtils.format.format(
                                        Calendar.getInstance().time
                                    )
                                }", "confide.log", true
                            )
                        } else {
                            ToastHelper.show(it.data?.dialDetail?.dialReason ?: "连接失败")
                            AudioLogUtils.writeAgoraLog(
                                "连接状态：${it.data?.dialDetail?.dialStatus}失败原因：${it.data?.dialDetail?.dialReason}-------Time:${
                                    AudioLogUtils.format.format(
                                        Calendar.getInstance().time
                                    )
                                }", "confide.log", true
                            )
                            LogHelper.getInstance().uploadLog(false)
                        }
                    } else {
                        ToastHelper.show(it.data?.dialDetail?.dialReason ?: "连接失败")
                        AudioLogUtils.writeAgoraLog(
                            "连接状态：${it.data?.dialDetail?.dialStatus}失败原因：${it.data?.dialDetail?.dialReason}-------Time:${
                                AudioLogUtils.format.format(
                                    Calendar.getInstance().time
                                )
                            }", "confide.log", true
                        )
                        LogHelper.getInstance().uploadLog(false)
                    }
                } else {
                    ToastHelper.show(it.data?.dialDetail?.dialReason ?: "连接失败")
                    AudioLogUtils.writeAgoraLog(
                        "连接状态：${it.data?.dialDetail?.dialStatus}失败原因：${it.data?.dialDetail?.dialReason}-------Time:${
                            AudioLogUtils.format.format(
                                Calendar.getInstance().time
                            )
                        }", "confide.log", true
                    )
                    LogHelper.getInstance().uploadLog(false)
                }
            }, { e ->
                LogUtil.d(e.message)
                AudioLogUtils.writeAgoraLog(
                    "连接状态：${e.message}-------Time:${
                        AudioLogUtils.format.format(
                            Calendar.getInstance().time
                        )
                    }", "confide.log", true
                )
                LogHelper.getInstance().uploadLog(false)
            })
    }

    /**
     * 通知服务端发送推送
     */
    @SuppressLint("CheckResult")
    override fun noticeServerPush(param: NoticePushCommand) {
        mModel.noticeServerPush(param)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                if (it.code == 200) {
                    AudioLogUtils.writeAgoraLog(
                        "通知服务端发送推送成功-------Time:${
                            AudioLogUtils.format.format(
                                Calendar.getInstance().time
                            )
                        }", "confide.log", true
                    )
                    AliYunRichLogsHelper.getInstance()
                        .sendRichLog(
                            AliYunLogConfig.AGORA,
                            "通知服务端发送推送成功----接口：push/notify/doctor ---Time:${AudioLogUtils.format.format(Calendar.getInstance().time)}"
                        )
                } else {
                    LogUtil.e(it.msg)
                    AudioLogUtils.writeAgoraLog(
                        "通知服务端发送推送失败${it.msg}-------Time:${
                            AudioLogUtils.format.format(
                                Calendar.getInstance().time
                            )
                        }", "confide.log", true
                    )
                    AliYunRichLogsHelper.getInstance()
                        .sendRichLog(
                            AliYunLogConfig.AGORA,
                            "通知服务端发送推送失败${it.msg}--接口：push/notify/doctor -----Time:${AudioLogUtils.format.format(Calendar.getInstance().time)}"
                        )
                    LogHelper.getInstance().uploadLog(false)
                }
            }, { e ->
                AudioLogUtils.writeAgoraLog(
                    "通知服务端发送推送失败${e.message}-------Time:${
                        AudioLogUtils.format.format(
                            Calendar.getInstance().time
                        )
                    }", "confide.log", true
                )
                AliYunRichLogsHelper.getInstance()
                    .sendRichLog(
                        AliYunLogConfig.AGORA,
                        "通知服务端发送推送失败${e.message}--接口：push/notify/doctor -----Time:${AudioLogUtils.format.format(Calendar.getInstance().time)}"
                    )
                LogHelper.getInstance().uploadLog(false)
                LogUtil.e(e.message)
            })
    }


    override fun createModel(): IAudioHomeActivityContract.Model {
        return AudioHomeModelImpl()
    }
}