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

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import com.alibaba.android.arouter.launcher.ARouter
import com.ydl.audioim.IntentConstants
import com.ydl.audioim.YDLavManager
import com.ydl.audioim.bean.ExpertInfoBean
import com.ydl.audioim.widget.AxbConfirmDialog
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.home.util.ConfideNetworkUtil
import com.ydl.webview.H5Params
import com.ydl.webview.NewH5Activity
import com.ydl.webview.TellData
import com.ydl.ydlcommon.base.BaseApp
import com.ydl.ydlcommon.modular.ModularServiceManager
import com.ydl.ydlcommon.utils.remind.ToastHelper
import com.ydl.ydlcommon.view.dialog.CommonDialog
import com.yidianling.common.tools.RxSPTool
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.schedulers.Schedulers

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

    //倾诉支付弹窗
    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)
    }

    //java版axb和声网接口
    @SuppressLint("CheckResult")
    fun connectionJava(
        id: Int,
        type: Int,
        activity: Activity,
        tellData: TellData?,
        callType: String?
    ) {
        ConfideHomeDataManager.getHttp()
            .connectionJava(ConnectParamJava("" + id, "" + type, callType))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                if ("200" == it.code) {
                    if (it.data?.dialDetail?.dialStatus != null) {
                        if (100007 == it.data?.dialDetail?.dialStatus) {
                            //支付弹窗
                            //参数转换
                            var confidePay = ConfidePayParams(
                                it.data?.payTitle ?: "倾诉服务",
                                it.data?.listenOrderPrice,
                                it.data?.coupon?.couponMoney ?: 0.00,
                                it.data?.userBaseInfoRespDto?.availableMoney ?: 0.00,
                                it.data?.payId ?: "",
                                "",
                                ""
                            )
                            confidePayDialog(id, type, activity, confidePay, callType)
                        } else if (100008 == it.data?.dialDetail?.dialStatus) {
                            CommonDialog(activity)
                                .setCancelAble(false)
                                .setMessage(FinalString.TEL_BINDPHONE)
                                .setLeftOnclick("忍痛放弃", null)
                                .setRightClick("果断绑定") { view ->
                                    try {
                                        ModularServiceManager.provide(IUserService::class.java)
                                            .wxBindToInputhonePage(activity)
                                    } catch (e: Exception) {
                                    }
                                }
                                .show()
                        } else if (0 == it.data?.dialDetail?.dialStatus) {
                            //连接成功
                            if (it.data?.dialDetail?.callConnectType ?: -1 == 3) {
                                //声网
                                it.data?.dialDetail?.agoraExpertInfo ?: return@subscribe
                                if (!YDLavManager.isOnlineRtm){ // 判断如果账号在其它设备登录rtm是否在线
                                    ToastUtil.toastShort("网络通话错误代码001")
                                    return@subscribe
                                }
                                callAgora(
                                    activity,
                                    id,
                                    it.data!!.dialDetail!!.agoraExpertInfo!!,
                                    it.data.callId ?: "0",
                                    it.data.listenOrderId ?: 0L,
                                    tellData,
                                    it.data.isShowAxb,
                                    it.data?.dialDetail?.dialStatus.toString()
                                )
                            } else {
                                //axb
                                val dialog = AxbConfirmDialog(
                                    activity,
                                    1,
                                    object : AxbConfirmDialog.OnClickEnsureListener {
                                        override fun onClickEnsure() {
                                            var phoneIntent = Intent(
                                                Intent.ACTION_DIAL,
                                                Uri.parse("tel:${it.data?.dialDetail?.phoneNu ?: 0}")
                                            )
                                            activity.startActivity(phoneIntent)
                                        }

                                        override fun onClose() {

                                        }
                                    })
                                dialog.show()
                            }
                        } else {
                            ToastHelper.show(it.data?.dialDetail?.dialReason ?: "连接失败")
                        }
                    } else {
                        ToastHelper.show(it.data?.dialDetail?.dialReason ?: "连接失败")
                    }
                } else {
                    ToastHelper.show(it.msg)
                }
            }, {
                ToastHelper.show(it.message ?: "连接失败")
            })
    }

    //启动声网电话
    private fun callAgora(
        activity: Activity,
        confideId: Int,
        expertInfo: ExpertInfoBean,
        call_id: String,
        relation_id: Long,
        tellData: TellData?,
        isShowAXB: Boolean,
        dialStatus: String
    ) {
        //3G以下或者其他不确定异常能判断出来的
        if (!ConfideNetworkUtil.isWifiOr3G(activity)) {
            CommonDialog.create(activity)
                .setTitle("温馨提示")
                .setMessage("当前网络异常\n请使用普通电话拨打？")
                .setLeftOnclick("暂不拨打") {

                }
                .setRightClick("普通电话拨号") {
                    connectionJava(confideId, 1, activity, tellData, "0")
                }
                .show()
        } else {
            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);
            }

            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)
        }
    }


}
