package com.sjkj.appthreefloor_tsgz.web;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.webkit.JavascriptInterface;
import android.webkit.PermissionRequest;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.lifecycle.ViewModelProvider;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.king.zxing.util.LogUtils;
import com.sjkj.appthreefloor_tsgz.R;
import com.sjkj.appthreefloor_tsgz.databinding.ActivityWebViewBinding;
import com.sjkj.base_lib.utils.AppTools;
import com.sjkj.base_lib.utils.ToastUtils;
import com.sjkj.base_lib.view.BaseActivity;
import com.sjkj.base_lib.app.AppManager;
import com.tencent.mmkv.MMKV;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.util.List;

public class WebViewActivity extends BaseActivity {

    private WebViewModel model;
    private ActivityWebViewBinding binding;
    private String url;
    private String enterpriseId, dangerSource;
    private MMKV mmkv = MMKV.defaultMMKV();

    @Override
    public int initLayout() {
        return R.layout.activity_web_view;
    }

    @Override
    public void initBinding() {
        binding = (ActivityWebViewBinding) getViewDataBinding();
        model = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(WebViewModel.class);
        binding.setLifecycleOwner(this);
    }

    @Override
    public void initView() {
        url = getIntent().getStringExtra("url");
        if (getIntent().hasExtra("enterpriseId")) {
            enterpriseId = getIntent().getStringExtra("enterpriseId");
        }
        binding.webView.addJavascriptInterface(this, "$App");
        //localStorage  允许存储
//        binding.webView.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);//存储的最大容量
//        String appCachePath = getCacheDir().getAbsolutePath();
//        binding.webView.getSettings().setAppCachePath(appCachePath);
//        binding.webView.getSettings().setAllowFileAccess(true);
//        binding.webView.getSettings().setAppCacheEnabled(true);

        WebSettings webSettings = binding.webView.getSettings();
        //如果访问的页面中要与Javascript交互，则webView必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);
        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webView的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setGeolocationEnabled(true);
        webSettings.setDomStorageEnabled(true);
        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        //其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); //关闭webView中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        binding.webView.setScrollContainer(true);

        binding.webView.loadUrl(url);

        binding.webView.requestFocus();
//        binding.webView.setScrollBarStyle(0);
        binding.webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                try {
                    if (url.startsWith("http:") || url.startsWith("https:")) {
                        view.loadUrl(url);
                    } else {
                    }
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
            }

        });
        binding.webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onPermissionRequest(PermissionRequest request) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    request.grant(request.getResources());
                }
//                super.onPermissionRequest(request);
            }

            @Override
            public void onPermissionRequestCanceled(PermissionRequest request) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    LogUtils.e("TAG" + "取消的权限" + request.getResources().length);
                }
//                super.onPermissionRequestCanceled(request);
            }
        });
    }


    @Override
    public void initListener() {
    }

    @Override
    public void loadData() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // 先判断有没有权限
            if (Environment.isExternalStorageManager()) {

            } else {
//                RequestPermissions.obtainPermission(this, ConstantPermission.MANAGE_EXTERNAL_STORAGE, new PermissionCallback() {
//                @Override
//                public void onSuccess() {
//
//                }
//
//                @Override
//                public void onFailure() {
//
//                }
//            });
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.setData(Uri.parse("package:" + this.getPackageName()));
                startActivityForResult(intent, 1111);
            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == 100 && resultCode == RESULT_OK) {
//            List<Uri> result = Matisse.obtainResult(data);
//            uploadFile(result.get(0));
//        }
    }

    @JavascriptInterface
    public void obtainImage() {
        XXPermissions.with(this)
                .permission(Permission.CAMERA)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            Matisse.from(WebViewActivity.this)
                                    .choose(MimeType.ofImage())//图片类型
                                    .countable(true)//true:选中后显示数字;false:选中后显示对号
                                    .maxSelectable(1)//可选的最大数
                                    .capture(true)//选择照片时，是否显示拍照
                                    .captureStrategy(new CaptureStrategy(false, AppTools.getPackageNameProvider()))//参数1 true表示拍照存储在共有目录，false表示存储在私有目录；参数2与 AndroidManifest中authorities值相同，用于适配7.0系统 必须设置
                                    .imageEngine(new GlideEngine())//图片加载引擎
                                    .forResult(100);
                        } else {
                            ToastUtils.show("获取部分权限成功，但部分权限未正常授予");
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            ToastUtils.show("被永久拒绝授权，请手动授予权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(AppManager.getAppManager().currentActivity(), permissions);
                        } else {
                            ToastUtils.show("获取权限失败");
                        }
                    }
                });

    }

//    //下载打开文件
//    @JavascriptInterface
//    public void downloadFileAndOpen(String fileUrl) {
////        String pathString = "http://202.111.178.254:9004/efa310bd-28d9-4978-8f4d-02020bb87e29.doc";
//        if (TextUtils.isEmpty(fileUrl)) {
//            ToastUtils.show("文件路径有误");
//            return;
//        }
//        try {
//            String currentFileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1, fileUrl.length());
//            HttpTools.downloadFile(WebViewActivity.this, fileUrl, currentFileName);
//        } catch (Exception e) {
//            ToastUtils.show("文件加载失败，请重试");
//            e.printStackTrace();
//        }
//    }

//    private void uploadFile(Uri uri) {
//        String path = RealPathFromUriUtils.getRealPathFromUri(this, uri);
//        File file = new File(path);
//        if (file.exists()) {
//            ProgressHelper.show(this);
//            HttpTools.uploadFile(this, URLConfig.getInstance().getUpload() + "upload", file, new UploadResponseListener() {
//                @Override
//                public void onSuccess(JSONObject response) {
//                    ProgressHelper.hide();
//                    try {
//                        if (TextUtils.equals("200", response.optString("code"))) {
//                            String url = response.optJSONObject("data").optString("url");
//                            String webUrl = response.optJSONObject("data").optString("webUrl");
//                            LogUtils.e("uploadFile_" + webUrl);
//                            callBack(url, webUrl);
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                        ToastUtils.show("上传文件失败");
//                    }
//                }
//
//                @Override
//                public void onProgress() {
//
//                }
//
//                @Override
//                public void onFailure(String result) {
//                    ProgressHelper.hide();
////                    ToastUtils.show(result);
//                    ToastUtils.show("上传文件失败");
//                }
//            });
//        } else {
//            ToastUtils.show("上传文件失败");
//        }
//    }

    public void callBack(String url, String webUrl) {
        binding.webView.post(() -> binding.webView.loadUrl("javascript:onImagePath('" + url + "','" + webUrl + "')"));
    }
//
//    @JavascriptInterface
//    public void inspectionFinishPage(String dangerSourceId, String information) {
//        startActivity(new Intent(this, SuccessInspectionActivity.class)
//                .putExtra("enterpriseId", enterpriseId)
//                .putExtra("information", information)
//                .putExtra("dangerSourceId", dangerSourceId));
//        finish();
//    }

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

    @JavascriptInterface
    public void getDeptId() {
//        ToastUtils.show( "deptId:"+mmkv.decodeString("deptId") );
        if (mmkv != null) {
            binding.webView.post(() -> binding.webView.loadUrl("javascript:deptIdResult('" + mmkv.decodeString("deptId") + "')"));
        }
    }

    @JavascriptInterface
    public void getAccessToken() {
//        ToastUtils.show( "access_token:"+mmkv.decodeString(ACCESS_TOKEN) );
        if (mmkv != null) {
            binding.webView.post(() -> binding.webView.loadUrl("javascript:accessTokenResult('" + mmkv.decodeString(AppTools.ACCESS_TOKEN) + "')"));
        }
    }

//    @JavascriptInterface
//    public void startNavLocation() {
//        LocationUtil.getInstance().startLocation(aMapLocation -> {
////            double userLat = Constant.DEFAULT_LAT, userLog = Constant.DEFAULT_LON;
////            String address = "";
////            ToastUtils.show(aMapLocation.getLatitude() + "," + aMapLocation.getLongitude() + "," + aMapLocation.getAddress());
//            try {
//                binding.webView.post(() -> binding.webView.loadUrl("javascript:navLocationResult('" + aMapLocation.getLatitude() + "','" + aMapLocation.getLongitude() + "','" + aMapLocation.getAddress() + "')"));
//            } catch (Exception e) {
//                ToastUtils.show(e.getMessage());
//                e.printStackTrace();
//            }
//        }, true);
//    }
}