package com.ruansee.macall.testwebview.app;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.URLUtil;
import android.webkit.ValueCallback;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.widget.TextView;

import com.just.agentweb.WebChromeClient;
import com.just.agentweb.WebViewClient;
import com.rs.macall.androidx.basemodel.base.BasePresenter;
import com.rs.macall.androidx.basemodel.callback.CustomClickListener;
import com.rs.macall.androidx.basemodel.utils.BitMapUtils;
import com.rs.macall.androidx.basemodel.utils.LogUtils;
import com.rs.macall.androidx.basemodel.utils.StringUtil;
import com.ruansee.macall.testwebview.R;
import com.ruansee.macall.testwebview.model.SelectFileOptions;
import com.ruansee.macall.testwebview.provider.DownloadUtil;
import com.ruansee.macall.testwebview.utils.FileUtils;
import com.ruansee.macall.testwebview.utils.UriUtils;

import java.io.File;

import top.zibin.luban.OnCompressListener;

import static android.content.Context.DOWNLOAD_SERVICE;

/**
 * created by:   Macall
 * create time:  2022/11/21 17:26
 * copyright:    @ruansee.com
 * Describe:
 */
public class WebViewPresenter extends BasePresenter<WebActivityCallback> {
    public File photoFile;
    public final static int RESULT_CODE = 10000;
    public final static int SELECT_IMG_CODE = 10001;
    public final static int SELECT_FILE_CODE = 10002;
    public SelectFileOptions selectFileOptions;
    private String fileTypes;
    private Dialog selectItems;
    private boolean isLogin = false;
    public String ywryName = "", ywryPhone = "";

    public String intoUrl = "http://20.90.1.150:8888/";
//    public Map<String, SelectFileOptions> selectFileOptionsMap;

    public ValueCallback<Uri[]> mFilePathCallback;

    public WebViewPresenter(Context context, WebActivityCallback callback) {
        super(context, callback);
//        selectFileOptionsMap = new HashMap<>();
    }

    public void onDestroy() {

    }
    /**
     * 相机拍照
     *
     * @param activity 当前活动
     */
    private void skipPickPhoto(Activity activity) {
        if (photoFile != null && photoFile.exists()) {
            photoFile.delete();
        }
        photoFile = new File(FileUtils.IMAGE_DIR, FileUtils.getPhotoName());
        Intent photoIntent = UriUtils.getPhotoIntent(activity, photoFile);
        activity.startActivityForResult(photoIntent, RESULT_CODE);
    }

    private void showSelectUploadDialog() {
        if (selectFileOptions.onlyOneItemIsSelected()) {
            if (selectFileOptions.isCamera()) {
                callBack.onShowOperationSelectDialog(new String[]{"相机"}, 0);
                return;
            }
            if (selectFileOptions.isDCIM()) {
                callBack.onShowOperationSelectDialog(new String[]{"相册"}, 0);
                return;
            }
            if (selectFileOptions.isFileSelection()) {
                callBack.onShowOperationSelectDialog(new String[]{"文件选择"}, 0);
                return;
            }
        }
        int a = View.GONE, b = View.GONE, c = View.GONE;
        StringBuilder builder = new StringBuilder();
        String sp = "";
        if (selectFileOptions.isCamera()) {
            builder.append(sp);
            builder.append("相机");
            a = View.VISIBLE;
            sp = ",";
        }
        if (selectFileOptions.isDCIM()) {
            builder.append(sp);
            builder.append("相册");
            b = View.VISIBLE;
            sp = ",";
        }
        if (selectFileOptions.isFileSelection()) {
            builder.append(sp);
            builder.append("文件选择");
            c = View.VISIBLE;
        }
        String str = builder.toString();
        if (StringUtil.isNullOrEmpty(str)) {
            str = "相机,相册,文件选择";
        }
        final String[] split = str.split(",");
        if (selectItems == null) {
            View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_select_items, null, false);
            selectItems = new AlertDialog.Builder(getContext())
                    .setView(view)
                    .setOnCancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            mFilePathCallback.onReceiveValue(null);
                            mFilePathCallback = null;
                        }
                    })
                    .create();
        }
        selectItems.show();
        TextView tv_title = selectItems.findViewById(R.id.tv_title);
        tv_title.setText("选择操作方式");
        View tv_xj = selectItems.findViewById(R.id.tv_xj);
        tv_xj.setVisibility(a);
        View tv_xc = selectItems.findViewById(R.id.tv_xc);
        tv_xc.setVisibility(b);
        View tv_wjxz = selectItems.findViewById(R.id.tv_wjxz);
        tv_wjxz.setVisibility(c);
        tv_xj.setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                selectItems.dismiss();
                callBack.onShowOperationSelectDialog(new String[]{"相机"}, 0);
            }
        });
        tv_xc.setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                selectItems.dismiss();
                callBack.onShowOperationSelectDialog(new String[]{"相册"}, 0);
            }
        });
        tv_wjxz.setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                selectItems.dismiss();
                callBack.onShowOperationSelectDialog(new String[]{"文件选择"}, 0);
            }
        });
    }

    /**
     * 显示选择文件弹框
     *
     * @param whit 可操作的项
     *             1表示 只能相机拍照，将直接打开系统相机
     *             2表示  提供相机拍照、相册选取两个选项
     *             3表示  文件选取
     */
    public void onShowOperationSelectDialog(Activity activity, int whit, String[] split) {
        String s = split[whit];
        switch (s) {
            case "相机":
                skipPickPhoto(activity);
                break;
            case "相册":
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, fileTypes);
                intent.setType(fileTypes);
                activity.startActivityForResult(intent, SELECT_IMG_CODE);
                break;
            case "文件选择":
                intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType(fileTypes);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                activity.startActivityForResult(intent, SELECT_FILE_CODE);
                break;
        }
    }

    /**
     * 下载文件
     *
     * @param url              文件URL
     * @param fileName         文件名称
     * @param downloadListener 下载监听
     */
    public void downloadFile(String url, String fileName, DownloadUtil.OnDownloadListener downloadListener) {
//        ApiModel.request(RetrofitService.getBaseInstance().downFile(url), new BaseRequestCallback<ResponseBody>() {
//            @Override
//            public void onRequestFailure(String msg) {
//                // 下载失败
//                downloadListener.onDownloadFailed(msg);
//            }
//
//            @Override
//            public void onRequestSuccess(ResponseBody result) {
//                try {
//                    DownloadUtil.get().handDownFile(url,FileUtils.DOWNLOADS_DIR,result,fileName,downloadListener);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                    // 下载失败
//                    downloadListener.onDownloadFailed(e.getMessage());
//                }
//            }
//        });
        DownloadUtil.get().download(url, FileUtils.DOWNLOADS_DIR, fileName, downloadListener);
    }

    public WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            //do you  work
            LogUtils.w(String.format("onPageStarted :  url=%s", url));
            if (url.startsWith(intoUrl) || url.startsWith("http://localhost")) {
                if (isLogin) {
                    callBack.onFinish();
                }
                isLogin = true;
            }
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            //net::ERR_NAME_NOT_RESOLVED  -2   网页超时加载 执行这个回调
//            showLoadWebError("应用加载超时，请联系管理员排查系统。",ywryName,ywryPhone);
        }

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            //内部系统 沒有用用户
//            errorResponse.getStatusCode() == 404;
//            if(errorResponse.getStatusCode() == 404){
//                showLoadWebError("应用加载失败，用户没有权限，请联系管理添加权限。",ywryName,ywryPhone);
//            }else {
            super.onReceivedHttpError(view, request, errorResponse);
//            }
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            super.onReceivedSslError(view, handler, error);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            view.getSettings().setBlockNetworkImage(false);
            super.onPageFinished(view, url);
        }
    };

    public WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            //do you work
            super.onProgressChanged(view, newProgress);
            if (newProgress>=100){
                view.getSettings().setBlockNetworkImage(false);
            }
            LogUtils.w(TAG, String.format("onProgressChanged :  newProgress=%s", newProgress));
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            //设置弹窗
            AlertDialog.Builder b = new AlertDialog.Builder(getContext());
            b.setTitle("Alert");
            b.setMessage(message);
            b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    result.confirm();
                }
            });
            b.setCancelable(true);
            b.create().show();
            return true;
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            mFilePathCallback = filePathCallback;
            if (fileChooserParams != null) {
                if (fileChooserParams.getAcceptTypes() != null
                        && fileChooserParams.getAcceptTypes().length > 0) {
                    StringBuilder builder = new StringBuilder();
                    String sp = "";
                    for (int i = 0; i < fileChooserParams.getAcceptTypes().length; i++) {
                        builder.append(sp);
                        builder.append(fileChooserParams.getAcceptTypes()[0]);
                        sp = ";";
                    }
                    fileTypes = builder.toString();
                }
            }
            if (StringUtil.isNullOrEmpty(fileTypes)) {
                fileTypes = "*/*";
            }
            if (selectFileOptions == null) {
                selectFileOptions = new SelectFileOptions(false, true, true, true);
            }
            if (selectFileOptions.isSelfRealization()) {
                return super.onShowFileChooser(webView, filePathCallback, fileChooserParams);
            }
            showSelectUploadDialog();
            return true;
        }
    };


    public void showLoadWebError(String titleStr, String msg, String lxryName, String lxryPhone) {
        if (StringUtil.isNullOrEmpty(titleStr)){
            titleStr = "温馨提示";
        }
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_h5_error, null, false);
        Dialog insertTips = new AlertDialog.Builder(getContext())
                .setView(view)
                .create();
        insertTips.show();
        TextView title = insertTips.findViewById(R.id.textView2);
        title.setText(titleStr);
        TextView tvMsg = insertTips.findViewById(R.id.tv_msg);
        TextView tvYwry = insertTips.findViewById(R.id.tv_wery);
        TextView tvPhone = insertTips.findViewById(R.id.tv_ywrydh);
        tvMsg.setText(msg);
        String name = "暂无";
        String lxdh ="暂无";
        if (StringUtil.isNullOrEmpty(lxryName)) {
            if (StringUtil.hasContent(ywryName)) {
                name =ywryName;
                if (StringUtil.hasContent(ywryPhone)){
                    lxdh = ywryPhone;
                }
            }
        }else {
            name = lxryName;
            lxdh= StringUtil.isNullOrEmpty(lxryPhone)?"暂无":lxryPhone;
        }
        tvYwry.setText(name+"：");
        tvPhone.setText(lxdh);
        insertTips.findViewById(R.id.btn_determine).setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                insertTips.dismiss();
                callBack.onFinish();
            }
        });
    }

    /**
     * 处理选择相册和选择文件
     *
     * @param requestCode
     * @param resultCode
     * @param intent
     */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            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)};
            }
            mFilePathCallback.onReceiveValue(results);
            mFilePathCallback = null;
        } else {
            mFilePathCallback.onReceiveValue(null);
            mFilePathCallback = null;
        }
    }

    /**
     * 压缩图片
     */
    public void ysBitmap() {
        BitMapUtils.lubanCompress(getContext(), photoFile, FileUtils.IMAGE_DIR, new OnCompressListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(File file) {
                if (!file.getAbsolutePath().equals(photoFile.getAbsolutePath())) {
                    photoFile.delete();
                    photoFile = file;
                }
                Uri ph = UriUtils.getUri(getContext(), file);
                Uri[] uris = new Uri[]{ph};
                mFilePathCallback.onReceiveValue(uris);
                mFilePathCallback = null;
            }

            @Override
            public void onError(Throwable e) {
                mFilePathCallback.onReceiveValue(null);
                mFilePathCallback = null;

            }
        });
    }

    /**
     * 浏览器下载
     *
     * @param url
     */
    private void downloadByBrowser(String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_BROWSABLE);
        intent.setData(Uri.parse(url));
        getContext().startActivity(intent);
    }

    /**
     * 系统下载服务下载
     *
     * @param url
     * @param contentDisposition
     * @param mimeType
     */
    public void downloadBySystem(String url, String contentDisposition, String mimeType) {
        // 指定下载地址
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        // 允许媒体扫描，根据下载的文件类型被加入相册、音乐等媒体库
        request.allowScanningByMediaScanner();
        // 设置通知的显示类型，下载进行时和完成后显示通知
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        // 设置通知栏的标题，如果不设置，默认使用文件名
//        request.setTitle("This is title");
        // 设置通知栏的描述
//        request.setDescription("This is description");
        // 允许在计费流量下下载
        request.setAllowedOverMetered(false);
        // 允许该记录在下载管理界面可见
        request.setVisibleInDownloadsUi(false);
        // 允许漫游时下载
        request.setAllowedOverRoaming(true);
        // 允许下载的网路类型
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        // 设置下载文件保存的路径和文件名
        String fileName = URLUtil.guessFileName(url, contentDisposition, mimeType);
        LogUtils.d("fileName:{}", fileName);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
//        另外可选一下方法，自定义下载路径
//        request.setDestinationUri()
//        request.setDestinationInExternalFilesDir()
        final DownloadManager downloadManager = (DownloadManager) getContext().getSystemService(DOWNLOAD_SERVICE);
        // 添加一个下载任务
        long downloadId = downloadManager.enqueue(request);
        LogUtils.d("downloadId:{}", downloadId + "");
    }


    /**
     * 打开GPS
     */
//    private void openGPSSettings() {
//        LocationManager alm = (LocationManager) context
//                .getSystemService(Context.LOCATION_SERVICE);
//        if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
//            Toast.makeText(context, "GPS模块正常", Toast.LENGTH_SHORT).show();
////            baiDuMapManager.startLocation();
//            return;
//        } else {
//            Toast.makeText(context, "请开启GPS！", Toast.LENGTH_SHORT).show();
//            Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
//            startActivityForResult(intent, 0); // 此为设置完成后返回到获取界面
//        }
//    }
}
