package com.electric.chargingpile.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebBackForwardList;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.LogUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.electric.chargingpile.BuildConfig;
import com.electric.chargingpile.R;
import com.electric.chargingpile.application.MainApplication;
import com.electric.chargingpile.data.CarOwnerCertificateBean;
import com.electric.chargingpile.data.ChargingShareBean;
import com.electric.chargingpile.data.User;
import com.electric.chargingpile.manager.ProfileManager;
import com.electric.chargingpile.util.BarColorUtil;
import com.electric.chargingpile.util.DES3;
import com.electric.chargingpile.util.ImageUitl;
import com.electric.chargingpile.util.JsonUtils;
import com.electric.chargingpile.util.LoadingDialog;
import com.electric.chargingpile.util.PhoneUtils;
import com.electric.chargingpile.util.ToastUtil;
import com.electric.chargingpile.util.Util;
import com.electric.chargingpile.view.AlertDialogTwo;
import com.google.gson.Gson;
import com.khoiron.actionsheets.ActionSheet;
import com.khoiron.actionsheets.callback.ActionSheetCallBack;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import okhttp3.Call;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class MyWebViewActivity extends Activity implements PlatformActionListener, View.OnClickListener, EasyPermissions.PermissionCallbacks {
    private static final String TAG = "MyWebViewActivity";
    private OpenFileWebChromeClient mOpenFileWebChromeClient = null;
    private WebViewClient mWebViewClient;
    private TextView tv_webTitle, tv_webShare;
    private ImageView iv_webClose, iv_webBack, iv_message;
    private ProgressBar pb_webBar;
    private LoadingDialog loadDialog;
    private WebView webView;
    private String canRefresh = "false";
    private String index = "0";
    private String mUrl = "";
    private String advertiser;
    private ArrayList<String> list = new ArrayList<>();
    private String refreshUrl = "";
    private String currentUrl = "";
    private String shareTitle, shareIcon, shareContext, shareUrl;
    private String nickname, username, usersex, hascar, nocar, usericon, userid;
    private TextView tv_point;
    private RelativeLayout rl_point;
    private android.view.animation.Animation animation;
    private static final int RC_CALL_PERM = 123;

    private static final int RC_ALBUM_PERM = 127;
    private final static int FILE_CHOOSER_RESULT_CODE = 128;  // 图片
    private final static int FILE_CAMERA_RESULT_CODE = 129; // 拍照
    private String cameraFilePath;  // 拍照图片路径
    private boolean loginToShare;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_web_view);
        BarColorUtil.initStatusBarColor(MyWebViewActivity.this);
        getIntentData();
        initView();
        initWebView();
    }

    private void getIntentData() {
        mUrl = getIntent().getStringExtra("url");
        advertiser = getIntent().getStringExtra("advertiser");
        Log.e(TAG, "getIntentData: " + mUrl);
        if (advertiser != null && advertiser.equals("1")) {
            mUrl = Util.generateDmpUrl(mUrl);
        }
    }


    private void initView() {
        loadDialog = new LoadingDialog(this);
        loadDialog.setCanceledOnTouchOutside(false);
        rl_point = (RelativeLayout) findViewById(R.id.rl_point);
        tv_point = (TextView) findViewById(R.id.tv_point);
        animation = AnimationUtils.loadAnimation(MyWebViewActivity.this, R.anim.nn);
        tv_webTitle = (TextView) findViewById(R.id.tv_webview_title);
        tv_webShare = (TextView) findViewById(R.id.tv_webview_share);
        tv_webShare.setOnClickListener(this);
        iv_webBack = (ImageView) findViewById(R.id.iv_webview_back);
        iv_webBack.setOnClickListener(this);
        iv_webClose = (ImageView) findViewById(R.id.iv_webview_close);
        iv_webClose.setOnClickListener(this);
        pb_webBar = (ProgressBar) findViewById(R.id.pb_webview_bar);
        iv_message = (ImageView) findViewById(R.id.iv_message);
        webView = (WebView) findViewById(R.id.webView);
        Log.e("!!", webView.getId() + "");

    }

    private void initWebView() {
        mOpenFileWebChromeClient = new OpenFileWebChromeClient(this);
        mWebViewClient = new MyWebViewClient();
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setDatabaseEnabled(true);
        String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        webView.getSettings().setGeolocationEnabled(true);
        webView.getSettings().setGeolocationDatabasePath(dir);
        webView.setWebChromeClient(mOpenFileWebChromeClient);
        webView.getSettings().setDomStorageEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webView.addJavascriptInterface(this, "cdz");
        webView.setWebViewClient(mWebViewClient);
        if (null != mUrl && !"".equals(mUrl)) {
            if (mUrl.contains("?")) {
                mUrl = mUrl + "&version_code=" + BuildConfig.VERSION_CODE + "&from=cdz&system=android";
            } else {
                mUrl = mUrl + "?version_code=" + BuildConfig.VERSION_CODE + "&from=cdz&system=android";
            }
            if (MainApplication.isLogin()) {
                mUrl = mUrl + "&phone=" + MainApplication.userPhone;
            }

            webView.loadUrl(mUrl);
        }

        webView.setLongClickable(true);
        webView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                final WebView.HitTestResult result = webView.getHitTestResult(); // 获取元素内容
                // 判断元素类型是 图片 || 图片URL
                if (result.getType() == WebView.HitTestResult.IMAGE_TYPE || result.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
                    String url = result.getExtra(); // 获取元素
                    Glide.with(MyWebViewActivity.this).asBitmap().load(url).into(new CustomTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@NonNull @NotNull Bitmap resource, @Nullable @org.jetbrains.annotations.Nullable Transition<? super Bitmap> transition) {
                            ArrayList<String> data = new ArrayList<>();
                            data.add("保存图像");
                            new ActionSheet(MyWebViewActivity.this, data)
                                    .hideTitle()
                                    .setCancelTitle("取消")
                                    .setColorTitle(Color.parseColor("#999999"))
                                    .setColorTitleCancel(Color.parseColor("#999999"))
                                    .setColorData(getResources().getColor(R.color.ui_green, null))
                                    .create(new ActionSheetCallBack() {
                                        @Override
                                        public void data(@NotNull String data, int position) {
                                            System.out.println(position);
                                            System.out.println(data);
                                            switch (position) {
                                                case 0:
                                                    saveImage(resource);
                                                    break;
                                            }
                                        }
                                    });
                        }

                        @Override
                        public void onLoadCleared(@Nullable @org.jetbrains.annotations.Nullable Drawable placeholder) {

                        }
                    });
                }
                return true;
            }
        });
    }

    private void saveImage(Bitmap resource) {
        String saveImagePath = null;
        String imageFileName = "d1ev_" + PhoneUtils.getGUID() + ".png";
        File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "d1ev");
        boolean success = true;
        if (!storageDir.exists()) {
            success = storageDir.mkdir();
        }

        if (success) {
            File imageFile = new File(storageDir, imageFileName);
            saveImagePath = imageFile.getAbsolutePath();
            try {
                OutputStream outputStream = new FileOutputStream(imageFile);
                resource.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
                outputStream.close();
            } catch (Exception e) {
                ToastUtil.showToast(MyWebViewActivity.this, "保存图像失败", Toast.LENGTH_SHORT);
                e.printStackTrace();
            }

            galleryAddPic(saveImagePath);
        } else {
            ToastUtil.showToast(MyWebViewActivity.this, "保存图像失败", Toast.LENGTH_SHORT);
        }
    }

    private void galleryAddPic(String imagePath) {
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File file = new File(imagePath);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        sendBroadcast(intent);
        ToastUtil.showToast(MyWebViewActivity.this, "图像已成功保存到相册", Toast.LENGTH_SHORT);
    }


    // 93 3.5.5 小程序埋点
    @JavascriptInterface
    public void showminiprogram(final String user_name, String path, int type) {
        if (Util.isWxAppInstalledAndSupported(MyWebViewActivity.this)) {
            IWXAPI api = WXAPIFactory.createWXAPI(MyWebViewActivity.this, getResources().getString(R.string.wx_app_key));
            WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
            req.userName = user_name;
            req.path = path;
            req.miniprogramType = type;
            api.sendReq(req);
        } else {
            ToastUtil.showToast(getApplicationContext(), "请先安装微信", Toast.LENGTH_SHORT);
        }
    }

    @JavascriptInterface
    public void welfareshare(final String shareUrl) {
        if (TextUtils.isEmpty(shareUrl)) {
            loginToShare = true;
            startActivity(new Intent(getApplicationContext(), LoginActivity.class));
            ToastUtil.showToast(getApplicationContext(), "请先登录", Toast.LENGTH_SHORT);
        } else {
            loginToShare = false;
            showSimpleBottomSheetGrid(shareUrl);
        }
    }

    @JavascriptInterface
    public void showsharebtn(final String show) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (show.equals("yes")) {
                    tv_webShare.setVisibility(View.VISIBLE);
                    tv_webShare.setText("分享");
                } else {
                    tv_webShare.setVisibility(View.GONE);
                    tv_webShare.setText("");
                }
            }
        });

    }

    @JavascriptInterface
    public void freshpage(final String url) {
        list.add(url);
    }

    @JavascriptInterface
    public void setrctext(final String s) {
        Log.e(TAG, "setrctext: s=" + s);
        String[] strarray = s.split("\\#\\#");
        final String text = strarray[0];
        final String show = strarray[1];
        final String message = strarray[2];
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (show.equals("yes")) {
                    tv_webShare.setVisibility(View.VISIBLE);
                    tv_webShare.setText(text);
                    if (message.equals("yes")) {
                        iv_message.setVisibility(View.VISIBLE);
                    } else {
                        iv_message.setVisibility(View.GONE);
                    }
                } else {
                    tv_webShare.setVisibility(View.GONE);
                }
            }
        });
    }

    @JavascriptInterface
    public void emitshareinfo(String shareInfo) {
//        "分享标题##分享描述##分享ico##分享url"
        String[] strarray = shareInfo.split("\\#\\#");
        if (strarray.length > 1) {
            shareTitle = strarray[0];
            shareContext = strarray[1];
            shareIcon = strarray[2];
            shareUrl = strarray[3];
        }
    }

    @JavascriptInterface
    public void sharetowxfd() {
        if (null != shareTitle && null != shareContext && null != shareIcon && null != shareUrl) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    Platform.ShareParams wechat = new Platform.ShareParams();
                    wechat.setTitle(shareTitle);
                    wechat.setText(shareContext);
                    wechat.setImageUrl(shareIcon);
                    wechat.setUrl(shareUrl);
                    wechat.setShareType(Platform.SHARE_WEBPAGE);
                    Platform weixin = ShareSDK.getPlatform(Wechat.NAME);
                    weixin.setPlatformActionListener(MyWebViewActivity.this);
                    weixin.share(wechat);
                }
            });
        } else {
            ToastUtil.showToast(getApplicationContext(), "分享信息不完整", Toast.LENGTH_SHORT);
        }
    }

    @JavascriptInterface
    public void sharetowxlf() {
        if (null != shareTitle && null != shareContext && null != shareIcon && null != shareUrl) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    Platform.ShareParams wechatMoments = new Platform.ShareParams();
                    wechatMoments.setTitle(shareTitle);
                    wechatMoments.setUrl(shareUrl);
                    wechatMoments.setImageUrl(shareIcon);
                    wechatMoments.setText(shareContext);
                    wechatMoments.setShareType(Platform.SHARE_WEBPAGE);
                    Platform weixin1 = ShareSDK.getPlatform(WechatMoments.NAME);
                    weixin1.setPlatformActionListener(MyWebViewActivity.this);
                    weixin1.share(wechatMoments);
                }
            });
        } else {
            ToastUtil.showToast(getApplicationContext(), "分享信息不完整", Toast.LENGTH_SHORT);
        }
    }

    @JavascriptInterface
    public void sharetoqq() {
        if (null != shareTitle && null != shareContext && null != shareIcon && null != shareUrl) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    Platform.ShareParams qq = new Platform.ShareParams();
                    qq.setTitle(shareTitle);
                    qq.setUrl(shareUrl);
                    qq.setImageUrl(shareIcon);
                    qq.setText(shareContext);
                    qq.setShareType(Platform.SHARE_WEBPAGE);
                    Platform weixin1 = ShareSDK.getPlatform(QQ.NAME);
                    weixin1.setPlatformActionListener(MyWebViewActivity.this);
                    weixin1.share(qq);
                }
            });
        } else {
            ToastUtil.showToast(getApplicationContext(), "分享信息不完整", Toast.LENGTH_SHORT);
        }
    }

    private void btnToShare() {
        showSimpleBottomSheetGrid(shareUrl);
    }

    private void showSimpleBottomSheetGrid(final String shareUrl) {
        final int TAG_SHARE_WECHAT_FRIEND = 0;
        final int TAG_SHARE_WECHAT_MOMENT = 1;
        final int TAG_SHARE_QQ = 2;
        QMUIBottomSheet.BottomGridSheetBuilder builder = new QMUIBottomSheet.BottomGridSheetBuilder(MyWebViewActivity.this);
        QMUIBottomSheet build = builder.addItem(R.drawable.icon_share_wechat, "微信", TAG_SHARE_WECHAT_FRIEND, QMUIBottomSheet.BottomGridSheetBuilder.FIRST_LINE)
                .addItem(R.drawable.icon_share_wechatquan, "朋友圈", TAG_SHARE_WECHAT_MOMENT, QMUIBottomSheet.BottomGridSheetBuilder.FIRST_LINE)
                .addItem(R.drawable.icon_share_qq, "QQ", TAG_SHARE_QQ, QMUIBottomSheet.BottomGridSheetBuilder.FIRST_LINE)
                .setOnSheetItemClickListener(new QMUIBottomSheet.BottomGridSheetBuilder.OnSheetItemClickListener() {
                    @Override
                    public void onClick(QMUIBottomSheet dialog, View itemView) {
                        dialog.dismiss();
                        int tag = (int) itemView.getTag();
                        switch (tag) {
                            case TAG_SHARE_WECHAT_FRIEND:
                                share(Wechat.NAME, shareUrl);
                                break;
                            case TAG_SHARE_WECHAT_MOMENT:
                                share(WechatMoments.NAME, shareUrl);
                                break;
                            case TAG_SHARE_QQ:
                                share(QQ.NAME, shareUrl);
                                break;
                        }
                    }
                }).build();
        build.show();
    }

    private void showSimpleBottomSheetGrid(final ChargingShareBean chargingShareBean) {
        final int TAG_SHARE_WECHAT_FRIEND = 0;
        final int TAG_SHARE_WECHAT_MOMENT = 1;
        final int TAG_SHARE_QQ = 2;
        QMUIBottomSheet.BottomGridSheetBuilder builder = new QMUIBottomSheet.BottomGridSheetBuilder(MyWebViewActivity.this);
        QMUIBottomSheet build = builder.addItem(R.drawable.icon_share_wechat, "微信", TAG_SHARE_WECHAT_FRIEND, QMUIBottomSheet.BottomGridSheetBuilder.FIRST_LINE)
                .addItem(R.drawable.icon_share_wechatquan, "朋友圈", TAG_SHARE_WECHAT_MOMENT, QMUIBottomSheet.BottomGridSheetBuilder.FIRST_LINE)
                .addItem(R.drawable.icon_share_qq, "QQ", TAG_SHARE_QQ, QMUIBottomSheet.BottomGridSheetBuilder.FIRST_LINE)
                .setOnSheetItemClickListener(new QMUIBottomSheet.BottomGridSheetBuilder.OnSheetItemClickListener() {
                    @Override
                    public void onClick(QMUIBottomSheet dialog, View itemView) {
                        dialog.dismiss();
                        int tag = (int) itemView.getTag();
                        switch (tag) {
                            case TAG_SHARE_WECHAT_FRIEND:
                                share(Wechat.NAME, chargingShareBean);
                                break;
                            case TAG_SHARE_WECHAT_MOMENT:
                                share(WechatMoments.NAME, chargingShareBean);
                                break;
                            case TAG_SHARE_QQ:
                                share(QQ.NAME, chargingShareBean);
                                break;
                        }
                    }
                }).build();
        build.show();
    }

    private void share(final String name, final String shareUrl) {
        Platform.ShareParams paramsToShare = new Platform.ShareParams();
        paramsToShare.setText(shareContext);
        paramsToShare.setTitle(shareTitle);
        paramsToShare.setTitleUrl(shareUrl);
        paramsToShare.setUrl(shareUrl);
        paramsToShare.setImageUrl(shareIcon);
        paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
        Platform platform = ShareSDK.getPlatform(name);
        platform.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                getShareIntegral();
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                LogUtils.e(throwable.getMessage());
            }

            @Override
            public void onCancel(Platform platform, int i) {
            }
        });
        platform.share(paramsToShare);
    }

    private void share(final String name, ChargingShareBean chargingShareBean) {
        Platform.ShareParams paramsToShare = new Platform.ShareParams();
        paramsToShare.setText(chargingShareBean.getText());
        paramsToShare.setTitle(chargingShareBean.getTitle());
        paramsToShare.setTitleUrl(chargingShareBean.getUrl());
        paramsToShare.setUrl(chargingShareBean.getUrl());
        paramsToShare.setImageUrl(chargingShareBean.getIcon());
        paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
        Platform platform = ShareSDK.getPlatform(name);
        platform.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                if (MainApplication.isLogin()) {
                    getShareIntegral();
                }
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                LogUtils.e(throwable.getMessage());
            }

            @Override
            public void onCancel(Platform platform, int i) {
            }
        });
        platform.share(paramsToShare);
    }

    @JavascriptInterface
    public void gotoshare() {
        showSimpleBottomSheetGrid(shareUrl);
    }


    @AfterPermissionGranted(RC_CALL_PERM)
    public void telTask(final String s) {
        if (hasCallPhonePermission()) {
            // Have permission, do the thing!
            new com.electric.chargingpile.view.AlertDialog(MyWebViewActivity.this).builder()
                    .setMsg(s)
                    .setPositiveButton("呼叫", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent();
                            intent.setAction("android.intent.action.CALL");
                            intent.addCategory("android.intent.category.DEFAULT");
                            intent.setData(Uri.parse("tel:" + s));
                            startActivity(intent);
                        }
                    }).setNegativeButton("取消", new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            }).show();
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(
                    this,
                    "该功能需要开启拨号权限,是否前往开启?",
                    RC_CALL_PERM,
                    Manifest.permission.CALL_PHONE);
        }
    }

    @JavascriptInterface
    public void makeacall(final String s) {
        //telTask(s);
        wechatAlert();
    }

    private void wechatAlert() {
        AlertDialogTwo wechatAlert = new AlertDialogTwo(MyWebViewActivity.this);
        wechatAlert.builder().setTitle("温馨提示")
                .setMsg("客服微信:chongdianzhuang2")
                .setPositiveButton("复制", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                        ClipData cdzData = ClipData.newPlainText("Label", "chongdianzhuang2");
                        cm.setPrimaryClip(cdzData);
                        ToastUtil.showToast(getApplicationContext(), "微信号复制成功", Toast.LENGTH_SHORT);
                    }
                }).show();
    }

    @JavascriptInterface
    public void closepage() {
        finish();
    }

    @JavascriptInterface
    public String getuserinfo() throws Exception {
        String s = null;
        if (MainApplication.isLogin()) {
            long appTime1 = System.currentTimeMillis() / 1000;
            long updatetime = appTime1 - MainMapActivity.cha - 3;
            String token = DES3.encode(String.valueOf(updatetime));
            s = MainApplication.userId + "##" + MainApplication.userPhone + "##" + token;
        } else {
            s = "no";
        }
        final String finalS = s;
        runOnUiThread(new Runnable() {
            @TargetApi(Build.VERSION_CODES.KITKAT)
            @Override
            public void run() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    webView.evaluateJavascript("window.myglobal.regetuserinfo('" + finalS + "')", new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(String arg0) {

                        }
                    });
                } else {
                    webView.loadUrl("window.myglobal.regetuserinfo('" + finalS + "')");
                }

            }
        });
        return s;
    }

    @JavascriptInterface
    public void openpaynopwd() {
        Intent intent = new Intent(getApplicationContext(), NonSecretSeettingActivity.class);
        Uri uri = Uri.parse("chongdianzhuang://");
        intent.setData(uri);
        startActivity(intent);
        finish();
    }

    @JavascriptInterface
    public void runpaynopwd(String s) {
        String[] strarray = s.split("\\#\\#");
        String user_id = strarray[0];
        String order_id = strarray[1];
        Intent intent = new Intent(getApplicationContext(), NonSecretSeettingActivity.class);
        intent.putExtra("user_id", user_id);
        intent.putExtra("order_id", order_id);
        intent.putExtra("money", "");
        intent.putExtra("tag", "1");
        Uri uri = Uri.parse("chongdianzhuang://");
        intent.setData(uri);
        startActivity(intent);
        finish();
    }

    @JavascriptInterface
    public void commentredpack(String s) {
        String[] strarray = s.split("\\#\\#");
        String zhanid = strarray[0];
        String orderid = strarray[1];
        String url = strarray[2];
        String money = strarray[3];
        Intent intent = new Intent(getApplicationContext(), ChargingCommentActivity.class);
        intent.putExtra("zhan_id", zhanid);
        intent.putExtra("order_id", orderid);
        intent.putExtra("money", money);
        intent.putExtra("url", url);
        intent.putExtra("zhuang_id", "");
        startActivity(intent);
        MobclickAgent.onEvent(getApplicationContext(), "0610");
    }


    @JavascriptInterface
    public void gotopage(String s) {
        Log.e(TAG, "gotopage: s=" + s);
        String[] strarray = s.split("\\#\\#");
        String id = strarray[0];
        switch (id) {
            case "01":
                //注册
                startActivity(new Intent(getApplicationContext(), RegisterActivity.class));
                break;
            case "02":
                //登录页
                if (MainApplication.isLogin()) {
                    ToastUtil.showToast(getApplicationContext(), "您已经登录", Toast.LENGTH_SHORT);
                } else {
                    startActivity(new Intent(getApplicationContext(), LoginActivity.class));
                }
                break;
            case "03":
                //余额页
                if (MainApplication.isLogin()) {
                    startActivity(new Intent(getApplication(), MyBalanceActivity.class));
                } else {
                    startActivity(new Intent(getApplicationContext(), LoginActivity.class));
                    ToastUtil.showToast(getApplicationContext(), "请先登录", Toast.LENGTH_SHORT);
                    index = "3";
                }
                break;
            case "04":
                //充值页
                if (!MainApplication.isLogin()) {
                    ToastUtil.showToast(getApplication(), "请先登录", Toast.LENGTH_SHORT);
                    startActivity(new Intent(getApplication(), LoginActivity.class));
                    index = "4";
                } else {
                    startActivity(new Intent(getApplication(), AccountRechargeActivity.class));
                }
                break;
            case "05":
                //兑吧商城首页
                skipShopCenter();
                break;
            case "06":
                //兑吧商品详情页
                String url = strarray[1];
                Log.e(TAG, "gotopage: !!!!!");
                skipShopDetail(url);
                break;
            case "07":
                //添加新站点
                if (MainApplication.isLogin()) {
                    startActivity(new Intent(getApplication(), ShareTwoActivity.class));
                } else {
                    startActivity(new Intent(getApplicationContext(), LoginActivity.class));
                    ToastUtil.showToast(getApplicationContext(), "请先登录", Toast.LENGTH_SHORT);
                    index = "7";
                }
                break;
            case "08":
                //充电排行榜
                if (MainApplication.isLogin()) {
                    startActivity(new Intent(getApplication(), RankingListActivity.class));
                } else {
                    startActivity(new Intent(getApplicationContext(), LoginActivity.class));
                    ToastUtil.showToast(getApplicationContext(), "请先登录", Toast.LENGTH_SHORT);
                    index = "8";
                }
                break;
            case "09":
                //路径规划
                startActivity(new Intent(getApplicationContext(), RoutePlanShowAddressActivity.class));
                break;
            case "10":
                //站点详情
                String zhan_id = strarray[1];
                String current = strarray[2];
                if (current.equals("detail")) {
                    Intent intent = new Intent(getApplicationContext(), NewZhanDetailsActivity.class);
                    intent.putExtra("zhan_id", zhan_id);
                    MainApplication.details_flag = "2";
                    startActivity(intent);
                } else if (current.equals("comment")) {
                    Intent intent = new Intent(getApplicationContext(), NewZhanDetailsActivity.class);
                    intent.putExtra("zhan_id", zhan_id);
                    MainApplication.details_flag = "4";
                    startActivity(intent);
                } else if (current.equals("writecomment")) {
                    Intent intent = new Intent(getApplicationContext(), ZhanCommentActivity.class);
                    intent.putExtra("zhan_id", zhan_id);
                    intent.putExtra("show_txt", "有什么想吐槽的吗?来跟其他车友分享一下吧...");
                    startActivity(intent);
                }
                break;
            case "11":
                //意见反馈
                if (MainApplication.isLogin()) {
                    startActivity(new Intent(getApplication(), FeedbackActivity.class));
                } else {
                    startActivity(new Intent(getApplicationContext(), LoginActivity.class));
                    ToastUtil.showToast(getApplicationContext(), "请先登录", Toast.LENGTH_SHORT);
                    index = "11";
                }
                break;
            case "12":
                //邀请记录
                startActivity(new Intent(getApplication(), YaoQingListActivity.class));
                break;
            case "13":
                //提问页
                if (MainApplication.isLogin()) {
                    startActivity(new Intent(getApplication(), EditQuestionOneActivity.class));
                } else {
                    startActivity(new Intent(getApplicationContext(), LoginActivity.class));
                    ToastUtil.showToast(getApplicationContext(), "请先登录", Toast.LENGTH_SHORT);
                    index = "13";
                }
                break;
            case "14":
                startActivity(new Intent(getApplication(), UnansweredActivity.class));
                break;
            case "15":
                if (MainApplication.isLogin()) {
                    runOnUiThread(new Runnable() {
                        @TargetApi(Build.VERSION_CODES.KITKAT)
                        @Override
                        public void run() {
                            loadDialog.show();
                        }
                    });

                    getCarOwnerCertificateList();
                } else {
                    startActivity(new Intent(getApplicationContext(), LoginActivity.class));
                    ToastUtil.showToast(getApplicationContext(), "请先登录", Toast.LENGTH_SHORT);
                    index = "15";
                }
                break;
        }

    }

    @JavascriptInterface
    public void userlogin(String s) throws Exception {
        String[] strarray = s.split("\\#\\#");
        final String user_name = strarray[0];
        final String password = strarray[1];
        long appTime1 = System.currentTimeMillis() / 1000;
        long updatetime = appTime1 - MainMapActivity.cha - 3;
        String token = DES3.encode(String.valueOf(updatetime));
        final String replace = URLEncoder.encode(token, "UTF-8");
        String url = MainApplication.url + "/zhannew/basic/web/index.php/tpmember/login?phone="
                + user_name + "&password=" + URLEncoder.encode(password, "UTF-8") + "&token=" + replace
                + "&imei=" + "android_" + MainApplication.imei + "&registration_id=" + MainApplication.getInstance().getPushID();
        StringCallback stringCallback = new StringCallback() {
            @Override
            public void onError(Call call, Exception e) {
                runOnUiThread(new Runnable() {
                    @TargetApi(Build.VERSION_CODES.KITKAT)
                    @Override
                    public void run() {
                        webView.evaluateJavascript("window.myglobal.reuserlogin('" + "no" + "')", new ValueCallback<String>() {
                            @Override
                            public void onReceiveValue(String arg0) {
                            }
                        });
                    }
                });
            }

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObj = new JSONObject(response);
                    String rtnCode = jsonObj.getString("rtnCode");
                    if (rtnCode.equals("01")) {
                        String data = jsonObj.getString("data");
                        try {
                            Gson g = new Gson();
                            User u = g.fromJson(data, User.class);
                            userid = u.getUserid().toString();
                            if (!u.getUserpic().toString().equals("")) {
                                usericon = MainApplication.url + "/zhannew//uploadfile/" + u.getUserpic().toString();
                            } else {
                                usericon = "";
                            }
                            nickname = u.getNickname();
                            username = u.getUsername();
                            usersex = u.getSex();
                            hascar = u.getChexing();
                            nocar = u.getYichexing();
                            if (nickname == null) {
                                nickname = "";
                            }
                            Log.e("usericon", usericon);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        SharedPreferences mySharedPreferences = getSharedPreferences("loginUserName",
                                Activity.MODE_PRIVATE);
                        SharedPreferences.Editor editor1 = mySharedPreferences.edit();
                        editor1.putString("username", user_name);
                        editor1.commit();
                        SharedPreferences mSharedPreferences = getSharedPreferences("userInfo",
                                Activity.MODE_PRIVATE);
                        SharedPreferences.Editor editor = mSharedPreferences.edit();
                        editor.putString("nickname", nickname);
                        editor.putString("username", username);
                        editor.putString("sex", usersex);
                        editor.putString("chexing", hascar);
                        editor.putString("yichexing", nocar);
                        editor.putString("password", password);
                        editor.putString("yonghuming", user_name);
                        editor.commit();
                        MainApplication.ok = "1";
                        MainApplication.userPhone = user_name;
                        MainApplication.userPassword = password;
                        ProfileManager.getInstance().setUsername(MyWebViewActivity.this,
                                user_name);
                        ProfileManager.getInstance().setId(MyWebViewActivity.this, user_name);
                        ProfileManager.getInstance().setKeyUserpassword(MyWebViewActivity.this, password);
                        MainApplication.userId = userid;
                        MainApplication.userIcon = usericon;
                        MainApplication.userNickname = nickname;
                        ProfileManager.getInstance().setUserid(MyWebViewActivity.this, userid);
                        ProfileManager.getInstance().setUsericon(MyWebViewActivity.this, usericon);
                        ProfileManager.getInstance().setNickname(MyWebViewActivity.this, nickname);
                        MobclickAgent.onProfileSignIn(MainApplication.userId);
                        ToastUtil.showToast(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT);
                        runOnUiThread(new Runnable() {
                            @TargetApi(Build.VERSION_CODES.KITKAT)
                            @Override
                            public void run() {
                                webView.evaluateJavascript("window.myglobal.reuserlogin('" + "yes" + "')", new ValueCallback<String>() {
                                    @Override
                                    public void onReceiveValue(String arg0) {

                                    }
                                });
                            }
                        });
                    } else if (rtnCode.equals("03")) {
                        runOnUiThread(new Runnable() {
                            @TargetApi(Build.VERSION_CODES.KITKAT)
                            @Override
                            public void run() {
                                webView.evaluateJavascript("window.myglobal.reuserlogin('" + "no" + "')", new ValueCallback<String>() {
                                    @Override
                                    public void onReceiveValue(String arg0) {

                                    }
                                });
                            }
                        });
                        ToastUtil.showToast(getApplicationContext(), "登录超时,请重新登录", Toast.LENGTH_SHORT);
                    } else if (rtnCode.equals("02")) {
                        runOnUiThread(new Runnable() {
                            @TargetApi(Build.VERSION_CODES.KITKAT)
                            @Override
                            public void run() {
                                webView.evaluateJavascript("window.myglobal.reuserlogin('" + "no" + "')", new ValueCallback<String>() {
                                    @Override
                                    public void onReceiveValue(String arg0) {

                                    }
                                });
                            }
                        });
                        ToastUtil.showToast(getApplicationContext(), "用户不存在,请核对后重新填写", Toast.LENGTH_SHORT);
                    } else if (rtnCode.equals("04")) {
                        runOnUiThread(new Runnable() {
                            @TargetApi(Build.VERSION_CODES.KITKAT)
                            @Override
                            public void run() {
                                webView.evaluateJavascript("window.myglobal.reuserlogin('" + "no" + "')", new ValueCallback<String>() {
                                    @Override
                                    public void onReceiveValue(String arg0) {

                                    }
                                });
                            }
                        });
                        ToastUtil.showToast(getApplicationContext(), "密码错误,请重新输入", Toast.LENGTH_SHORT);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        OkHttpUtils.get().url(url).build().execute(stringCallback);
    }

    private void onResumeSkip() {
        switch (index) {
            case "3":
                if (MainApplication.isLogin()) {
                    startActivity(new Intent(getApplication(), MyBalanceActivity.class));
                    index = "0";
                }
                break;
            case "4":
                if (MainApplication.isLogin()) {
                    startActivity(new Intent(getApplication(), AccountRechargeActivity.class));
                    index = "0";
                }
                break;
            case "7":
                if (MainApplication.isLogin()) {
                    startActivity(new Intent(getApplication(), ShareTwoActivity.class));
                    index = "0";
                }
                break;
            case "8":
                if (MainApplication.isLogin()) {
                    startActivity(new Intent(getApplication(), RankingListActivity.class));
                    index = "0";
                }
                break;
            case "11":
                if (MainApplication.isLogin()) {
                    startActivity(new Intent(getApplication(), FeedbackActivity.class));
                    index = "0";
                }
                break;
            case "13":
                if (MainApplication.isLogin()) {
                    startActivity(new Intent(getApplication(), EditQuestionOneActivity.class));
                    index = "0";
                }
                break;
            case "100":
                if (MainApplication.isLogin()) {
                    startActivity(new Intent(getApplication(), MyFeedbackActivity.class));
                    index = "0";
                }
                break;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        onResumeSkip();
        Log.e(TAG, "onResume: =" + "---------");
        for (int i = 0; i < list.size(); i++) {
            if (currentUrl.contains(list.get(i))) {
                Log.e(TAG, "onResume: =" + "========");
                webView.reload();
                list.remove(list.get(i));
                break;
            }
        }

        if (null != mUrl && !"".equals(mUrl) && loginToShare) {
            if (!mUrl.contains("&phone=")) {
                if (MainApplication.isLogin()) {
                    mUrl = mUrl + "&phone=" + MainApplication.userPhone;
                    webView.loadUrl(mUrl);
                }
            }
        }
    }

    private void skipShopCenter() {
        long appTime11 = System.currentTimeMillis() / 1000;
        Log.i("appTime(long)---", appTime11 + "");
        long updatetime1 = appTime11 - MainMapActivity.cha - 5;
        Log.i("updatetime(long)---", updatetime1 + "");
        Log.i("cha---", MainMapActivity.cha + "");
        String token1 = String.valueOf(updatetime1);
        String encode_token = null;
        try {
            encode_token = DES3.encode(token1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String replace = URLEncoder.encode(encode_token);
        Intent intent11 = new Intent();
        intent11.setClass(getApplicationContext(), CreditActivity.class);
        intent11.putExtra("navColor", "#fcfcfc");    //配置导航条的背景颜色,请用#ffffff长格式。
        intent11.putExtra("titleColor", "#222222");    //配置导航条标题的颜色,请用#ffffff长格式。
        MainApplication.goods_type = "shop";
        if (!MainApplication.isLogin()) {
            intent11.putExtra("url", "http://cdz.evcharge.cc/zhannew/basic/web/index.php/duiba/active?token=" + replace);    //配置自动登陆地址,每次需服务端动态生成。
        } else {
            intent11.putExtra("url", "http://cdz.evcharge.cc/zhannew/basic/web/index.php/duiba/active?user_id=" + MainApplication.userId + "&token=" + replace);    //配置自动登陆地址,每次需服务端动态生成。
        }
        startActivity(intent11);

        CreditActivity.creditsListener = new CreditActivity.CreditsListener() {
            /**
             * 当点击分享按钮被点击
             * @param shareUrl 分享的地址
             * @param shareThumbnail 分享的缩略图
             * @param shareTitle 分享的标题
             * @param shareSubtitle 分享的副标题
             */
            public void onShareClick(WebView webView, String shareUrl, String shareThumbnail, String shareTitle, String shareSubtitle) {
                //当分享按钮被点击时,会调用此处代码。在这里处理分享的业务逻辑。
                ChargingShareBean chargingShareBean = new ChargingShareBean();
                chargingShareBean.setIcon(shareThumbnail);
                chargingShareBean.setTitle(shareTitle);
                chargingShareBean.setUrl(shareUrl);
                chargingShareBean.setText("");
                showSimpleBottomSheetGrid(chargingShareBean);
            }

            /**
             * 当点击“请先登录”按钮唤起登录时,会调用此处代码。
             * 用户登录后,需要将CreditsActivity.IS_WAKEUP_LOGIN变量设置为true。
             * @param webView 用于登录成功后返回到当前的webview刷新登录状态。
             * @param currentUrl 当前页面的url
             */
            public void onLoginClick(WebView webView, final String currentUrl) {
                //当未登录的用户点击去登录时,会调用此处代码。
                //用户登录后,需要将CreditsActivity.IS_WAKEUP_LOGIN变量设置为true。
                //为了用户登录后能回到未登录前的页面(currentUrl)。
                //当用户登录成功后,需要重新请求一次服务端,带上currentUrl。
                //用该方法中的webview变量加载请求链接。
                //服务端收到请求后在生成免登录url时,将currentUrl放入redirect参数,通知客户端302跳转到新生成的免登录URL。
                new AlertDialog.Builder(webView.getContext()).setTitle("跳转登录").setMessage("跳转到登录页面?")
                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                MainApplication.current_url = currentUrl;
                                startActivity(new Intent(getApplicationContext(), LoginActivity.class));
                            }
                        })
                        .setNegativeButton("否", null)
                        .show();
            }

            /**
             * 当点击“复制”按钮时,触发该方法,回调获取到券码code
             * @param webView webview对象。
             * @param code 复制的券码
             */
            public void onCopyCode(WebView webView, String code) {
                //当未登录的用户点击去登录时,会调用此处代码。
                new AlertDialog.Builder(webView.getContext())
                        .setTitle("复制券码")
                        .setMessage("已复制,券码为:" + code)
                        .setPositiveButton("是", null)
                        .setNegativeButton("否", null)
                        .show();
            }

            /**
             * 积分商城返回首页刷新积分时,触发该方法。
             */
            public void onLocalRefresh(WebView mWebView, String credits) {
                //String credits为积分商城返回的最新积分,不保证准确。
                //触发更新本地积分,这里建议用ajax向自己服务器请求积分值,比较准确。
            }
        };
    }

    private void skipShopDetail(String url) {
        long appTime11 = System.currentTimeMillis() / 1000;
        long updatetime1 = appTime11 - MainMapActivity.cha - 5;
        String token1 = String.valueOf(updatetime1);
        String encode_token = null;
        try {
            encode_token = DES3.encode(token1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String replace = URLEncoder.encode(encode_token);
//                    startActivity(new Intent(getApplication(), ShopActivity.class));
        Intent intent11 = new Intent();
        intent11.setClass(getApplicationContext(), CreditActivity.class);
        intent11.putExtra("navColor", "#fcfcfc");    //配置导航条的背景颜色,请用#ffffff长格式。
        intent11.putExtra("titleColor", "#222222");    //配置导航条标题的颜色,请用#ffffff长格式。
        MainApplication.goods_type = "details";
//            MainApplication.current_url = getIntent().getStringExtra("shareUrl");
//                MainApplication.current_url = "http://www.duiba.com.cn/mobile/appItemDetail?appItemId=453087";
        if (!MainApplication.isLogin()) {
            intent11.putExtra("url", "http://cdz.evcharge.cc/zhannew/basic/web/index.php/duiba/active?token=" + replace + "&url=" + url);    //配置自动登陆地址,每次需服务端动态生成。
        } else {
            intent11.putExtra("url", "http://cdz.evcharge.cc/zhannew/basic/web/index.php/duiba/active?user_id=" + MainApplication.userId + "&token=" + replace + "&url=" + url);    //配置自动登陆地址,每次需服务端动态生成。
        }
        startActivity(intent11);

        overridePendingTransition(0, 0);

        CreditActivity.creditsListener = new CreditActivity.CreditsListener() {
            /**
             * 当点击分享按钮被点击
             * @param shareUrl 分享的地址
             * @param shareThumbnail 分享的缩略图
             * @param shareTitle 分享的标题
             * @param shareSubtitle 分享的副标题
             */
            public void onShareClick(WebView webView, String shareUrl, String shareThumbnail, String shareTitle, String shareSubtitle) {
                //当分享按钮被点击时,会调用此处代码。在这里处理分享的业务逻辑。
                ChargingShareBean chargingShareBean = new ChargingShareBean();
                chargingShareBean.setIcon(shareThumbnail);
                chargingShareBean.setTitle(shareTitle);
                chargingShareBean.setUrl(shareUrl);
                chargingShareBean.setText("");


                showSimpleBottomSheetGrid(chargingShareBean);
            }

            /**
             * 当点击“请先登录”按钮唤起登录时,会调用此处代码。
             * 用户登录后,需要将CreditsActivity.IS_WAKEUP_LOGIN变量设置为true。
             * @param webView 用于登录成功后返回到当前的webview刷新登录状态。
             * @param currentUrl 当前页面的url
             */
            public void onLoginClick(WebView webView, final String currentUrl) {
                //当未登录的用户点击去登录时,会调用此处代码。
                //用户登录后,需要将CreditsActivity.IS_WAKEUP_LOGIN变量设置为true。
                //为了用户登录后能回到未登录前的页面(currentUrl)。
                //当用户登录成功后,需要重新请求一次服务端,带上currentUrl。
                //用该方法中的webview变量加载请求链接。
                //服务端收到请求后在生成免登录url时,将currentUrl放入redirect参数,通知客户端302跳转到新生成的免登录URL。
                new AlertDialog.Builder(webView.getContext())
                        .setTitle("跳转登录")
                        .setMessage("跳转到登录页面?")
                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                MainApplication.h5_url = currentUrl;
                                startActivity(new Intent(getApplicationContext(), LoginActivity.class));

                            }
                        })
                        .setNegativeButton("否", null)
                        .show();
            }

            /**
             * 当点击“复制”按钮时,触发该方法,回调获取到券码code
             * @param webView webview对象。
             * @param code 复制的券码
             */
            public void onCopyCode(WebView webView, String code) {
                //当未登录的用户点击去登录时,会调用此处代码。
                new AlertDialog.Builder(webView.getContext())
                        .setTitle("复制券码")
                        .setMessage("已复制,券码为:" + code)
                        .setPositiveButton("是", null)
                        .setNegativeButton("否", null)
                        .show();
            }

            /**
             * 积分商城返回首页刷新积分时,触发该方法。
             */
            public void onLocalRefresh(WebView mWebView, String credits) {
                //String credits为积分商城返回的最新积分,不保证准确。
                //触发更新本地积分,这里建议用ajax向自己服务器请求积分值,比较准确。
            }
        };
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        WebBackForwardList mWebBackForwardList = webView.copyBackForwardList();
        Log.e("tag", "mWebBackForwardList.getSize() " + mWebBackForwardList.getSize());
        if (webView.canGoBack()) {
            webView.goBack();
            iv_webBack.setVisibility(View.VISIBLE);
        } else {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtil.showToast(getApplicationContext(), "分享成功", Toast.LENGTH_SHORT);
            }
        });
        ToastUtil.showToast(getApplicationContext(), "分享成功", Toast.LENGTH_SHORT);
        getShareIntegral();
    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtil.showToast(getApplicationContext(), "分享失败", Toast.LENGTH_SHORT);
            }
        });

    }

    @Override
    public void onCancel(Platform platform, int i) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtil.showToast(getApplicationContext(), "分享已取消", Toast.LENGTH_SHORT);
            }

        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_webview_share:
                if (tv_webShare.getText().toString().equals("分享")) {
                    if (null != shareIcon && null != shareUrl && null != shareTitle && null != shareContext) {
                        btnToShare();
                    }
                } else if (tv_webShare.getText().toString().equals("我的反馈")) {
                    if (MainApplication.isLogin()) {
                        Intent i = new Intent(getApplicationContext(), MyFeedbackActivity.class);
                        startActivity(i);
                    } else {
                        startActivity(new Intent(getApplicationContext(), LoginActivity.class));
                        ToastUtil.showToast(getApplicationContext(), "请先登录", Toast.LENGTH_SHORT);
                        index = "100";
                    }

                } else {
                    runOnUiThread(new Runnable() {
                        @TargetApi(Build.VERSION_CODES.KITKAT)
                        @Override
                        public void run() {
                            webView.evaluateJavascript("window.myglobal.resetrctext()", new ValueCallback<String>() {
                                @Override
                                public void onReceiveValue(String arg0) {

                                }
                            });
                        }
                    });
                }
                break;
            case R.id.iv_webview_back:
                WebBackForwardList mWebBackForwardList = webView.copyBackForwardList();
                Log.e("tag", "mWebBackForwardList.getSize() " + mWebBackForwardList.getSize());
                if (webView.canGoBack()) {
                    webView.goBack();
                    iv_webClose.setVisibility(View.VISIBLE);
                } else {
                    finish();
                }
                break;
            case R.id.iv_webview_close:
                finish();
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // EasyPermissions handles the request result.
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == RC_ALBUM_PERM) {
            mOpenFileWebChromeClient.mFilePathCallback = null;
            mOpenFileWebChromeClient.mFilePathCallbacks = null;
        }
    }

    private boolean hasCallPhonePermission() {
        return EasyPermissions.hasPermissions(this, Manifest.permission.CALL_PHONE);
    }

    public class OpenFileWebChromeClient extends WebChromeClient {
        public static final int REQUEST_FILE_PICKER = 1;
        public ValueCallback<Uri> mFilePathCallback;
        public ValueCallback<Uri[]> mFilePathCallbacks;
        Activity mContext;

        public OpenFileWebChromeClient(Activity mContext) {
            super();
            this.mContext = mContext;
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            Log.d("ANDROID_LAB", "TITLE=" + title);
            tv_webTitle.setText(title);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            pb_webBar.setProgress(newProgress);
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(String origin,
                                                       GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
            super.onGeolocationPermissionsShowPrompt(origin, callback);
        }

        // Android < 3.0 调用这个方法
        public void openFileChooser(ValueCallback<Uri> filePathCallback) {
            mFilePathCallback = filePathCallback;
            permissionTask();
        }

        // 3.0 + 调用这个方法
        public void openFileChooser(ValueCallback filePathCallback, String acceptType) {
            mFilePathCallback = filePathCallback;
            permissionTask();
        }

        // / js上传文件的<input type="file" name="fileField" id="fileField" />事件捕获
        // Android > 4.1.1 调用这个方法
        public void openFileChooser(ValueCallback<Uri> filePathCallback, String acceptType, String capture) {
            mFilePathCallback = filePathCallback;
            permissionTask();
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            mFilePathCallbacks = filePathCallback;
            permissionTask();
            return true;
        }
    }

    @AfterPermissionGranted(RC_ALBUM_PERM)
    public void permissionTask() {
        if (isPermissionOK()) {
            openImageChooserActivity();
        } else {
            EasyPermissions.requestPermissions(
                    this, "充电桩想要获取您的图片读取权限,是否允许?",
                    RC_ALBUM_PERM,
                    Manifest.permission.CAMERA,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE);
        }
    }

    private boolean isPermissionOK() {
        return EasyPermissions.hasPermissions(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA
        );
    }

    private void openImageChooserActivity() {
        new MaterialDialog.Builder(this).items(R.array.photo).positiveText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (mOpenFileWebChromeClient.mFilePathCallbacks != null) {
                            mOpenFileWebChromeClient.mFilePathCallbacks.onReceiveValue(null);
                            mOpenFileWebChromeClient.mFilePathCallbacks = null;
                        }

                        if (mOpenFileWebChromeClient.mFilePathCallback != null) {
                            mOpenFileWebChromeClient.mFilePathCallback.onReceiveValue(null);
                            mOpenFileWebChromeClient.mFilePathCallback = null;
                        }
                        dialog.dismiss();
                    }
                }).cancelable(false)
                .canceledOnTouchOutside(false).itemsCallback(new MaterialDialog.ListCallback() {
            @Override
            public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) {
                if (position == 0) {
                    takeCamera();
                } else if (position == 1) {
                    takePhoto();
                }
            }
        }).show();
    }

    // 选择图片
    private void takePhoto() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        startActivityForResult(Intent.createChooser(intent, "Image Choose"), FILE_CHOOSER_RESULT_CODE);
    }

    // 拍照
    private void takeCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (ImageUitl.hasSdcard()) {
            String fileName = "android" + System.currentTimeMillis() / 1000 + ".jpg";
            cameraFilePath = ImageUitl.getPath(Environment.getExternalStorageDirectory() + "/" + "cdz") + "/" + fileName;
            File imageFile = ImageUitl.getFile(cameraFilePath);
            Uri uri = parseUri(imageFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            try {
                startActivityForResult(intent, FILE_CAMERA_RESULT_CODE);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    private Uri parseUri(File cameraFile) {
        Uri imageUri;
        String authority = getPackageName() + ".provider";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //通过FileProvider创建一个content类型的Uri
            imageUri = FileProvider.getUriForFile(getApplicationContext(), authority, cameraFile);
        } else {
            imageUri = Uri.fromFile(cameraFile);
        }
        return imageUri;
    }

    public class MyWebViewClient extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            Log.e(TAG, "onPageStarted: " + url);
            pb_webBar.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            Log.e(TAG, "onPageFinished: " + url);
            currentUrl = url;
            pb_webBar.setVisibility(View.GONE);

        }

        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            //handler.cancel(); // Android默认的处理方式
            handler.proceed();  // 接受所有网站的证书
            //handleMessage(Message msg); // 进行其他处理
        }

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.e(TAG, "onPage1 :" + url);
            //  重写此方法表明点击网页里面的链接还是在当前的webview里跳转,不跳到浏览器那边
//                view.loadUrl(url);
            if (url.startsWith("http://cdz.evcharge.cc/zhannew/basic/web/index.php/drive/wxpay?")) {
                try {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                } catch (ActivityNotFoundException e) {
                }
            } else if (url.startsWith("tel:")) {
                Intent intent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse(url));
                startActivity(intent);
                return true;
            } else {
                Log.e(TAG, "shouldOverrideUrlLoading: 1");
                view.loadUrl(url);
            }
            return false;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (null == mOpenFileWebChromeClient.mFilePathCallback && null == mOpenFileWebChromeClient.mFilePathCallbacks)
            return;
        if (resultCode != RESULT_OK) {
            if (mOpenFileWebChromeClient.mFilePathCallbacks != null) {
                mOpenFileWebChromeClient.mFilePathCallbacks.onReceiveValue(null);
                mOpenFileWebChromeClient.mFilePathCallbacks = null;
            }

            if (mOpenFileWebChromeClient.mFilePathCallback != null) {
                mOpenFileWebChromeClient.mFilePathCallback.onReceiveValue(null);
                mOpenFileWebChromeClient.mFilePathCallback = null;
            }
            return;
        }

        Uri result = null;
        if (requestCode == FILE_CAMERA_RESULT_CODE) {
            if (null != data && null != data.getData()) {
                result = data.getData();
            }
            if (result == null && ImageUitl.hasFile(cameraFilePath)) {
                result = Uri.fromFile(new File(cameraFilePath));
            }

            if (mOpenFileWebChromeClient.mFilePathCallbacks != null) {
                mOpenFileWebChromeClient.mFilePathCallbacks.onReceiveValue(new Uri[]{result});
                mOpenFileWebChromeClient.mFilePathCallbacks = null;
            } else if (mOpenFileWebChromeClient.mFilePathCallback != null) {
                mOpenFileWebChromeClient.mFilePathCallback.onReceiveValue(result);
                mOpenFileWebChromeClient.mFilePathCallback = null;
            }
        } else if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (data != null) {
                result = data.getData();
            }
            if (mOpenFileWebChromeClient.mFilePathCallbacks != null) {
                onActivityResultCallbacks(data);
            } else if (mOpenFileWebChromeClient.mFilePathCallback != null) {
                mOpenFileWebChromeClient.mFilePathCallback.onReceiveValue(result);
                mOpenFileWebChromeClient.mFilePathCallback = null;
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultCallbacks(Intent intent) {
        Uri[] results = null;
        if (intent != null) {
            String dataString = intent.getDataString();
            ClipData clipData = intent.getClipData();
            if (clipData != null) {
                results = new Uri[clipData.getItemCount()];
                for (int i = 0; i < clipData.getItemCount(); i++) {
                    ClipData.Item item = clipData.getItemAt(i);
                    results[i] = item.getUri();
                }
            }
            if (dataString != null) {
                results = new Uri[]{Uri.parse(dataString)};
            }
            mOpenFileWebChromeClient.mFilePathCallbacks.onReceiveValue(results);
            mOpenFileWebChromeClient.mFilePathCallbacks = null;
        }
    }

    private void getShareIntegral() {
        String url = MainApplication.url + "/zhannew/basic/web/index.php/member/insert-task?userid=" + MainApplication.userId;
        OkHttpUtils.get().url(url).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                Log.e(TAG, "onResponse: getShareIntegral=" + response);
                String rtnCode = JsonUtils.getKeyResult(response, "rtnCode");
                if ("01".equals(rtnCode)) {
                    String plusScore = JsonUtils.getKeyResult(response, "plusScore");
                    if (!plusScore.equals("")) {
                        tv_point.setText(plusScore);
                        rl_point.setVisibility(View.VISIBLE);
                        rl_point.startAnimation(animation);
                        new Handler().postDelayed(new Runnable() {
                            public void run() {
                                rl_point.setVisibility(View.GONE);
                            }
                        }, 1500);
                    }

                } else {
                    ToastUtil.showToast(getApplicationContext(), "分享成功", Toast.LENGTH_SHORT);
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        list.clear();
    }

    /**
     * 获取车主认证信息
     */
    private void getCarOwnerCertificateList() {
        long tokenTime = System.currentTimeMillis() / 1000 - MainMapActivity.cha - 1;
        String token = null;
        try {
            token = DES3.encode(String.valueOf(tokenTime));
            token = URLEncoder.encode(token, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }

        String url = MainApplication.url + "/zhannew/basic/web/index.php/car/my?userid=" + MainApplication.userId + "&order=1" + "&token=" + token;
        OkHttpUtils.get().url(url).build().connTimeOut(6000).readTimeOut(6000).execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @TargetApi(Build.VERSION_CODES.KITKAT)
                    @Override
                    public void run() {
                        loadDialog.dismiss();
                    }
                });

                Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response) {
                runOnUiThread(new Runnable() {
                    @TargetApi(Build.VERSION_CODES.KITKAT)
                    @Override
                    public void run() {
                        loadDialog.dismiss();
                    }
                });
                String rtnCode = JsonUtils.getKeyResult(response, "rtnCode");
                if ("01".equals(rtnCode)) {
                    String data = JsonUtils.getKeyResult(response, "data");
                    List<CarOwnerCertificateBean> list = JsonUtils.parseToObjectList(data, CarOwnerCertificateBean.class);
                    if (list.size() == 0) {
                        startActivity(new Intent(getApplication(), CarOwnerCertificateActivity.class));
                    } else {
                        Intent intent = new Intent(getApplication(), CarOwnerCertificateListActivity.class);
                        intent.putExtra("data", data);
                        startActivity(intent);
                    }
                } else {
                    String rtnMsg = JsonUtils.getKeyResult(response, "rtnMsg");
                    Toast.makeText(getApplicationContext(), rtnMsg, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}