package com.sipai.jspatrol.Webv;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.WindowManager;
import android.webkit.URLUtil;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.sipai.jspatrol.R;
import com.sipai.jspatrol.URL.MethodURL;
import com.sipai.jspatrol.utils.AndroidFileUtil;
import com.sipai.jspatrol.utils.FileProvider7;
import com.sipai.jspatrol.utils.okHttpCookie.CookiesManager;
import com.sipai.ui.TitleLayout;
import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.DownloadListener;
import com.tencent.smtt.sdk.MimeTypeMap;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import org.xutils.x;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class MonitorScreenActivity extends AppCompatActivity {
    private String url;
    private String name;
    private WebView webView;
    private SwipeRefreshLayout refresh;
    private SweetAlertDialog pDialog;
    private String cookies;
    private String fileabspath = "";
    private ProgressDialog progressDialog;
    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> uploadMessage; // 用于5.0以上
    final static int FILE_SELECTED = 4;
    public static final int REQUEST_SELECT_FILE = 100;
    private TitleLayout titleLayout;

    public static void actionStart(Context context, String url, String name) {
        Intent intent = new Intent(context, MonitorScreenActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("name", name);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_guide_menu);
        init();
        initView();
    }

    private void initView() {
        titleLayout = findViewById(R.id.moudle_guide_menu_ui_title);
        titleLayout.setVisibility(View.GONE);
        TextView tv_title = (TextView) findViewById(R.id.moudle_back_title_tv_title);
        tv_title.setText(name);
        ImageView btn_back = (ImageView) findViewById(R.id.moudle_back_title_iv_back);
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
        pDialog.getProgressHelper().setBarColor(Color.parseColor("#419DE4"));
        pDialog.setCancelable(true);
        pDialog.setCanceledOnTouchOutside(true);
        progressDialog = new ProgressDialog(this);
        webView = (WebView) findViewById(R.id.moudle_guide_menu_webview);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setDomStorageEnabled(true);
        //设置自适应屏幕，两者合用
        webView.getSettings().setUseWideViewPort(true); //将图片调整到适合webview的大小
        webView.getSettings().setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        //缩放操作
        webView.getSettings().setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webView.getSettings().setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webView.getSettings().setDisplayZoomControls(false); //隐藏原生的缩放控件
        webView.getSettings().setDefaultTextEncodingName("utf-8");
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String s) {
                return super.shouldOverrideUrlLoading(webView, s);
            }

            @Override
            public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
                super.onPageStarted(webView, s, bitmap);
                showMsgDialog();
            }

            @Override
            public void onPageFinished(WebView webView, String s) {
                super.onPageFinished(webView, s);
                showMsgFinish();
            }
        });
        webView.setWebChromeClient(new WebChromeClient() {
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                if (mUploadMessage!=null) {
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    intent.setType("image/*");
                    MonitorScreenActivity.this.startActivityForResult(
                            Intent.createChooser(intent, "完成操作需要使用"),
                            FILE_SELECTED);
                }
            }

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> valueCallback, FileChooserParams fileChooserParams) {
                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                }

                uploadMessage = valueCallback;
                if (uploadMessage!=null) {
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    intent.setType("image/*");
                    MonitorScreenActivity.this.startActivityForResult(
                            Intent.createChooser(intent, "完成操作需要使用"),
                            REQUEST_SELECT_FILE);
                }
                return true;
            }
        });
        cookies = CookiesManager.getCookieText(this);
        synCookies(mServer, cookies);
        webView.loadUrl(mServer + MethodURL.PJ_Base + url);
        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(final String url, String userAgent, final String contentDisposition, final String mimeType, final long contentLength) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        new SweetAlertDialog(MonitorScreenActivity.this, SweetAlertDialog.NORMAL_TYPE)
                                .setTitleText("下载附件?")
                                .setConfirmText("确定")
                                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                    @Override
                                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                                        long caca = contentLength;
                                        Uri uri = Uri.parse(url);
                                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                                        startActivity(intent);

//                                        downloadBySystem(url, contentDisposition, mimeType);
                                        sweetAlertDialog.dismissWithAnimation();
                                    }
                                })
                                .setCancelText("取消")
                                .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                    @Override
                                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                                        sweetAlertDialog.dismissWithAnimation();
                                    }
                                })
                                .show();
                    }
                });
            }
        });
        webView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (titleLayout.getVisibility()==View.VISIBLE){
                    titleLayout.setVisibility(View.GONE);
                    Toast.makeText(MonitorScreenActivity.this, "长按显示标题", Toast.LENGTH_LONG).show();
                }else {
                    titleLayout.setVisibility(View.VISIBLE);
                    Toast.makeText(MonitorScreenActivity.this, "长按隐藏标题", Toast.LENGTH_LONG).show();
                }
                return true;
            }
        });
        refresh = (SwipeRefreshLayout) findViewById(R.id.moudle_guide_menu_refresh);
        refresh.setColorSchemeResources(R.color.blue);
        refresh.setEnabled(false);
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                webView.loadUrl(mServer + MethodURL.PJ_Base + url);
                refresh.setRefreshing(false);
            }
        });
        Toast.makeText(MonitorScreenActivity.this, "长按页面显示标题", Toast.LENGTH_LONG).show();
    }


    private void downloadBySystem(String url, String contentDisposition, String mimeType) {


        // 设置下载文件保存的路径和文件名
        String fileName = URLUtil.guessFileName(url, contentDisposition, mimeType);
        fileName = URLDecoder.decode(fileName);
        downloadFile(url, fileName, fileabspath);
//        new DownloadTask().execute(url, fileabspath+"/"+fileName);
    }

    private class DownloadTask extends AsyncTask<String, Void, Void> {
        // 传递两个参数：URL 和 目标路径
        private String url;
        private String destPath;


        @Override
        protected void onPreExecute() {
//            log.info("开始下载");
            if (!MonitorScreenActivity.this.isFinishing()) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MonitorScreenActivity.this, "开始下载", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }

        @Override
        protected Void doInBackground(String... params) {

            if (!MonitorScreenActivity.this.isFinishing()) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                        progressDialog.setMessage("下载中...");
                        progressDialog.show();
                    }
                });
            }
//            log.debug("doInBackground. url:{}, dest:{}", params[0], params[1]);
            url = params[0];
            destPath = params[1];
            OutputStream out = null;
            HttpURLConnection urlConnection = null;
            try {
                URL url = new URL(params[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setConnectTimeout(15000);
                urlConnection.setReadTimeout(15000);
                InputStream in = urlConnection.getInputStream();
                out = new FileOutputStream(params[1]);
                byte[] buffer = new byte[10 * 1024];
                int len;
                while ((len = in.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                in.close();
            } catch (IOException e) {
//                log.warn(e);
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
//                        log.warn(e);
                    }
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
//            log.info("完成下载");
            if (!MonitorScreenActivity.this.isFinishing()) {
                Toast.makeText(MonitorScreenActivity.this, "下载成功", Toast.LENGTH_SHORT).show();
                progressDialog.dismiss();
            }
            File file  = new File(destPath);
            openThisFile(file);
//            Intent handlerIntent = new Intent(Intent.ACTION_VIEW);
//            String mimeType = getMIMEType(url);
//            Uri uri = Uri.fromFile(new File(destPath));
//            handlerIntent.setDataAndType(uri, mimeType);
//            startActivity(handlerIntent);
        }
    }

    private String getMIMEType(String url) {
        String type = null;
        String extension = MimeTypeMap.getFileExtensionFromUrl(url);
//        log.debug("extension:{}", extension);
        if (extension != null) {
            type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        }
        return type;
    }



    private void downloadFile(String nowurl, String filename, String path) {
        File filep = new File(path);
        if (!filep.exists())
            filep.mkdirs();
        filep = null;
        progressDialog = new ProgressDialog(this);
        org.xutils.http.RequestParams requestParams = new org.xutils.http.RequestParams(nowurl);
        requestParams.setAutoRename(false);
        requestParams.setSaveFilePath(path +"/"+ filename);
        x.http().get(requestParams, new org.xutils.common.Callback.ProgressCallback<File>() {
            @Override
            public void onWaiting() {
            }

            @Override
            public void onStarted() {
                if (!MonitorScreenActivity.this.isFinishing()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MonitorScreenActivity.this, "开始下载", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }

            @Override
            public void onLoading(final long total, final long current, boolean isDownloading) {
                if (!MonitorScreenActivity.this.isFinishing()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                            progressDialog.setMessage("下载中...");
                            progressDialog.show();
                            progressDialog.setProgressNumberFormat("");
                            progressDialog.setMax((int) total);
                            progressDialog.setProgress((int) current);
                        }
                    });
                }
            }


            @Override
            public void onSuccess(File result) {
                if (!MonitorScreenActivity.this.isFinishing()) {
                    Toast.makeText(MonitorScreenActivity.this, "下载成功", Toast.LENGTH_SHORT).show();
                    progressDialog.dismiss();
                }
                //下载成功,file为下载好的文件
                File file = result;
//                openFile(file);
                String name = file.getName();
                String filepath = file.getPath();
                String abso = file.getAbsolutePath();
                openThisFile(file);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                if (!MonitorScreenActivity.this.isFinishing()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MonitorScreenActivity.this, "下载失败，请检查网络和SD卡", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

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

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

//        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_SELECT_FILE:
//                    if (null == mUploadMessage) {
//                        break;
//                    }
//                    Uri mResult = data == null || resultCode != RESULT_OK ? null
//                            : data.getData();
//                    mUploadMessage.onReceiveValue(mResult);
//                    mUploadMessage = null;
                    if (uploadMessage == null)
                        return;
                    Uri result = (data == null || resultCode != RESULT_OK) ? null : data.getData();
                    if (result != null) {
                        uploadMessage.onReceiveValue(new Uri[]{result});
                    } else {
                        uploadMessage.onReceiveValue(new Uri[]{});
                    }
                    uploadMessage = null; //每次置空是为了防止下次点击按钮选择图片无响应
                    break;
                case FILE_SELECTED:
                    if (null == mUploadMessage) {
                        break;
                    }
                    Uri mResult = data == null || resultCode != RESULT_OK ? null
                            : data.getData();
                    mUploadMessage.onReceiveValue(mResult);
                    mUploadMessage = null;
                    break;

            }
//        }else {
//
//        }
    }

    private static final int REQUEST_CHOOSEFILE = 1212;

    private void openThisFile(File file) {


        if (!file.exists()) {

            Toast.makeText(MonitorScreenActivity.this, "文件不存在", Toast.LENGTH_SHORT).show();

        } else {

            try {


                Uri fileUri = FileProvider7.getUriForFile(MonitorScreenActivity.this, file);

                Intent in = AndroidFileUtil.openFile(file.getPath() + "", fileUri);

                startActivity(in);

            } catch (Exception e) {

                Toast.makeText(MonitorScreenActivity.this, "文件打开失败", Toast.LENGTH_SHORT).show();

            }

        }
    }

    private void showMsgFinish() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                pDialog.hide();
            }
        });
    }

    private void showMsgDialog() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                initDialog("页面加载中");
                pDialog.show();
            }
        });
    }

    private void initDialog(String st) {
        pDialog.setTitleText(st);
    }

    public void synCookies(String url, String cookies) {
        CookieSyncManager.createInstance(getApplicationContext());
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.setCookie(url, cookies);
        CookieSyncManager.getInstance().sync();
    }

    /**
     * 初始化
     */
    private String mServer;
    private String mUsername;
    private String mPassword;
    private String mUserid;
    private String mCaption;
    private String mBizid;

    public void init() {
        fileabspath = Environment.getExternalStorageDirectory() + "/" + getResources().getString(R.string.appflag) + "/" + getResources().getString(R.string.appflag) + "_FILE";
        SharedPreferences sharedPre = getSharedPreferences("config", MODE_PRIVATE);
        mServer = sharedPre.getString("server", "");
        mUsername = sharedPre.getString("username", "");
        mPassword = sharedPre.getString("password", "");
        mUserid = sharedPre.getString("userid", "");
        mCaption = sharedPre.getString("caption", "");
        mBizid = sharedPre.getString("bizid", "");
        url = getIntent().getStringExtra("url");
        name = getIntent().getStringExtra("name");
    }
}
