package com.cooleshow.student.ui.main;

import static com.cooleshow.base.utils.ViewUtils.runOnUiThread;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.GeolocationPermissions;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
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.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.alipay.sdk.app.PayTask;
import com.cooleshow.base.BuildConfig;
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.ui.fragment.BaseMVPFragment;
import com.cooleshow.base.utils.AppUtils;
import com.cooleshow.base.utils.PermissionUtils;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.utils.ToastUtils;
import com.cooleshow.base.utils.UriUtils;
import com.cooleshow.base.utils.helper.QMUIStatusBarHelper;
import com.cooleshow.base.utils.helper.upload.UploadHelper;
import com.cooleshow.base.widgets.DialogUtil;
import com.cooleshow.student.App;
import com.cooleshow.student.R;
import com.cooleshow.student.api.APIService;
import com.cooleshow.student.bean.alipay.AuthResult;
import com.cooleshow.student.bean.alipay.PayResult;
import com.cooleshow.student.bean.weixinpay.WeixinPayInfo;
import com.cooleshow.student.databinding.FragmentMallBinding;
import com.cooleshow.student.presenter.main.ShopMallPresenter;
import com.cooleshow.student.ui.web.HtmlActivity;
import com.cooleshow.student.widgets.FileUtils;
import com.cooleshow.student.widgets.LollipopFixedWebView;
import com.cooleshow.student.widgets.helper.JsInterfaceUtils;
import com.cooleshow.usercenter.helper.UserHelper;
import com.daya.live_teaching.utils.GlideEngine;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
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.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.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * 创建日期：2022/6/9 9:21
 *
 * @author Ryan
 * 类说明：
 */
public class MallFragment extends BaseMVPFragment<FragmentMallBinding, ShopMallPresenter> implements JsInterfaceUtils.onGetMethodsListener {
    private static final int REQUEST_CODE_FILE_CHOOSER = 500;
    public static final String TAG = "HtmlActivity";
    private IWXAPI api;
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    ConstraintLayout headerBbarView;
    View view;
    View viewStatusbar;
    ImageView btnBack;
    ImageView btnClose;
    ImageView ivAction;
    TextView tvTitle;
    TextView tvAction;
    FrameLayout viewParent;
    FrameLayout mLayout;
    ProgressBar progressBar;
    RelativeLayout rl_activity_html;
    LinearLayout ll_activity_html;

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

    private void initViewLayout() {
        headerBbarView = mViewBinding.headerBarView;
        view = mViewBinding.view;
        viewStatusbar = mViewBinding.viewStatusbar;
        btnBack = mViewBinding.btnBack;
        btnClose = mViewBinding.btnClose;
        ivAction = mViewBinding.ivAction;
        tvTitle = mViewBinding.tvTitle;
        tvAction = mViewBinding.tvAction;
        viewParent = mViewBinding.viewParent;
        mLayout = mViewBinding.flVideo;
        progressBar = mViewBinding.progressBar;
        rl_activity_html = mViewBinding.rlActivityHtml;
        ll_activity_html = mViewBinding.llActivityHtml;
    }

    WebView webView;
    private String url;
    private String webViewUrl;
    //    private String  vipGroupId;
    private String content;
    //    private PayBean bean;
    private boolean isGoback;
    private String Authorization;
    private String authorization;
    private final int PORTRAIT_REQUEST_CODE = 1002;
    private final int ADD_ACCOMPANIMENT_CODE = 1003;
    private ShareAction mShareAction;
    int ivActionIcon = -1;
    int startType = -1;

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

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

    @Override
    protected void initData() {

    }

    @Override
    protected void initView(View rootView) {
        initViewLayout();

        url = WebConstants.TEACHER_SHOPMALL;
        headerBbarView.setVisibility(View.GONE);
        viewStatusbar.setVisibility(View.VISIBLE);
        try {
            if (Build.VERSION.SDK_INT >= 21 && Build.VERSION.SDK_INT < 23) {
                webView = new LollipopFixedWebView(getContext());
            } else {
                webView = new WebView(getContext());
            }
        } catch (Exception e) {

        }
        if (null == webView) {
            return;
        }
        viewParent.addView(webView, new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT));
        initWebView();
        JsInterfaceUtils jsInterfaceUtils = new JsInterfaceUtils(getActivity());
        jsInterfaceUtils.setOnItemClickListener(this);

        webView.addJavascriptInterface(jsInterfaceUtils, WebConstants.WEB_JS_INTERFACE);
        webView.setWebViewClient(new WebClient());
        webView.setWebChromeClient(new MyWebChromeClient());

        String userToken = UserHelper.getUserToken();
        Authorization = TextUtils.isEmpty(userToken) ? null : userToken;
        if (!TextUtils.isEmpty(Authorization)) {
            try {
                authorization = URLEncoder.encode(Authorization, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            boolean status = url.contains("?");
            if (status) {
                webViewUrl = (url + "&Authorization=" + authorization);
            } else {
                webViewUrl = (url + "?Authorization=" + authorization);
            }
            webView.loadUrl(webViewUrl);
        } else {
            webView.loadUrl(url);
        }
        mShareListener = new CustomShareListener(getActivity());
    }


    private UMShareListener mShareListener;


    @Override
    public void onResume() {
        super.onResume();
        if (null != webView && App.isRefresh) {
            String userToken = UserHelper.getUserToken();
            Authorization = TextUtils.isEmpty(userToken) ? null : userToken;
            if (!TextUtils.isEmpty(Authorization)) {
                try {
                    authorization = URLEncoder.encode(Authorization, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                boolean status = url.contains("?");
                if (status) {
                    webViewUrl = (url + "&Authorization=" + authorization);
                } else {
                    webViewUrl = (url + "?Authorization=" + authorization);
                }
            }
            webView.loadUrl(webViewUrl);
            App.isRefresh = false;
        }
    }

    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.setAllowUniversalAccessFromFileURLs(false);
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

        //设置自适应屏幕，两者合用
        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(getContext().getDir("appcache", 0).getPath());
        webSettings.setDatabasePath(getContext().getDir("databases", 0).getPath());
        webSettings.setGeolocationDatabasePath(getContext().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);
        webView.setDownloadListener((url, userAgent, contentDisposition, mimetype, contentLength) -> {
            downloadFile(url);
        });
    }

    @Override
    public void downloadFile(String url) {
        if (TextUtils.isEmpty(url)) {
            ToastUtil.getInstance().showShort("文件异常");
            return;
        }
        //      url="data:image/png;base64, ";
        new RxPermissions(this)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(permission -> {
                    if (permission) {
                        try {
                            if (url.startsWith("http")) {
                                String type = url.substring(url.lastIndexOf(".") + 1);
                                if (TextUtils.isEmpty(type)) {
                                    ToastUtil.getInstance().showShort("文件异常");
                                    return;
                                }
                                String path = FileUtils.getPublicDirectory("file");
                                String name = "FILE_" + new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date()) + "." + type;
                                upDateNewsVideoFile(path, name, url, type);
                            } else {
                                String type = FileUtils.getBase64Type(url.split(",")[0]);
                                if (TextUtils.isEmpty(type)) {
                                    ToastUtil.getInstance().showShort("暂不支持该文件保存");
                                    return;
                                }
                                decoderBase64File(url, FileUtils.getPublicDirectory(("png".equals(type) || "jpg".equals(type) ? "img" : "file")), type);
                            }

                        } catch (Exception e) {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("api", "downloadFile");
                            onSendMessage(jsonObject.toString());
                        }
                    }
                });

    }

    @Override
    public void createRightNavToShareButton(String base64Code, String url) {
        String type = FileUtils.getBase64Type(base64Code.split(",")[0]);
        if (TextUtils.isEmpty(type)) {
            return;
        }
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("api", "shareDisplay");
            ivAction.setImageBitmap(FileUtils.base64ToBitmap(base64Code.split(",")[1]));
            ivAction.setVisibility(View.VISIBLE);
            ivAction.setOnClickListener(v ->
                    onSendMessage(jsonObject.toString())
            );
        } catch (Exception e) {
        }
    }

    @Override
    public void shareAchievements(JSONObject jsonObject) {

        JSONObject content = null;
        try {
            content = jsonObject.getJSONObject("content");

            String shareTitle = content.getString("title");
            String shareDesc = content.getString("desc");

            if ("image".equals(content.getString("type"))) {
                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) {

        }
    }

    @Override
    public void backIconChange(JSONObject message) {
        try {
            if (!TextUtils.isEmpty(message.toString())) {
                String icon = message.optJSONObject("content").optString("iconStyle");
                if (!TextUtils.isEmpty(icon)) {
                    if (icon.equals("black")) {
                        if (btnBack == null)
                            return;
                        btnBack.setImageResource(com.cooleshow.base.R.drawable.ic_back);
                    } else if (icon.equals("white")) {
                        if (btnBack == null)
                            return;
                        btnBack.setImageResource(com.cooleshow.base.R.drawable.ic_back_white);
                    }
                }
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void getNavHeight(JSONObject message) {
        try {
            message.getJSONObject("content").put("navHeight", getResources().getDimension(com.cooleshow.base.R.dimen.statusbar_view_height));
            message.getJSONObject("content").put("titleHeight", getResources().getDimension(com.cooleshow.base.R.dimen.dp_44));
            message.getJSONObject("content").put("dpi", getResources().getDisplayMetrics().density);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        onSendMessage(message.toString());
    }

    @Override
    public void setBarStatus(JSONObject message) {
        try {
            if (!TextUtils.isEmpty(message.toString())) {
                int status = message.optJSONObject("content").optInt("status", 1);
                if (status == 1) {
                    rl_activity_html.setBackgroundColor(Color.WHITE);
                    btnClose.setVisibility(View.VISIBLE);
                    tvTitle.setVisibility(View.VISIBLE);
                    tvAction.setVisibility(View.INVISIBLE);
                    if (ivActionIcon > 0 && 1000 == startType) {
                        ivAction.setVisibility(View.VISIBLE);
                    } else {
                        ivAction.setVisibility(View.GONE);
                    }
                    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                    lp.addRule(RelativeLayout.BELOW, R.id.ll_activity_html);
                    viewParent.setLayoutParams(lp);
                    mLayout.setLayoutParams(lp);
                } else {
                    rl_activity_html.setBackgroundColor(Color.TRANSPARENT);
                    btnClose.setVisibility(View.INVISIBLE);
                    tvTitle.setVisibility(View.INVISIBLE);
                    tvAction.setVisibility(View.INVISIBLE);
                    if (ivActionIcon > 0 && 1000 == startType) {
                        ivAction.setVisibility(View.VISIBLE);
                    } else {
                        ivAction.setVisibility(View.GONE);
                    }
                    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                    viewParent.setLayoutParams(lp);
                    mLayout.setLayoutParams(lp);
                }
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void authToBack(JSONObject message) {

    }

    @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) {

    }

    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("支付失败" + resultInfo);
                        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 chooseFile(JSONObject message) {
        baseJsonObject = message;
        showFileChooser();

    }

    private JSONObject baseJsonObject;

    private void showFileChooser() {
        JSONObject content = (JSONObject) baseJsonObject.opt("content");
        String type = "";
        try {
            type = content.getString("type");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//       type: "img" | "video" | "file" | "midi" | "mp3" | "xml"
        if (type.equals("img")) {
            intent.setType("image/*");
        } else if (type.equals("video")) {
            intent.setType("video/*");
        } else if (type.equals("mp3")) {
            intent.setType("audio/*");
        } else if (type.equals("xml")) {
            intent.setType("text/xml");
        } else if (type.equals("midi")) {
            intent.setType("audio/midi");
        } else {
            intent.setType("*/*");
        }
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.putExtra(Intent.EXTRA_TITLE, "File Chooser");
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        startActivityForResult(intent, REQUEST_CODE_FILE_CHOOSER);
    }

    public void decoderBase64File(String base64Code, String savePath, String type) {
        String fileName = File.separator + type + "_" + new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date()) + "." + type;
        try {
            //byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
            byte[] buffer = Base64.decode(base64Code.split(",")[1], Base64.DEFAULT);
            FileOutputStream out = new FileOutputStream(savePath + fileName);
            out.write(buffer);
            out.close();
            getContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(savePath + fileName))));
            ToastUtil.getInstance().showShort("图片储存在：" + savePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void upDateNewsVideoFile(String filePath, String fileName, String url, String type) {
//        showUploadLoading("下载中");
        RetrofitClientNoToken.getInstance().getRetrofit().create(APIService.class)
                .downloadFileWithFixedUrl(url)
                .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, filePath, fileName)) {

                            runOnUiThread(() -> {
                                hideLoading();
                                JSONObject jsonObject = new JSONObject();
                                try {
                                    jsonObject.put("api", "downloadFile");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                onSendMessage(jsonObject.toString());
                                getContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(filePath + File.separator + fileName))));
                                DialogUtil.showInCenter(getParentFragmentManager(), com.cooleshow.base.R.layout.common_popu, "提示", "保存成功，文件保存位置：" + filePath + File.separator + fileName + "；是否打开？", new DialogUtil.OnDialogButtonClickListener() {
                                    @Override
                                    public void onCancel(View v) {

                                    }

                                    @Override
                                    public void onCommit(View v) {
                                        try {
                                            Intent intent = FileUtils.startIntent(getContext(), filePath + File.separator + fileName);
                                            if (intent != null) {
                                                startActivity(intent);
                                            } else {
                                                ToastUtil.getInstance().showShort("打开失败");
                                            }
                                        } catch (Exception e) {
                                            ToastUtil.getInstance().showShort("打开失败");
                                        }

                                    }
                                });
                            });
                        } else {
                            runOnUiThread(() -> {
                                hideLoading();
                                JSONObject jsonObject = new JSONObject();
                                try {
                                    jsonObject.put("api", "downloadFile");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                onSendMessage(jsonObject.toString());
                                ToastUtil.getInstance().showShort("保存失败");
                            });
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        runOnUiThread(() -> {
                            hideLoading();
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("api", "downloadFile");
                            } catch (JSONException e1) {
                                e1.printStackTrace();
                            }
                            onSendMessage(jsonObject.toString());
                            ToastUtil.getInstance().showShort("保存失败");
                        });
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    //android获取一个用于打开PDF文件的intent
    public static Intent getPdfFileIntent(String Path) {
        File file = new File(Path);
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.fromFile(file);
        intent.setDataAndType(uri, "application/pdf");
        return intent;
    }

    private class WebClient extends WebViewClient {
        //页面开始载入时调用

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

        //页面载入结束时调用
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            webViewUrl = url;
            if (!TextUtils.isEmpty(authorization)) {
                String js = "window.localStorage.setItem('Authorization','" + authorization + "');";
                String jsUrl = "javascript:(function({var localStorage = window.localStorage; localStorage.setItem('Authorization','" + authorization + "') })()";
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    view.evaluateJavascript(js, null);
                } else {
                    view.loadUrl(jsUrl);
                    view.reload();
                }
            }

        }

        //截取url请求，在当前视图加载，避免在跳转到自带浏览器
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String request) {
            if (!(request.startsWith("http://") || request.startsWith("https://"))) {
                try {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(request));
                    view.getContext().startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            } else {
                view.loadUrl(request);
                return true;
            }
        }

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


    public void clickBack() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            ((MainActivity) getActivity()).clickBackPressed();
        }
    }

    private class MyWebChromeClient extends WebChromeClient {
        public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100 && null != progressBar) {
                if (null != progressBar) {
                    progressBar.setVisibility(View.GONE);//加载完网页进度条消失
                    //                                if (isNerworkError) {
                    //                                    isNerworkError = false;
                    //                                    onLoadSuccess();
                    //                                }
                }
            } else {
                if (null != progressBar) {
                    progressBar.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    progressBar.setProgress(newProgress);//设置进度值
                }

            }
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (null != tvTitle && !TextUtils.isEmpty(title)) {
                tvTitle.setText(title);
            }

        }

        // Android > 5.0.1
        public boolean onShowFileChooser(
                WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {
            setUploadMsg(filePathCallback);

            addPermissions(PORTRAIT_REQUEST_CODE);
            return true;
        }

        private CustomViewCallback mCustomViewCallback;
        //  横屏时，显示视频的view
        private View mCustomView;

        // 点击全屏按钮时，调用的方法
        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            super.onShowCustomView(view, callback);

            //如果view 已经存在，则隐藏
            if (mCustomView != null) {
                callback.onCustomViewHidden();
                return;
            }

            mCustomView = view;
            mCustomView.setVisibility(View.VISIBLE);
            mCustomViewCallback = callback;
            mLayout.addView(mCustomView);
            mLayout.setVisibility(View.VISIBLE);
//            mLayout.bringToFront();
            headerBbarView.setVisibility(View.GONE);
            //设置横屏
            getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }

        // 取消全屏调用的方法
        @Override
        public void onHideCustomView() {
            super.onHideCustomView();
            if (mCustomView == null) {
                return;
            }
            mCustomView.setVisibility(View.GONE);
            mLayout.removeView(mCustomView);
            mCustomView = null;
            mLayout.setVisibility(View.GONE);
            try {
                mCustomViewCallback.onCustomViewHidden();
            } catch (Exception e) {

            }
            headerBbarView.setVisibility(View.VISIBLE);
            getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
        }
    }


    private ValueCallback mUploadCallbackAboveL;

    public void setUploadMsg(ValueCallback uploadMsg) {
        mUploadCallbackAboveL = uploadMsg;
    }

    private void addPermissions(int requestCode) {
        new RxPermissions(this)
                .request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(permission -> {
                    if (permission) {
                        PictureSelector.create(this)
                                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                                .loadImageEngine(GlideEngine.createGlideEngine())
                                .theme(com.cooleshow.base.R.style.picture_daya_style)// 主题样式设置 具体参考 values/styles   用法：R .style.picture.white.style
                                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                                .enableCrop(false)// 是否裁剪 true or false
                                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                                .compress(true)// 是否压缩 true or false
                                .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                    } else {
                        DialogUtil.showInCenter(getParentFragmentManager(), com.cooleshow.base.R.layout.common_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();
                            });
                        });
                    }
                });
    }

    private void upLoadFileFaile() {
        try {
            JSONObject contentObj = baseJsonObject.getJSONObject("content");
            String uuid = contentObj.getString("uuid");
            contentObj.put("type", "error");
            contentObj.put("uuid", uuid);
            contentObj.put("message", "上传失败");
            onSendMessage(baseJsonObject.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != webView) {
            webView.destroy();
        }
        EventBus.getDefault().unregister(this);
        UMShareAPI.get(getContext()).release();
    }

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

    @Override
    public void setStatusBarTextColor(boolean statusBarTextColor) {
    }


    @Override
    public void onAccompanySelecResult(String id, String name) {

    }


    private static class CustomShareListener implements UMShareListener {

        private WeakReference<Activity> 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(@NonNull @NotNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (mShareAction != null) {
            mShareAction.close();
        }
    }

    /**
     * 发送支付结果
     *
     * @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();
        }
    }
}
