package com.cooleshow.teacher.ui.web;

import static com.luck.picture.lib.thread.PictureThreadUtils.runOnUiThread;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothHeadset;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.media.AudioDeviceInfo;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.cooleshow.base.bean.WxPayResult;
import com.cooleshow.base.common.WebConstants;
import com.cooleshow.base.constanst.Constants;
import com.cooleshow.base.data.net.RetrofitClientNoToken;
import com.cooleshow.base.recorder.AudioChunk;
import com.cooleshow.base.recorder.AudioRecordConfig;
import com.cooleshow.base.recorder.MsRecorder;
import com.cooleshow.base.recorder.PullTransport;
import com.cooleshow.base.recorder.Recorder;
import com.cooleshow.base.ui.fragment.BaseFragment;
import com.cooleshow.base.ui.fragment.BaseMVPFragment;
import com.cooleshow.base.utils.AppUtils;
import com.cooleshow.base.utils.HeadsetPlugListener;
import com.cooleshow.base.utils.HeadsetPlugReceiver;
import com.cooleshow.base.utils.PermissionUtils;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.utils.ToastUtils;
import com.cooleshow.base.websocket.JWebSocketClient;
import com.cooleshow.base.widgets.BaseDialog;
import com.cooleshow.base.widgets.CommonDialog;
import com.cooleshow.base.widgets.DialogUtil;
import com.cooleshow.base.widgets.ViewConvertListener;
import com.cooleshow.base.widgets.ViewHolder;
import com.cooleshow.teacher.BuildConfig;
import com.cooleshow.teacher.api.APIService;
import com.cooleshow.teacher.bean.alipay.AuthResult;
import com.cooleshow.teacher.bean.alipay.PayResult;
import com.cooleshow.teacher.bean.weixinpay.WeixinPayInfo;
import com.cooleshow.teacher.databinding.FragmentAccompanyBinding;
import com.cooleshow.teacher.databinding.FragmentMineLayoutBinding;
import com.cooleshow.teacher.presenter.main.MinePresenter;
import com.cooleshow.teacher.presenter.web.AccompanyPresenter;
import com.cooleshow.teacher.widgets.FileUtils;
import com.cooleshow.teacher.widgets.LollipopFixedWebView;
import com.cooleshow.teacher.widgets.helper.JsInterfaceAccomPanyUtils;
import com.cooleshow.usercenter.helper.UserHelper;
import com.google.gson.Gson;
import com.jinmingyunle.midiplaylib.MidiPlayerUtils;
import com.tbruyelle.rxpermissions3.RxPermissions;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;
import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.lang.ref.WeakReference;
import java.net.URI;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * 创建日期：2022/6/8 14:32
 *
 * @author Ryan
 * 类说明：
 */
public class AccompanyFragment extends BaseMVPFragment<FragmentAccompanyBinding, AccompanyPresenter> implements JsInterfaceAccomPanyUtils.onGetMethodsListener {
    private final static String TAG = "AccompanyFragmenttag";
    private IWXAPI api;
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    FrameLayout viewParent;
    WebView webView;
    private UMShareListener mShareListener;
    private String url;
    private Recorder wavRecorder;
    private JWebSocketClient webSocketClient;
    private ShareAction mShareAction;
    private URI webSocketUri = URI.create("BuildConfig.BASE_STU_SOCKET_URL");

    public static AccompanyFragment newInstance(String url) {
        AccompanyFragment fragment = new AccompanyFragment();
        Bundle args = new Bundle();
        args.putString("url", url);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        api = WXAPIFactory.createWXAPI(getContext(), null);
        api.registerApp("wx149a928c415c137a");
    }


    @Override
    protected FragmentAccompanyBinding getLayoutView() {
        return FragmentAccompanyBinding.inflate(getLayoutInflater());
    }

    @Override
    protected AccompanyPresenter createPresenter() {
        return new AccompanyPresenter();
    }

    @Override
    protected void initView(View rootView) {
        viewParent = mViewBinding.viewParent;
        ;
        if (getArguments() != null) {
            url = getArguments().getString("url");
        }
        String localUserId = UserHelper.getUserId();
        webSocketUri = URI.create(WebConstants.getWebSocketUrl() + "/" + localUserId);
        try {
            if (Build.VERSION.SDK_INT >= 21 && Build.VERSION.SDK_INT < 23) {
                webView = new LollipopFixedWebView(getActivity());
            } else {
                webView = new WebView(getActivity());
            }
        } catch (Exception e) {

        }
        if (null == webView) {
            return;
        }
        JsInterfaceAccomPanyUtils jsInterfaceUtils = new JsInterfaceAccomPanyUtils(getActivity());
        jsInterfaceUtils.setOnGetMethodsListener(this);
        webView.addJavascriptInterface(jsInterfaceUtils, WebConstants.WEB_JS_INTERFACE);
        viewParent.addView(webView, new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT));
        webView.setBackgroundColor(0);
        initWebView();
        webView.setWebViewClient(new WebClient());
        webView.loadUrl(url);

    }


    @Override
    protected void initData() {
        mShareListener = new CustomShareListener(getActivity());
    }


    private void initWebView() {
        //声明WebSettings子类
        WebSettings webSettings = webView.getSettings();
        webSettings.setUserAgentString(webSettings.getUserAgentString() + WebConstants.WEB_UA_PARAMS);
        webSettings.setGeolocationDatabasePath(getContext().getFilesDir().getPath());
        webSettings.setGeolocationEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);
        webSettings.setMediaPlaybackRequiresUserGesture(false);//false允许自动播放音视频
        //是否启用缓存
        webSettings.setAppCacheEnabled(true);

        // 开启DOM缓存,默认状态下是不支持LocalStorage的
        webSettings.setDomStorageEnabled(true);
        // 开启数据库缓存
        webSettings.setDatabaseEnabled(true);

        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        //缩放操作
        webSettings.setSupportZoom(false); //支持缩放，默认为true。是下面那个的前提。
        // 设置允许JS弹窗
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        //其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("UTF-8");//设置编码格式

        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);  //富文本适配
        webSettings.setAppCacheMaxSize(Long.MAX_VALUE);
        webSettings.setAppCachePath(getActivity().getDir("appcache", 0).getPath());
        webSettings.setDatabasePath(getActivity().getDir("databases", 0).getPath());
        webSettings.setGeolocationDatabasePath(getActivity().getDir("geolocation", 0)
                .getPath());
        webSettings.setPluginState(WebSettings.PluginState.ON_DEMAND);
        if (BuildConfig.DEBUG) {
            webView.setWebContentsDebuggingEnabled(true);
        }
        webSettings.setTextZoom(100);//设置字体默认的缩放比例，以避免手机系统的字体修改对页面字体及布局造成影响。
        webView.setHorizontalScrollBarEnabled(false);
        webView.setVerticalScrollBarEnabled(false);


    }

    @Override
    public void onSendMessage(String message) {
        webView.evaluateJavascript("postMessage('" + message + "')", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String s) {
            }
        });
    }

    private int setColorCount = 0;

    @Override
    public void setStatusBarTextColor(boolean statusBarTextColor, JSONObject message) {
        setColorCount++;
        if (setColorCount == 1) {
            if (onAccompanyListener != null)
                onAccompanyListener.setStatusBarTextColor(false);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    onSendMessage(message.toString());
                }
            }, 1500);
        }

    }

    boolean isSendStartEvaluatingMessage = false;
    boolean isWiredHeadsetOn = false;

    /**
     * 开始评测
     *
     * @param message
     */
    @SuppressLint("CheckResult")
    @Override
    public void startEvaluating(JSONObject message) {
        isWiredHeadsetOn = false;
        isSendStartEvaluatingMessage = true;
        new RxPermissions(this)
                .request(Manifest.permission.RECORD_AUDIO)
                .subscribe(permission -> {
                    if (permission) {
//                        startWebSocketClient(message);
                        if (webSocketClient != null) {
                            if (webSocketClient.getReadyState() == ReadyState.NOT_YET_CONNECTED) {
                                if (webSocketClient.isClosed()) {
                                    webSocketClient.reconnectBlocking();
                                } else {
                                    webSocketClient.reconnectBlocking();
                                }
                            } else if (webSocketClient.getReadyState() == ReadyState.CLOSED) {
                                webSocketClient.reconnectBlocking();
                            }
                            onSendMessage(message.toString());
                            try {
                                JSONObject jsonObject = new JSONObject();
                                JSONObject headerObject = new JSONObject();
                                headerObject.put("commond", "musicXml");
                                headerObject.put("type", "SOUND_COMPARE");
                                headerObject.put("status", 200);
                                jsonObject.put("header", headerObject);
                                jsonObject.put("body", message.getJSONObject("content"));
                                webSocketClient.send(jsonObject.toString());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            startWebSocketClient(message);
                        }


                    } else {
                        try {
                            JSONObject content = message.getJSONObject("content");
                            content.put("reson", "没有麦克风权限");
                            onSendMessage(message.toString());
                            isSendStartEvaluatingMessage = false;
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        DialogUtil.showInCenter(getChildFragmentManager(), com.cooleshow.base.R.layout.accompany_permissions_popu, (holder, dialog) -> {
                            TextView tvTitle = holder.getView(com.cooleshow.base.R.id.tv_title);
                            TextView tvContent = holder.getView(com.cooleshow.base.R.id.tv_content);
                            TextView btncancel = holder.getView(com.cooleshow.base.R.id.btn_cancel);
                            TextView btnCommit = holder.getView(com.cooleshow.base.R.id.btn_commit);
                            tvTitle.setText("提示");
                            tvContent.setText("请开启麦克风访问权限");
                            btncancel.setOnClickListener(view1 -> {

                                dialog.dismiss();

                            });
                            btnCommit.setOnClickListener(view1 -> {
                                PermissionUtils.toSelfSetting(getContext());
                                dialog.dismiss();
                            });
                        });
                    }
                });

    }

    JSONObject msg = null;

    private void startWebSocketClient(JSONObject message) throws JSONException {
        msg = message;
        if (webSocketClient == null) {
            Observable.create(new ObservableOnSubscribe<String>() {
                @Override
                public void subscribe(@NonNull ObservableEmitter<String> emitter) throws Exception {
                    Map<String, String> httpHeaders = new HashMap<String, String>();
                    httpHeaders.put("Authorization", UserHelper.getUserToken());
                    webSocketClient = new JWebSocketClient(webSocketUri, httpHeaders) {
                        @Override
                        public void onMessage(String message) {
                            emitter.onNext(message);
                        }

                        @Override
                        public void onError(Exception ex) {
                            super.onError(ex);
                            emitter.onNext("-2");
                        }

                        @Override
                        public void onOpen(ServerHandshake handshakedata) {
                            super.onOpen(handshakedata);
                            emitter.onNext("-1");

                        }

                        @Override
                        public void onClose(int code, String reason, boolean remote) {
                            super.onClose(code, reason, remote);
                            emitter.onNext("-2");
                        }
                    };
                    webSocketClient.setConnectionLostTimeout(60 * 1000);
                    webSocketClient.connect();
                }
            }).subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<String>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@NonNull String serverMsg) {

                            if ("-1".equals(serverMsg) && isWiredHeadsetOn) {
                                if (msg != null) {
                                    onSendMessage(msg.toString());
                                }

                            } else if ("-1".equals(serverMsg) && isSendStartEvaluatingMessage) {

                                if (msg != null) {
                                    onSendMessage(msg.toString());
                                }
                                try {
                                    JSONObject jsonObject = new JSONObject();
                                    JSONObject headerObject = new JSONObject();
                                    headerObject.put("commond", "musicXml");
                                    headerObject.put("type", "SOUND_COMPARE");
                                    headerObject.put("status", 200);
                                    jsonObject.put("header", headerObject);
                                    jsonObject.put("body", msg.getJSONObject("content"));
                                    webSocketClient.send(jsonObject.toString());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else if ("-2".equals(serverMsg)) {
                                if (isSendStartEvaluatingMessage) {
                                    isSendStartEvaluatingMessage = false;

                                    try {
                                        if (msg != null) {
                                            JSONObject content = msg.getJSONObject("content");
                                            content.put("reson", "服务异常，请重试");
                                            onSendMessage(msg.toString());
                                            msg = null;
                                        }
                                    } catch (Exception e3) {
                                        e3.printStackTrace();
                                    }
                                } else if (isWiredHeadsetOn) {
                                    isWiredHeadsetOn = false;
                                    return;
                                }
//                                } else {
//                                    LOG.i(TAG, "onNext: serverMsg333" + isWiredHeadsetOn);
//                                    JSONObject object = new JSONObject();
//                                    JSONObject reson = new JSONObject();
//                                    try {
//                                        reson.put("reson", "服务异常，请重试");
//                                        object.put("api", "cancelEvaluating");
//                                        object.put("content", reson);
//                                        onSendMessage(object.toString());
//                                    } catch (JSONException e2) {
//                                        e2.printStackTrace();
//                                    }
//                                }
                            } else {
                                JSONObject object = new JSONObject();
                                try {
                                    object.put("api", "sendResult");
                                    object.put("content", new JSONObject(serverMsg));
                                    onSendMessage(object.toString());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                            msg = null;

                        }

                        @Override
                        public void onError(@NonNull Throwable e) {

                            if (isSendStartEvaluatingMessage) {
                                isSendStartEvaluatingMessage = false;
                                try {
                                    JSONObject content = msg.getJSONObject("content");
                                    content.put("reson", "服务异常，请重试");
                                    onSendMessage(msg.toString());
                                    msg = null;
                                } catch (Exception e3) {
                                    e3.printStackTrace();
                                }
                            } else if (isWiredHeadsetOn) {
                                isWiredHeadsetOn = false;
                            } else {
                                JSONObject object = new JSONObject();
                                JSONObject reson = new JSONObject();
                                try {
                                    reson.put("reson", "服务异常，请重试");
                                    object.put("api", "cancelEvaluating");
                                    object.put("content", reson);
                                    onSendMessage(object.toString());
                                } catch (Exception e2) {
                                    e.printStackTrace();
                                }
                            }
                            msg = null;
                        }

                        @Override
                        public void onComplete() {

                        }
                    });


        } else if (webSocketClient.isClosed() || webSocketClient.isClosing()) {

            if (isWiredHeadsetOn) {
                isSendStartEvaluatingMessage = false;
            } else {
                isSendStartEvaluatingMessage = true;
            }
            webSocketClient.reconnect();
        } else {
            if (isWiredHeadsetOn) {
                isSendStartEvaluatingMessage = false;
            } else if (isSendStartEvaluatingMessage) {
                isWiredHeadsetOn = false;
                try {
                    JSONObject jsonObject = new JSONObject();
                    JSONObject headerObject = new JSONObject();
                    headerObject.put("commond", "musicXml");
                    headerObject.put("type", "SOUND_COMPARE");
                    headerObject.put("status", 200);
                    jsonObject.put("header", headerObject);
                    jsonObject.put("body", message.getJSONObject("content"));
                    webSocketClient.send(jsonObject.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            onSendMessage(message.toString());


        }
    }

    boolean isSendRecordStartTime = false;

    /**
     * 开始录音
     *
     * @param message
     */
    public void startRecording(JSONObject message) {
        onSendMessage(message.toString());

        isSendRecordStartTime = true;
        if (webSocketClient != null && webSocketClient.isOpen()) {
            try {
                JSONObject jsonObject = new JSONObject();
                JSONObject headerObject = new JSONObject();
                headerObject.put("commond", "recordStart");
                headerObject.put("type", "SOUND_COMPARE");
                headerObject.put("status", 200);
                jsonObject.put("header", headerObject);
                webSocketClient.send(jsonObject.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (wavRecorder != null) {
            wavRecorder.stopRecording();
            FileUtils.deleteFile(getVoicePath());
            wavRecorder.startRecording(getContext());
        } else {
            Observable.create((ObservableOnSubscribe<String>) emitter -> {
                wavRecorder = MsRecorder.wav(
                        new File(getVoicePath()),
                        new AudioRecordConfig(),
                        // AudioRecordConfig(MediaRecorder.AudioSource.MIC, AudioFormat.ENCODING_PCM_16BIT, AudioFormat.CHANNEL_IN_MONO, 44100),
                        new PullTransport.Default().setOnAudioChunkPulledListener(new PullTransport.OnAudioChunkPulledListener() {
                            @Override
                            public void onAudioChunkPulled(AudioChunk audioChunk) {
                                if (webSocketClient != null && webSocketClient.isOpen()) {
                                    webSocketClient.send(audioChunk.toBytes());
                                    if (isSendRecordStartTime) {
                                        isSendRecordStartTime = false;
                                        emitter.onNext("-2");
                                    }
                                } else {
                                    emitter.onNext("-1");
                                }
                            }
                        }));
                if (wavRecorder != null) {
                    wavRecorder.startRecording(getContext());
                }
                emitter.onNext("1");
            }).subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<String>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@NonNull String recorder) {
                            if ("-2".equals(recorder) && isSendStartEvaluatingMessage) {
                                try {
                                    JSONObject json = new JSONObject();
                                    JSONObject content = new JSONObject();
                                    content.put("inteveral", System.currentTimeMillis());
                                    json.put("api", "recordStartTime");
                                    json.put("content", content);
                                    onSendMessage(json.toString());

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            } else if ("1".equals(recorder)) {
//                                onSendMessage(message.toString());
                            } else {
                                JSONObject object = new JSONObject();
                                JSONObject reson = new JSONObject();
                                try {
                                    reson.put("reson", "服务异常，请重试");
                                    object.put("api", "cancelEvaluating");
                                    object.put("content", reson);
                                    onSendMessage(object.toString());
                                    if (wavRecorder != null) {
                                        wavRecorder.stopRecording();
                                    }
                                } catch (JSONException e2) {
                                    e2.printStackTrace();
                                }
                            }
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            JSONObject object = new JSONObject();
                            JSONObject reson = new JSONObject();
                            try {
                                reson.put("reson", "录制错误，请重试");
                                object.put("api", "cancelEvaluating");
                                object.put("content", reson);
                                onSendMessage(object.toString());
                                if (wavRecorder != null) {
                                    wavRecorder.stopRecording();
                                }
                            } catch (JSONException e2) {
                                e2.printStackTrace();
                            }
                        }

                        @Override
                        public void onComplete() {

                        }
                    });


        }
    }

    /**
     * 结束录音
     *
     * @param message
     */
    @Override
    public void endRecording(JSONObject message) {
        if (wavRecorder == null) {
            return;
        }
        wavRecorder.stopRecording();
        if (webSocketClient != null) {
            webSocketClient.close();
        }
        onSendMessage(message.toString());
    }


    @Override
    public void keepScreenLongLight(JSONObject message) {
        onSendMessage(message.toString());
        isWiredHeadsetOn = true;
        if (webSocketClient == null) {
            new RxPermissions(this)
                    .request(Manifest.permission.RECORD_AUDIO)
                    .subscribe(permission -> {
                        if (permission) {
                            startWebSocketClient(message);
                        } else {
                            DialogUtil.showInCenter(getChildFragmentManager(), com.cooleshow.base.R.layout.accompany_permissions_popu, (holder, dialog) -> {
                                TextView tvTitle = holder.getView(com.cooleshow.base.R.id.tv_title);
                                TextView tvContent = holder.getView(com.cooleshow.base.R.id.tv_content);
                                TextView btncancel = holder.getView(com.cooleshow.base.R.id.btn_cancel);
                                TextView btnCommit = holder.getView(com.cooleshow.base.R.id.btn_commit);
                                tvTitle.setText("提示");
                                tvContent.setText("请开启麦克风访问权限");
                                btncancel.setOnClickListener(view1 -> {

                                    dialog.dismiss();

                                });
                                btnCommit.setOnClickListener(view1 -> {
                                    PermissionUtils.toSelfSetting(getContext());
                                    dialog.dismiss();
                                });
                            });
                        }
                    });
        }
    }

    boolean isSoundCheckStartTime = false;

    /**
     * 开始校音
     *
     * @param message
     */
    @Override
    public void startSoundCheck(JSONObject message) {
        //开录制 实时把给后台传音频数据
        onSendMessage(message.toString());
        isSoundCheckStartTime = true;
        if (webSocketClient != null && webSocketClient.isOpen()) {
            try {
                JSONObject jsonObject2 = new JSONObject();
                JSONObject headerObject2 = new JSONObject();
                headerObject2.put("commond", "start");
                headerObject2.put("type", "PITCH_DETECTION");
                headerObject2.put("status", 200);
                jsonObject2.put("header", headerObject2);
                webSocketClient.send(jsonObject2.toString());
            } catch (Exception e) {

            }
        }

        if (wavRecorder != null) {
            wavRecorder.stopRecording();
            FileUtils.deleteFile(getVoicePath());
            wavRecorder.startRecording(getContext());
        } else {
            Observable.create((ObservableOnSubscribe<String>) emitter -> {
                wavRecorder = MsRecorder.wav(
                        new File(getVoicePath()),
                        new AudioRecordConfig(),
                        // AudioRecordConfig(MediaRecorder.AudioSource.MIC, AudioFormat.ENCODING_PCM_16BIT, AudioFormat.CHANNEL_IN_MONO, 44100),
                        new PullTransport.Default().setOnAudioChunkPulledListener(new PullTransport.OnAudioChunkPulledListener() {
                            @Override
                            public void onAudioChunkPulled(AudioChunk audioChunk) {
                                if (webSocketClient != null && webSocketClient.isOpen()) {
                                    webSocketClient.send(audioChunk.toBytes());
                                    if (isSoundCheckStartTime) {
                                        isSoundCheckStartTime = false;
                                        emitter.onNext("-2");
                                    }
                                } else {
                                    emitter.onNext("-1");
                                }
                            }
                        }));
                if (wavRecorder != null) {
                    wavRecorder.startRecording(getContext());
                }
                emitter.onNext("1");
            }).subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<String>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {
                        }

                        @Override
                        public void onNext(@NonNull String recorder) {
                            if ("-2".equals(recorder)) {
                                try {
                                    JSONObject json = new JSONObject();
                                    JSONObject content = new JSONObject();
                                    content.put("inteveral", System.currentTimeMillis());
                                    json.put("api", "recordStartTime");
                                    json.put("content", content);
                                    onSendMessage(json.toString());

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            } else if ("1".equals(recorder)) {
//                                onSendMessage(message.toString());
                            } else {
                                JSONObject object = new JSONObject();
                                JSONObject reson = new JSONObject();
                                try {
                                    reson.put("reson", "服务异常，请重试");
                                    object.put("api", "cancelEvaluating");
                                    object.put("content", reson);
                                    onSendMessage(object.toString());
                                    if (wavRecorder != null) {
                                        wavRecorder.stopRecording();
                                    }
                                } catch (JSONException e2) {
                                    e2.printStackTrace();
                                }
                            }
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            JSONObject object = new JSONObject();
                            JSONObject reson = new JSONObject();
                            try {
                                reson.put("reson", "录制错误，请重试");
                                object.put("api", "cancelEvaluating");
                                object.put("content", reson);
                                onSendMessage(object.toString());
                                if (wavRecorder != null) {
                                    wavRecorder.stopRecording();
                                }
                            } catch (JSONException e2) {
                                e2.printStackTrace();
                            }
                        }

                        @Override
                        public void onComplete() {
                        }
                    });


        }
    }

    /**
     * 结束校音
     *
     * @param message
     */
    @Override
    public void endSoundCheck(JSONObject message) {
        //结束校音  校音结束 这个就是结束给后台传音频 停止录音
        onSendMessage(message.toString());
        if (wavRecorder == null) {
            return;
        }
        wavRecorder.stopRecording();
        wavRecorder = null;

    }

    // 录音文件存储名称
    private String getVoicePath() {
        return FileUtils.getCacheDir(getContext()) + File.separator + "wav-accompany" + ".wav";
    }

    /**
     * 结束评测
     *
     * @param jsonObject
     */
    @Override
    public void endEvaluating(JSONObject jsonObject) {
        if (wavRecorder == null) {
            return;
        }
        wavRecorder.stopRecording();
        wavRecorder = null;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (webSocketClient != null && webSocketClient.isOpen()) {
                    try {
                        JSONObject jsonObject = new JSONObject();
                        JSONObject headerObject = new JSONObject();
                        headerObject.put("commond", "recordEnd");
                        headerObject.put("type", "SOUND_COMPARE");
                        headerObject.put("status", 200);
                        jsonObject.put("header", headerObject);
                        webSocketClient.send(jsonObject.toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                onSendMessage(jsonObject.toString());
            }
        }, 1000);

//        Map<String, RequestBody> data = new HashMap<>();
//        try {
//            JSONObject content = jsonObject.getJSONObject("content");
//            data.put("musicScoreId", RequestBodyUtil.convertToRequestBody(content.getString("musicScoreId")));
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        presenter.soundCompare(RequestBodyUtil.filesToMultipartBodyParts(new File(getVoicePath()), "record", "audio/wav"), data, jsonObject);
    }

    /**
     * 取消评测
     */
    @Override
    public void cancelEvaluating() {
        if (wavRecorder == null) {
            return;
        }
        wavRecorder.stopRecording();
        FileUtils.deleteFile(getVoicePath());
    }

    /**
     * 恢复录音
     *
     * @param jsonObject
     */
    @Override
    public void resumeRecording(JSONObject jsonObject) {
        if (wavRecorder != null) {
            wavRecorder.resumeRecording(getContext());
            onSendMessage(jsonObject.toString());
        }
    }

    /**
     * 暂停
     *
     * @param jsonObject
     */
    @Override
    public void pauseRecording(JSONObject jsonObject) {
        if (wavRecorder != null) {
            wavRecorder.pauseRecording();
            onSendMessage(jsonObject.toString());
        }
    }

    /**
     * 检测 耳机或者其他设备
     *
     * @param jsonObject
     */
    @SuppressLint("CheckResult")
    @Override
    public void isWiredHeadsetOn(JSONObject jsonObject) {


        try {
            JSONObject content = jsonObject.getJSONObject("content");
            content.put("checkIsWired", !TextUtils.isEmpty(checkType()));
            content.put("type", checkType());
            onSendMessage(jsonObject.toString());

            if (webSocketClient != null) {
                if (webSocketClient.getReadyState() == ReadyState.NOT_YET_CONNECTED) {
                    if (webSocketClient.isClosed()) {
                        webSocketClient.reconnectBlocking();
                    } else {
                        webSocketClient.connectBlocking();
                    }
                } else if (webSocketClient.getReadyState() == ReadyState.CLOSED) {
                    webSocketClient.reconnectBlocking();
                }
            } else {
                startWebSocketClient(jsonObject);
            }

        } catch (JSONException | InterruptedException e) {
            e.printStackTrace();
        }


    }

    @Override
    public void proxyMessage(JSONObject jsonObject) {
        if (webSocketClient != null && webSocketClient.isOpen()) {
            try {
                JSONObject json = new JSONObject();
                JSONObject headerObject = new JSONObject();
                headerObject.put("commond", "proxyMessage");
                json.put("header", headerObject);
                json.put("body", jsonObject.getJSONObject("content"));
                webSocketClient.send(json.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void proxyServiceMessage(JSONObject mesage) {
        // 直接把H5那边返回的 content转成string 给socket服务
        try {
            JSONObject content = null;
            content = mesage.getJSONObject("content");
            String type = content.getJSONObject("header").getString("type");
            if ("SOUND_CHECK".equals(type)) {
                return;
            } else {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (webSocketClient != null && webSocketClient.isOpen()) {
                            try {
                                JSONObject content = null;
                                content = mesage.getJSONObject("content");
                                webSocketClient.send(content.toString());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        onSendMessage(mesage.toString());
                    }
                }, 1000);
            }
        } catch (JSONException e) {
        }

    }

    /**
     * 打开相册
     *
     * @param message
     */
    @Override
    public void openCamera(JSONObject message) {
        new RxPermissions(this)
                .request(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(permission -> {
                    if (permission) {
                        if (onAccompanyListener != null)
                            onAccompanyListener.openCamera();
                        onSendMessage(message.toString());
                    } else {
                        try {
                            JSONObject content = message.getJSONObject("content");
                            content.put("reson", "没有摄像头，麦克风，储存权限");
                            onSendMessage(message.toString());
                            isSendStartEvaluatingMessage = false;
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        DialogUtil.showInCenter(getChildFragmentManager(), com.cooleshow.base.R.layout.accompany_permissions_popu, (holder, dialog) -> {
                            TextView tvTitle = holder.getView(com.cooleshow.base.R.id.tv_title);
                            TextView tvContent = holder.getView(com.cooleshow.base.R.id.tv_content);
                            TextView btncancel = holder.getView(com.cooleshow.base.R.id.btn_cancel);
                            TextView btnCommit = holder.getView(com.cooleshow.base.R.id.btn_commit);
                            tvTitle.setText("提示");
                            tvContent.setText("请开启摄像头、麦克风、储存访问权限");
                            btncancel.setOnClickListener(view1 -> {

                                dialog.dismiss();

                            });
                            btnCommit.setOnClickListener(view1 -> {
                                PermissionUtils.toSelfSetting(getContext());
                                dialog.dismiss();
                            });
                        });
                    }
                });

    }

    @Override
    public void closeCamera(JSONObject jsonObject) {
        if (onAccompanyListener != null) {
            onAccompanyListener.closeCamera();
            onSendMessage(jsonObject.toString());
        }
    }

    @Override
    public void startCapture(JSONObject message) {
        new RxPermissions(this)
                .request(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(permission -> {
                    if (permission) {
                        if (onAccompanyListener != null) {
                            onAccompanyListener.startCapture();
                            onSendMessage(message.toString());
                        }
                    } else {
                        try {
                            JSONObject content = message.getJSONObject("content");
                            content.put("reson", "没有摄像头，麦克风，储存权限");
                            onSendMessage(message.toString());
                            isSendStartEvaluatingMessage = false;
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        DialogUtil.showInCenter(getChildFragmentManager(), com.cooleshow.base.R.layout.accompany_permissions_popu, (holder, dialog) -> {
                            TextView tvContent = holder.getView(com.cooleshow.base.R.id.tv_content);
                            TextView btncancel = holder.getView(com.cooleshow.base.R.id.btn_cancel);
                            TextView btnCommit = holder.getView(com.cooleshow.base.R.id.btn_commit);
                            tvContent.setText("请开启摄像头、麦克风、储存访问权限");
                            btncancel.setOnClickListener(view1 -> {

                                dialog.dismiss();
                            });
                            btnCommit.setOnClickListener(view1 -> {
                                PermissionUtils.toSelfSetting(getContext());
                                dialog.dismiss();
                            });
                        });
                    }
                });

    }

    @Override
    public void endCapture(JSONObject jsonObject) {
        if (onAccompanyListener != null)
            onAccompanyListener.endCapture();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                onSendMessage(jsonObject.toString());
            }
        }, 1500);
    }

    private String checkType() {
        AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            AudioDeviceInfo[] devices = audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS);
            for (AudioDeviceInfo device : devices) {
                int deviceType = device.getType();
                if (deviceType == AudioDeviceInfo.TYPE_WIRED_HEADSET || deviceType == AudioDeviceInfo.TYPE_WIRED_HEADPHONES) {
                    return "有线耳机";
                }
                if (deviceType == AudioDeviceInfo.TYPE_BLUETOOTH_A2DP
                        || deviceType == AudioDeviceInfo.TYPE_BLUETOOTH_SCO) {
                    return "蓝牙耳机";
                }
                if (deviceType == AudioDeviceInfo.TYPE_BUILTIN_EARPIECE) {
                    if (Constants.HEADSET_PLUE_TAG.isEmpty()) {
                        return null;
                    } else {
                        return "有线耳机";
                    }
                }
            }
        } else {
            if (audioManager.isWiredHeadsetOn()) {
                return "有线耳机";
            }
            if (audioManager.isBluetoothScoOn() || audioManager.isBluetoothA2dpOn()) {
                return "蓝牙耳机";
            }
        }
        return null;
    }

    @Override
    public void videoUpdate(JSONObject jsonObject) {
        if (onAccompanyListener != null)
            onAccompanyListener.videoUpdate(jsonObject);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                onSendMessage(jsonObject.toString());
            }
        }, 1500);
    }

    private class WebClient extends WebViewClient {
        //页面开始载入时调用
        private int webViewPreviousState;
        private final int PAGE_STARTED = 0x1;
        private final int PAGE_REDIRECTED = 0x2;

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            webViewPreviousState = PAGE_STARTED;
        }

        //页面载入结束时调用
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (webViewPreviousState == PAGE_STARTED) {
                if (listener != null) {
                    listener.onPageFinished();
                }
            }
        }

        //截取url请求，在当前视图加载，避免在跳转到自带浏览器
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String request) {
            webViewPreviousState = PAGE_REDIRECTED;
            view.loadUrl(request);
            return true;
        }

        //处理报错信息
        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }
    }


    public void sendMessage(String message) {
        webView.evaluateJavascript("postMessage('" + message + "','*')", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String s) {
            }
        });
    }


    //注册蓝牙连接状态
    public void registRecevier() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_HEADSET_PLUG);
        intentFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
        mContext.registerReceiver(new HeadsetPlugReceiver(new HeadsetPlugListener() {
            @Override
            public void onHeadsetPlug(boolean isPlug, String type) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("api", "listenerWiredStatus");
                            JSONObject content = new JSONObject();
                            content.put("checkIsWired", isPlug);
                            content.put("type", type);
                            jsonObject.put("content", content);
                            onSendMessage(jsonObject.toString());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }), intentFilter);
    }

    @Override
    public void onPause() {
        super.onPause();

        if (webView != null) {
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("api", "suspendPlay");
                onSendMessage(jsonObject.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != webView) {
            webView.destroy();
        }
        if (wavRecorder != null) {
            wavRecorder.stopRecording();
        }
        if (webSocketClient != null) {
            webSocketClient.close();
        }
        EventBus.getDefault().unregister(this);
        MidiPlayerUtils.getInstance().stopPlay();
        UMShareAPI.get(mContext).release();

    }

    @Override
    public void onStop() {
        super.onStop();
        isReady = true;
        if (null != soundpool) {
            soundpool.release();
        }
        loopHandler.removeMessages(1);
        //取消评测
        if (MidiPlayerUtils.getInstance().isPlaying()) {
            MidiPlayerUtils.getInstance().stopPlay();
            try {
                JSONObject content = new JSONObject();
                content.put("songID", midiSongId);
                JSONObject json = new JSONObject();
                json.put("api", "cloudplayed");
                json.put("content", content);
                onSendMessage(json.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public onListener onAccompanyListener;

    public void setOnAccompanyListener(onListener onAccompanyListener) {
        this.onAccompanyListener = onAccompanyListener;
    }

    public interface onListener {
        void setStatusBarTextColor(boolean statusBarTextColor);

        void openCamera();


        void closeCamera();

        void startCapture();

        void endCapture();


        void videoUpdate(JSONObject jsonObject);

    }

    public WebViewListener listener;

    public void setOnWebViewListener(WebViewListener listener) {
        this.listener = listener;
    }

    public interface WebViewListener {
        void onPageFinished();

    }


    @Override
    public void shareAchievements(JSONObject message) {
        JSONObject content = null;
        try {
            content = message.getJSONObject("content");

            String shareTitle = content.getString("title");
            String shareDesc = content.getString("desc");
            if ("video".equals(content.getString("type"))) {
                String videoUrl = content.getString("video");
                /*增加自定义按钮的分享面板*/
                mShareAction = new ShareAction(getActivity()).setDisplayList(
                        SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.SINA)
                        .setShareboardclickCallback(new ShareBoardlistener() {
                            @Override
                            public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                                UMWeb video = new UMWeb(videoUrl);
                                video.setTitle(shareTitle);
                                video.setDescription(shareDesc.isEmpty() ? shareTitle : shareDesc);
                                new ShareAction(getActivity()).withMedia(video)
                                        .setPlatform(share_media)
                                        .setCallback(mShareListener)
                                        .share();

                            }
                        });
                mShareAction.open();
            } else {
                String imageBase64 = content.getString("image");
                /*增加自定义按钮的分享面板*/
                mShareAction = new ShareAction(getActivity()).setDisplayList(
                        SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.SINA)
                        .setShareboardclickCallback(new ShareBoardlistener() {
                            @Override
                            public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                                UMImage image = new UMImage(mContext, FileUtils.base64ToBitmap(imageBase64.split(",")[1]));//bitmap文件
                                image.setThumb(image);
                                image.compressStyle = UMImage.CompressStyle.SCALE;
                                new ShareAction(getActivity()).withMedia(image)
                                        .setPlatform(share_media)
                                        .setCallback(mShareListener)
                                        .share();

                            }
                        });
                mShareAction.open();
            }
        } catch (JSONException e) {

        }
    }


    private static class CustomShareListener implements UMShareListener {

        private WeakReference<AccompanyActivity> mActivity;

        private CustomShareListener(Activity activity) {
            mActivity = new WeakReference(activity);
        }

        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {

            if (platform.name().equals("WEIXIN_FAVORITE")) {
                ToastUtil.getInstance().showShort("收藏成功啦");
            } else {
                if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS
                        && platform != SHARE_MEDIA.EMAIL
                        && platform != SHARE_MEDIA.FLICKR
                        && platform != SHARE_MEDIA.FOURSQUARE
                        && platform != SHARE_MEDIA.TUMBLR
                        && platform != SHARE_MEDIA.POCKET
                        && platform != SHARE_MEDIA.PINTEREST

                        && platform != SHARE_MEDIA.INSTAGRAM
                        && platform != SHARE_MEDIA.GOOGLEPLUS
                        && platform != SHARE_MEDIA.YNOTE
                        && platform != SHARE_MEDIA.EVERNOTE) {
                    ToastUtil.getInstance().showShort("分享成功啦");
                }

            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS
                    && platform != SHARE_MEDIA.EMAIL
                    && platform != SHARE_MEDIA.FLICKR
                    && platform != SHARE_MEDIA.FOURSQUARE
                    && platform != SHARE_MEDIA.TUMBLR
                    && platform != SHARE_MEDIA.POCKET
                    && platform != SHARE_MEDIA.PINTEREST

                    && platform != SHARE_MEDIA.INSTAGRAM
                    && platform != SHARE_MEDIA.GOOGLEPLUS
                    && platform != SHARE_MEDIA.YNOTE
                    && platform != SHARE_MEDIA.EVERNOTE) {
                ToastUtil.getInstance().showShort("分享失败啦");

            }

        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            ToastUtil.getInstance().showShort("分享取消了");
        }
    }

    @Override
    public void onConfigurationChanged(@androidx.annotation.NonNull @NotNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (mShareAction != null) {
            mShareAction.close();
        }

    }

    /**
     * 分段上传
     *
     * @param message
     */
    @Override
    public void measureStart(JSONObject message) {

    }

    /**
     * 结束分段
     *
     * @param message
     */
    @Override
    public void allMeasureEnd(JSONObject message) {
    }

    /**
     * h5传递的midi文件地址
     */
    private String midiFilePath = null;
    /**
     * 初始速度
     */
    private int midiFileOriginalSpeed = 120;
    /**
     * 设定后速度，默认与初始速度一致
     */
    private int midiFileSpeed = 120;
    /**
     * 全曲时长，用以同步播放进度的基数
     */
    private long midiFileDuration = 0;

    /**
     * 回报进度间隔
     */
    int processInterval = 16;
    /**
     * 曲目id
     */
    private String midiSongId = null;

    private int hertz = 440;

    private SoundPool soundpool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
    private boolean isReady = true;

    @Override
    public void cloudDetail(JSONObject message) {
        try {
            JSONObject obj = message.optJSONObject("content");
            String midiFile = obj.optString("midi");
            midiFileOriginalSpeed = obj.optInt("originalSpeed", 120);
            midiFileSpeed = midiFileOriginalSpeed;
            midiFileDuration = obj.optLong("duration");
            processInterval = obj.optInt("interval", 16);
            if (TextUtils.isEmpty(midiFile)) {
                ToastUtil.getInstance().showShort("文件异常");
                return;
            }
            new RxPermissions(this)
                    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                    .subscribe(permission -> {
                        if (permission) {
                            try {
                                String type = midiFile.substring(midiFile.lastIndexOf(".") + 1);
                                if (TextUtils.isEmpty(type)) {
                                    ToastUtil.getInstance().showShort("文件异常");
                                    return;
                                }
                                String path = FileUtils.getPublicDirectory("file");
                                String name = hashKeyForDisk(midiFile) + "." + type;
                                File file = new File(path + "/" + name);
                                if (file.exists() && file.length() > 0) {
                                    //本地文件存在
                                    midiFilePath = file.getAbsolutePath();
                                    MidiPlayerUtils.getInstance().init(getActivity().getApplication(), midiFilePath);
                                    double tempDuration = MidiPlayerUtils.getInstance().getTotalLength2Second();
                                    if (Math.abs(midiFileDuration - tempDuration * 1000) > 2000) {
                                        midiFileDuration = (long) (tempDuration * 1000);
                                    }
                                    message.optJSONObject("content").put("midiDuration", midiFileDuration);
                                    onSendMessage(message.toString());
                                } else {
                                    RetrofitClientNoToken.getInstance().getRetrofit().create(APIService.class)
                                            .downloadFileWithFixedUrl(midiFile)
                                            .subscribeOn(Schedulers.io())
                                            .observeOn(Schedulers.io())
                                            .subscribeWith(new Observer<ResponseBody>() {
                                                @Override
                                                public void onSubscribe(Disposable d) {

                                                }

                                                @Override
                                                public void onNext(ResponseBody response) {
                                                    if (FileUtils.writeFileToSDCard(response, path, name)) {
                                                        runOnUiThread(() -> {
                                                            midiFilePath = path + File.separator + name;
                                                            MidiPlayerUtils.getInstance().init(getActivity().getApplication(), midiFilePath);
                                                            double tempDuration = MidiPlayerUtils.getInstance().getTotalLength2Second();
                                                            if (Math.abs(midiFileDuration - tempDuration * 1000) > 2000) {
                                                                midiFileDuration = (long) (tempDuration * 1000);
                                                            }
                                                            try {
                                                                message.optJSONObject("content").put("midiDuration", midiFileDuration);
                                                            } catch (JSONException e) {
                                                                e.printStackTrace();
                                                            } finally {
                                                                onSendMessage(message.toString());
                                                            }

                                                        });
                                                    } else {
                                                        runOnUiThread(() -> {
                                                            ToastUtil.getInstance().showShort("获取文件失败");
                                                            midiFilePath = null;
                                                            onSendMessage(message.toString());
                                                        });
                                                    }
                                                }

                                                @Override
                                                public void onError(Throwable e) {
                                                    runOnUiThread(() -> {
                                                        hideLoading();
                                                        ToastUtil.getInstance().showShort("文件异常");
                                                        midiFilePath = null;
                                                        onSendMessage(message.toString());
                                                    });
                                                }

                                                @Override
                                                public void onComplete() {

                                                }
                                            });
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            DialogUtil.showInCenter(getChildFragmentManager(), com.cooleshow.base.R.layout.accompany_permissions_popu, (holder, dialog) -> {
                                TextView tvContent = holder.getView(com.cooleshow.base.R.id.tv_content);
                                TextView btncancel = holder.getView(com.cooleshow.base.R.id.btn_cancel);
                                TextView btnCommit = holder.getView(com.cooleshow.base.R.id.btn_commit);
                                tvContent.setText("请开启储存访问权限");
                                btncancel.setOnClickListener(view1 -> {
                                    dialog.dismiss();
                                });
                                btnCommit.setOnClickListener(view1 -> {
                                    PermissionUtils.toSelfSetting(getContext());
                                    dialog.dismiss();
                                });
                            });
                        }
                    });
        } catch (Exception e) {

        }
    }

    private String hashKeyForDisk(String key) {
        String cacheKey;
        try {
            final MessageDigest mDigest = MessageDigest.getInstance("MD5");
            mDigest.update(key.getBytes());
            cacheKey = bytesToHexString(mDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            cacheKey = String.valueOf(key.hashCode());
        }
        return cacheKey;
    }

    private String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    @Override
    public void cloudPlay(JSONObject message) {
        try {
            JSONObject obj = message.optJSONObject("content");
            midiFileSpeed = obj.optInt("speed", 120);
            midiSongId = obj.optString("songID");
            hertz = obj.optInt("hertz", 440);
            if (MidiPlayerUtils.getInstance().isPause()) {
                MidiPlayerUtils.getInstance().resumePlay();
                loopHandler.sendEmptyMessage(1);
                onSendMessage(message.toString());
            } else {
                loopHandler.removeMessages(1);
                MidiPlayerUtils.getInstance().playSound(
                        (float) midiFileSpeed / (float) midiFileOriginalSpeed,
                        hertz,
                        fp -> {
                            onSendMessage(message.toString());
                            loopHandler.sendEmptyMessage(1);
                        },
                        fp -> {
                            loopHandler.removeMessages(1);
                            try {
                                JSONObject content = new JSONObject();
                                content.put("songID", obj.optString("songID"));
                                JSONObject json = new JSONObject();
                                json.put("api", "cloudplayed");
                                json.put("content", content);
                                onSendMessage(json.toString());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        });
                onSendMessage(message.toString());
                loopHandler.sendEmptyMessage(1);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void cloudSuspend(JSONObject message) {
        try {
            MidiPlayerUtils.getInstance().pausePlay();
            loopHandler.removeMessages(1);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                message.optJSONObject("content").put("currentTime", MidiPlayerUtils.getInstance().getCurrentPosition() * (midiFileDuration == 0 ? MidiPlayerUtils.getInstance().midiTotalTime : midiFileDuration) / MidiPlayerUtils.getInstance().getTotalLength());
            } catch (Exception e) {
                e.printStackTrace();
            }
            onSendMessage(message.toString());
        }


    }

    @Override
    public void cloudSetCurrentTime(JSONObject message) {
        try {
            MidiPlayerUtils.getInstance().seekTo(message.optJSONObject("content").optInt("currentTime") * MidiPlayerUtils.getInstance().getTotalLength() / midiFileDuration);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            onSendMessage(message.toString());
        }
    }

    @Override
    public void cloudChangeSpeed(JSONObject message) {
        try {
            JSONObject obj = message.optJSONObject("content");
            midiFileSpeed = obj.optInt("speed", 120);
            MidiPlayerUtils.getInstance().setSpeed((float) midiFileSpeed / (float) midiFileOriginalSpeed);
        } catch (Exception e) {

        }
    }

    @Override
    public void cloudSwitch(JSONObject message) {
        try {
            JSONObject obj = message.optJSONObject("content");
            JSONArray array = obj.optJSONArray("parts");
            for (int i = 0; i < MidiPlayerUtils.getInstance().getMidiTracks().size(); i++) {
                MidiPlayerUtils.getInstance().setTrackVolume(i, 0.7f);
            }
            for (int i = 0; i < array.length(); i++) {
                MidiPlayerUtils.getInstance().setTrackVolumeByName(array.optString(i), 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void cloudVolume(JSONObject message) {

        try {
            JSONObject obj = message.optJSONObject("content");
            JSONArray array = obj.optJSONArray("parts");
            for (int i = 0; i < array.length(); i++) {
                MidiPlayerUtils.getInstance().setTrackVolumeByName(array.optJSONObject(i).optString("name"), (float) array.optJSONObject(i).optInt("volume", 70) / 100f);
            }
        } catch (Exception e) {
            e.printStackTrace();
            sendMessage(message.toString());
        } finally {
            for (int i = 0; i < MidiPlayerUtils.getInstance().getMidiTracks().size(); i++) {
                Log.i(TAG, "track " + i + " vol is " + MidiPlayerUtils.getInstance().getTrackVolume(i));
            }
        }
    }

    @Override
    public void cloudGetMediaStatus(JSONObject message) {
        try {
            if (MidiPlayerUtils.getInstance().isPlaying()) {
                message.optJSONObject("content").put("status", "play");
            } else if (MidiPlayerUtils.getInstance().isPause()) {
                message.optJSONObject("content").put("status", "suspend");
            } else if (MidiPlayerUtils.getInstance().isStop()) {
                message.optJSONObject("content").put("status", "suspend");
            } else {
                message.optJSONObject("content").put("status", "suspend");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sendMessage(message.toString());
        }
    }

    @Override
    public void cloudDestroy(JSONObject message) {
        try {
            MidiPlayerUtils.getInstance().stopPlay();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sendMessage(message.toString());
        }
    }

    @Override
    public void joinLiveRoom(String roomId, String teacherId) {

    }

    @Override
    public void joinChatGroup(String type, String id) {

    }


    public void selectAddress(String addressJson) {
        onSendMessage("'getAddress'," + addressJson);
    }

    @Override
    public void paymentOrder(String orderNo, String payChannel, String payInfo) {
        if (payChannel.equals("ali_app")) {
            if (!AppUtils.checkAliPayInstalled(getContext())) {
                sendPayResult(Constants.PAY_ERROR_BY_NOT_INSTALL);
                return;
            }
            String orderInfo = payInfo;
            final Runnable payRunnable = new Runnable() {
                @Override
                public void run() {
                    PayTask alipay = new PayTask(getActivity());
                    Map<String, String> result = alipay.payV2(orderInfo, true);
                    Log.i("msp", result.toString());

                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }
            };

            // 必须异步调用
            Thread payThread = new Thread(payRunnable);
            payThread.start();
        } else {
            //微信
            if (!api.isWXAppInstalled()) {
                sendPayResult(Constants.PAY_ERROR_BY_NOT_INSTALL);
                return;
            }
            Gson gson = new Gson();
            WeixinPayInfo weixinPayInfo = gson.fromJson(payInfo, WeixinPayInfo.class);
            PayReq req = new PayReq();
            req.appId = weixinPayInfo.getAppid();
            req.partnerId = weixinPayInfo.getPartnerid();
            req.prepayId = weixinPayInfo.getPrepayid();
            req.nonceStr = weixinPayInfo.getNoncestr();
            req.timeStamp = weixinPayInfo.getTimestamp();
            req.packageValue = weixinPayInfo.getPackageValue();
            req.sign = weixinPayInfo.getSign();

//                    req.extData			= "app data"; // optional
            //正在前往微信支付
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            goPay = true;
            api.sendReq(req);
        }
    }

    @Override
    public void savePicture(String base64, String uuid) {
        try {
            com.cooleshow.base.utils.FileUtils.saveBase64ImgToLocalFile(base64);
            sendSavePicCallBack("savePicture", "success",uuid);
        } catch (Exception e) {
            sendSavePicCallBack("savePicture", "fail",uuid);
            e.printStackTrace();
        }
    }

    private void sendSavePicCallBack(String api, String result,String uuid) {
        JSONObject jsonObject = new JSONObject();
        JSONObject contentJson = new JSONObject();
        try {
            jsonObject.put("api", api);
            contentJson.put("status", result);
            contentJson.put("uuid", uuid);
            jsonObject.put("content", contentJson);
            sendMessage(jsonObject.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean goPay = false;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void loadEventBus(WxPayResult payResult) {
        if (goPay) {
            if (payResult.resultCode == 0) {
                sendPayResult(Constants.PAY_SUCCESS);
            } else {
                sendPayResult(Constants.PAY_ERROR);
            }
            goPay = false;
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ToastUtil.getInstance().showShort("支付成功");
                        sendPayResult(Constants.PAY_SUCCESS);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastUtil.getInstance().showShort("支付失败" + resultStatus);
                        sendPayResult(Constants.PAY_ERROR);
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        sendPayResult(Constants.PAY_SUCCESS);
                    } else {
                        // 其他状态值则为授权失败
                        sendPayResult(Constants.PAY_ERROR);
                    }
                    break;
                }
                default:
                    break;
            }
        }

    };


    @Override
    public void cloudMetronome(JSONObject message) {
        try {
            JSONObject obj = message.optJSONObject("content");
            int repeat = obj.optInt("repeat", 1);
            int denominator = obj.optInt("denominator", 4);
            int numerator = obj.optInt("repeat", 4);
            if (soundpool != null) {
                soundpool.release();
                soundpool = null;
            }
            isReady = false;
            HashMap<Integer, Integer> map = new HashMap<>();
            if (numerator == 2) {
                soundpool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
                map.put(0, soundpool.load(getContext(), com.cooleshow.base.R.raw.midstrong, 1));
                map.put(1, soundpool.load(getContext(), com.cooleshow.base.R.raw.feeble, 1));
            } else if (numerator == 3) {
                soundpool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);
                map.put(0, soundpool.load(getContext(), com.cooleshow.base.R.raw.midstrong, 1));
                map.put(1, soundpool.load(getContext(), com.cooleshow.base.R.raw.feeble, 1));
                map.put(2, soundpool.load(getContext(), com.cooleshow.base.R.raw.feeble, 1));
            } else if (numerator == 6) {
                soundpool = new SoundPool(6, AudioManager.STREAM_MUSIC, 0);
                map.put(0, soundpool.load(getContext(), com.cooleshow.base.R.raw.midstrong, 1));
                map.put(1, soundpool.load(getContext(), com.cooleshow.base.R.raw.feeble, 1));
                map.put(2, soundpool.load(getContext(), com.cooleshow.base.R.raw.feeble, 1));
                map.put(3, soundpool.load(getContext(), com.cooleshow.base.R.raw.midstrong, 1));
                map.put(4, soundpool.load(getContext(), com.cooleshow.base.R.raw.feeble, 1));
                map.put(5, soundpool.load(getContext(), com.cooleshow.base.R.raw.feeble, 1));
            } else {
                soundpool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
                map.put(0, soundpool.load(getContext(), com.cooleshow.base.R.raw.midstrong, 1));
                map.put(1, soundpool.load(getContext(), com.cooleshow.base.R.raw.feeble, 1));
                map.put(2, soundpool.load(getContext(), com.cooleshow.base.R.raw.feeble, 1));
                map.put(3, soundpool.load(getContext(), com.cooleshow.base.R.raw.feeble, 1));
            }
            int speed;
            if (denominator == 4) {
                if (midiFileSpeed > 0) {
                    speed = midiFileSpeed;
                } else {
                    speed = 60;
                }
            } else {
                if (midiFileSpeed * 2 > 0) {
                    speed = midiFileSpeed * 2;
                } else {
                    speed = 60;
                }
            }
            long sleepTime = (long) (60000.0 / (speed));
            showCountDownDialog(map.size(), message);
            new Thread(() -> {
                playPreSound(map, sleepTime, repeat);
                //播放完成开始录音
                runOnUiThread(() -> {
                    if (null != preCountDialog) {
                        preCountDialog.dismiss();
                    }
                    if (soundpool != null) {
                        try {
                            message.optJSONObject("content").put("status", "finish");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        onSendMessage(message.toString());
                    }
                });
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private CommonDialog preCountDialog;
    private ImageView iv1;
    private ImageView iv2;
    private ImageView iv3;
    private ImageView iv4;
    private ImageView iv5;
    private ImageView iv6;

    private void showCountDownDialog(int count, JSONObject message) {
        //弹出预备拍
        preCountDialog = CommonDialog.init().setLayoutId(com.cooleshow.base.R.layout.dialog_student_precount);
        preCountDialog.setConvertListener(new ViewConvertListener() {
            @Override
            public void convertView(ViewHolder holder, BaseDialog dialog) {
                if (count == 2) {
                    iv1 = holder.getView(com.cooleshow.base.R.id.iv_3);
                    iv2 = holder.getView(com.cooleshow.base.R.id.iv_4);
                    iv3 = holder.getView(com.cooleshow.base.R.id.iv_1);
                    iv4 = holder.getView(com.cooleshow.base.R.id.iv_2);
                    iv5 = holder.getView(com.cooleshow.base.R.id.iv_5);
                    iv6 = holder.getView(com.cooleshow.base.R.id.iv_6);
                    iv3.setVisibility(View.INVISIBLE);
                    iv4.setVisibility(View.INVISIBLE);
                    iv5.setVisibility(View.INVISIBLE);
                    iv6.setVisibility(View.INVISIBLE);
                } else if (count == 3) {
                    iv1 = holder.getView(com.cooleshow.base.R.id.iv_3);
                    iv2 = holder.getView(com.cooleshow.base.R.id.iv_4);
                    iv3 = holder.getView(com.cooleshow.base.R.id.iv_5);
                    iv4 = holder.getView(com.cooleshow.base.R.id.iv_2);
                    iv5 = holder.getView(com.cooleshow.base.R.id.iv_1);
                    iv6 = holder.getView(com.cooleshow.base.R.id.iv_6);
                    iv4.setVisibility(View.INVISIBLE);
                    iv5.setVisibility(View.INVISIBLE);
                    iv6.setVisibility(View.INVISIBLE);
                } else if (count == 4) {
                    iv1 = holder.getView(com.cooleshow.base.R.id.iv_2);
                    iv2 = holder.getView(com.cooleshow.base.R.id.iv_3);
                    iv3 = holder.getView(com.cooleshow.base.R.id.iv_4);
                    iv4 = holder.getView(com.cooleshow.base.R.id.iv_5);
                    iv5 = holder.getView(com.cooleshow.base.R.id.iv_1);
                    iv6 = holder.getView(com.cooleshow.base.R.id.iv_6);
                    iv5.setVisibility(View.INVISIBLE);
                    iv6.setVisibility(View.INVISIBLE);
                }
                iv1.setImageResource(com.cooleshow.base.R.drawable.bg_play_metronome_gray_dots_shape);
                iv2.setImageResource(com.cooleshow.base.R.drawable.bg_play_metronome_gray_dots_shape);
                iv3.setImageResource(com.cooleshow.base.R.drawable.bg_play_metronome_gray_dots_shape);
                iv4.setImageResource(com.cooleshow.base.R.drawable.bg_play_metronome_gray_dots_shape);
                iv5.setImageResource(com.cooleshow.base.R.drawable.bg_play_metronome_gray_dots_shape);
                iv6.setImageResource(com.cooleshow.base.R.drawable.bg_play_metronome_gray_dots_shape);
                ImageView iv_dialog_student_precount = holder.getView(com.cooleshow.base.R.id.iv_dialog_student_precount);
                iv_dialog_student_precount.setOnClickListener(v -> {
                    dialog.dismiss();
                    if (soundpool != null) {
                        soundpool.release();
                        soundpool = null;
                    }
                    try {
                        message.optJSONObject("content").put("status", "cancel");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    onSendMessage(message.toString());
                });
            }
        })
                .setDimAmount(0.6f)
                .setOutCancel(true)
                .setGravity(Gravity.CENTER)
                .show(getChildFragmentManager());
    }

    private void changeImageState(int size, int now) {
        if (null != preCountDialog && preCountDialog.isVisible()) {
            int resId = -1;
            if (now < size) {
                resId = com.cooleshow.base.R.drawable.bg_play_metronome_white_dots_shape;
            }
            now = now % size;
            if (now == 0) {
                iv1.setImageResource(com.cooleshow.base.R.drawable.bg_play_metronome_green_dots_shape);
            } else if (now == 1) {
                iv2.setImageResource(resId);
            } else if (now == 2) {
                iv3.setImageResource(resId);
            } else if (now == 3) {
                iv4.setImageResource(resId);
            } else if (now == 4) {
                iv5.setImageResource(resId);
            } else if (now == 5) {
                iv6.setImageResource(resId);
            }
        }
    }

    private void playPreSound(HashMap<Integer, Integer> map, long sleepTime, int repeat) {
        SystemClock.sleep(500);
        repeat--;
        for (int i = 0; i < map.size(); i++) {
            if (!isReady) {
                SystemClock.sleep(sleepTime);
                if (soundpool != null) {
                    soundpool.play(map.get(i), 1, 1, 0, 0, 1);
                    int finalI = i;
                    runOnUiThread(() -> changeImageState(map.size(), finalI));
                } else {
                    return;
                }
            }
        }
        if (repeat > 0) {
            playPreSound(map, sleepTime, repeat);
        } else {
            SystemClock.sleep(sleepTime);
        }
    }


    private Handler loopHandler = new Handler() {
        @Override
        public void handleMessage(@NotNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                checkPrecess();
                loopHandler.removeMessages(1);
                loopHandler.sendEmptyMessageDelayed(1, processInterval);
            }
        }
    };

    private void checkPrecess() {
        if (!MidiPlayerUtils.getInstance().isPlaying()) {
            return;
        }
        long dur = MidiPlayerUtils.getInstance().getCurrentPosition() * (midiFileDuration == 0 ? MidiPlayerUtils.getInstance().midiTotalTime : midiFileDuration) / MidiPlayerUtils.getInstance().getTotalLength();
        try {
            if (TextUtils.isEmpty(midiSongId)) {
                return;
            }
            JSONObject content = new JSONObject();
            content.put("currentTime", dur);
            content.put("songID", midiSongId);
            JSONObject json = new JSONObject();
            json.put("api", "cloudTimeUpdae");
            json.put("content", content);
            onSendMessage(json.toString());
        } catch (Exception e) {

        }

    }

    /**
     * 发送支付结果
     *
     * @param payResult
     */
    private void sendPayResult(int payResult) {
        JSONObject jsonObject = new JSONObject();
        JSONObject contentJson = new JSONObject();
        try {
            jsonObject.put("api", "paymentOperation");
            //支付成功
            if (payResult == Constants.PAY_SUCCESS) {
                contentJson.put("status", "success");
            }
            //支付失败
            if (payResult == Constants.PAY_ERROR) {
                contentJson.put("status", "error");
            }
            //支付未安装
            if (payResult == Constants.PAY_ERROR_BY_NOT_INSTALL) {
                contentJson.put("status", "fail");
            }
            //支付取消
            if (payResult == Constants.PAY_CANCEL) {
                contentJson.put("status", "cancel");
            }
            jsonObject.put("content", contentJson);
            onSendMessage(jsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}