package com.ydl.confide.home.modular.service

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.text.TextUtils
import androidx.fragment.app.FragmentActivity
import com.alibaba.android.arouter.launcher.ARouter
import com.ydl.audioim.api.IAudioImService
import com.ydl.audioim.bean.ExpertInfoBean
import com.ydl.audioim.listener.IntentConstants
import com.ydl.confide.home.ConfidePermissionDialog
import com.ydl.confide.home.bean.ConfideConnectResponse
import com.ydl.confide.home.bean.ConnectParamJava
import com.ydl.confide.home.constants.FinalString
import com.ydl.confide.home.http.ConfideHomeDataManager
import com.ydl.confide.router.PhoneCallIn
import com.ydl.webview.H5Params
import com.ydl.webview.NewH5Activity
import com.ydl.webview.TellData
import com.ydl.ydlcommon.modular.findRouteService
import com.ydl.ydlcommon.ui.Loading
import com.ydl.ydlcommon.utils.log.AliYunLogConfig
import com.ydl.ydlcommon.utils.log.AliYunRichLogsHelper
import com.ydl.ydlcommon.utils.remind.ToastHelper
import com.ydl.ydlcommon.view.dialog.CommonDialog
import com.yidianling.common.tools.ToastUtil
import com.yidianling.user.api.service.IUserService
import com.yidianling.ydl_pay.pay.payDialog.CallBack
import com.yidianling.ydl_pay.pay.payDialog.ConfidePayParams
import com.yidianling.ydl_pay.pay.payDialog.PayDialog
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers


/**
 * Created by haorui on 2019-10-10.
 * Des: 对应主项目中的WebServiceImpl
 */
class ConfideWebServiceImpl {

    //倾诉支付弹窗
    private fun confidePayDialog(
        id: Int?,
        type: Int?,
        activity: Activity,
        confidePay: ConfidePayParams,
        callType: String?
    ) {
        PayDialog(activity)
            .setCallback(object : CallBack {
                override fun onSuccess() {
                    //支付成功，直接拨打
                    if (TextUtils.isEmpty(confidePay.confideUrl)) {
                        connectionJava(id ?: 0, type ?: 1, activity, null, callType)
                    } else {
                        //倾诉订单列表页面过来，会有confideUrl值，则直接跳转此url
                        NewH5Activity.start(activity, H5Params(confidePay.confideUrl!!, ""))
                    }
                }


                override fun onError() {
                }

            })
            .show(confidePay)
    }

    private fun needPay(
        id: Int,
        type: Int,
        activity: Activity,
        callType: String?,
        data: ConfideConnectResponse?
    ) {
        //支付弹窗
        //参数转换
        val confidePay = ConfidePayParams(
            data?.payTitle ?: "倾诉服务",
            data?.listenOrderPrice,
            data?.coupon?.couponMoney ?: 0.00,
            data?.userBaseInfoRespDto?.availableMoney ?: 0.00,
            data?.payId ?: "",
            "",
            ""
        )
        confidePayDialog(id, type, activity, confidePay, callType)
    }

    private fun needBindPhone(activity: Activity) {
        CommonDialog(activity)
            .setCancelAble(false)
            .setMessage(FinalString.TEL_BINDPHONE)
            .setLeftOnclick("忍痛放弃", null)
            .setRightClick("果断绑定") {
                findRouteService(IUserService::class.java).wxBindToInputhonePage(activity)
            }
            .show()
    }

    fun agora(
        id: Int,
        activity: Context,
        data: ConfideConnectResponse?
    ) {
        val expertInfo = data?.dialDetail?.agoraExpertInfo ?: return
        if (!findRouteService(IAudioImService::class.java).getIsOnlineRtm()) { // 判断如果账号在其它设备登录rtm是否在线
            ToastUtil.toastShort("网络通话错误代码001")
            return
        }
        callAgora(
            activity,
            id,
            expertInfo,
            data.callId ?: "0",
            data.listenOrderId ?: 0L,
            data.isShowAxb,
            data.dialDetail?.dialStatus.toString()
        )
    }

    /**
     * axb 通话
     * */
    fun axb(activity: Activity, phone: String?) {
        if (phone.isNullOrEmpty())
            return
        findRouteService(IAudioImService::class.java).openAxbDialog(activity,1,phone)
    }

    //java版axb和声网接口
    @SuppressLint("CheckResult")
    fun connectionJava(
        id: Int,
        type: Int,
        activity: Activity,
        tellData: TellData?,
        callType: String?
    ) {
        if (!findRouteService(IAudioImService::class.java).getIsOnlineRtm()) {
            findRouteService(IAudioImService::class.java).loginRtm(PhoneCallIn.getUserService().getUserInfo()?.uid) { isSuccess: Boolean, _ ->
                if (isSuccess) {
                    toDial(id, type, callType, activity, tellData)
                } else {
                    ToastUtil.toastShort("网络通话错误代码001")
                }
            }
        }else{
            toDial(id, type, callType, activity, tellData)
        }
    }

    @SuppressLint("CheckResult")
    private fun toDial(
        id: Int,
        type: Int,
        callType: String?,
        activity: Activity,
        tellData: TellData?
    ) {
        Loading.show(activity)
        ConfideHomeDataManager.getHttp()
            .submitOrderAndPay(ConnectParamJava("" + id, "" + type, callType ?: ""))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                Loading.close()
                if ("200" == it.code) {
                    when (it.data?.dialDetail?.dialStatus) {
                        0 -> {//连接成功
                            if (type == 3) {
                                //checkpermission
                                checkPermission(id, type, activity, callType)
                            } else {
                                //axb
                                listenDial(id, type, activity, callType ?: "")
                            }
                        }
                        100007 -> {
                            needPay(id, type, activity, callType, it.data)
                        }
                        100008 -> {
                            needBindPhone(activity)
                        }
                        else -> {
                            ToastHelper.show(it.data?.dialDetail?.dialReason ?: "连接失败")
                        }
                    }
                } else {
                    ToastHelper.show(it.msg)
                }
            }, {
                Loading.close()
                ToastHelper.show(it.message ?: "连接失败")
            })
    }

    /**
     * 检查权限
     * */
    @SuppressLint("CheckResult")
    private fun checkPermission(id: Int, type: Int, activity: Activity, callType: String?) {
        (activity as? FragmentActivity)?.let {
            ConfidePermissionDialog().apply {
                callback = { granted ->
                    if (granted) {
                        listenDial(id, type, activity, callType ?: "")
                        AliYunRichLogsHelper.getInstance()
                            .sendRichLog(AliYunLogConfig.AGORA, "请求音频权限通过")
                    } else {
                        listenDial(id, 1, activity, callType ?: "")
                        AliYunRichLogsHelper.getInstance()
                            .sendRichLog(AliYunLogConfig.AGORA, "权限拒绝 转axb")
                    }

                }
            }.show(it.supportFragmentManager, "ConfidePermissionDialog")
        }
    }


    @SuppressLint("CheckResult")
    fun listenDial(
        id: Int,
        type: Int,
        activity: Activity,
        callType: String
    ) {
        ConfideHomeDataManager.getHttp()
            .connectionJava(ConnectParamJava("" + id, "" + type, callType))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                if ("200" == it.code) {
                    when (it.data?.dialDetail?.dialStatus) {
                        0 -> {//连接成功
                            if (it.data?.dialDetail?.callConnectType == 3) {
                                agora(id, activity, it.data)
                            } else {
                                axb(activity, it.data?.dialDetail?.phoneNu)
                            }
                        }
                        else -> {
                            ToastHelper.show(it.data?.dialDetail?.dialReason ?: "连接失败")
                        }
                    }
                } else {
                    ToastHelper.show(it.msg)
                }
            }, {
                ToastHelper.show(it.message ?: "连接失败")
            })

    }

    fun connectionJava(
        id: Int,
        type: Int,
        activity: Context,
        callType: String?,
        otherwise: (() -> Unit)? = null
    ): Disposable {
        Loading.show(activity)
        return ConfideHomeDataManager.getHttp()
            .submitOrderAndPay(ConnectParamJava("" + id, "" + type, callType ?: ""))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                Loading.close()
                if ("200" == it.code) {
                    when (it.data?.dialDetail?.dialStatus) {
                        0 -> {//连接成功
                            if (type == 3) {
                                //检查音频权限
                                checkPermission(id, type, activity as Activity, callType)
                            } else {
                                //axb
                                listenDial(id, type, activity as Activity, callType ?: "")
                            }
                        }
                        100007 -> {
                            otherwise?.invoke()
                        }
                        100008 -> {
                            if (activity is Activity) {
                                needBindPhone(activity)
                            }
                        }
                        else -> {
                            ToastHelper.show(it.data?.dialDetail?.dialReason ?: "连接失败")
                        }
                    }
                } else {
                    ToastHelper.show(it.msg)
                }
            }, {
                ToastHelper.show(it.message ?: "连接失败")
                Loading.close()
            })
    }

    //启动声网电话
    private fun callAgora(
        activity: Context,
        confideId: Int,
        expertInfo: ExpertInfoBean,
        call_id: String,
        relation_id: Long,
        isShowAXB: Boolean,
        dialStatus: String
    ) {
        if (expertInfo.listenerStatus != 1) {
            ToastHelper.show("老师正在通话中，请稍后重试")
            return
        }

        if (TextUtils.isEmpty(expertInfo.channelId)) {
            ToastHelper.show("服务端返回参数异常，请刷新页面后重试")
            return
        }

        if (expertInfo.remainingTime?.remainingTime == null) {
            expertInfo.remainingTime =
                ExpertInfoBean.ListenRemainingTime(expertInfo.totalDuration);
        }
        findRouteService(IAudioImService::class.java).callEventSave("10", "用户点击拨打", expertInfo.channelId, "7")
        Loading.close()
        ARouter.getInstance().build("/av/AudioHomeActivity")
            .withString(IntentConstants.INTENT_EXPERT_HEAD_URL, expertInfo.expertHeadUrl)
            .withString(IntentConstants.INTENT_EXPERT_NAME, expertInfo.expertName)
            .withString(IntentConstants.INTENT_EXPERT_TIPS, expertInfo.expertTips)
            .withString(IntentConstants.INTENT_ROOM_ID, expertInfo.channelId)
            .withString(
                IntentConstants.INTENT_REMAIN_TIME,
                expertInfo.remainingTime.remainingTime
            )
            .withString(IntentConstants.INTENT_CALL_ID, call_id)
            .withString(IntentConstants.INTENT_RELATION_ID, "${relation_id}")
            .withString(IntentConstants.INTENT_TOKEN, expertInfo.token)
            .withString(IntentConstants.INTENT_SIGNAL_TOKEN, expertInfo.signalToken)
            .withString(IntentConstants.INTENT_LISTENER_UID, expertInfo.listenerUid)
            .withString(IntentConstants.INTENT_TOTAL_DURATION, expertInfo.totalDuration)
            .withString(IntentConstants.INTENT_COMMENT_URL, expertInfo.commentUrl)
            .withString(IntentConstants.INTENT_LISTEN_ID, confideId.toString())
            .withString(IntentConstants.INTENT_DIALSTATUS, dialStatus)
            .withBoolean(IntentConstants.INTENT_ISSHOWAXB, isShowAXB)
            .navigation(activity)

    }
}
