package com.sheep.gamegroup.util;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.Html;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.utils.ClassFileHelper;
import com.sheep.jiuyan.samllsheep.utils.G;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by realicing on 2018/5/11.
 * realicing@sina.com
 */
public class ViewUtil {

    public static void showQR(final Activity activity, String link) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        View view = View.inflate(activity, R.layout.x_ask_qr_dialog, null);
        builder.setView(view);
        final AlertDialog dialog = builder.create();
        ImageView iv = view.findViewById(R.id.iv_close);
        final ImageView iv_qr = view.findViewById(R.id.iv_qr);
        View save_pic = view.findViewById(R.id.save_pic);
        ImageView iv_qr_small = view.findViewById(R.id.iv_qr_small);
        Glide.with(activity)
                .load(AppUtil.getQRLink(link, 800))
                .apply(new RequestOptions().override(800, 800))
                .into(iv_qr);
        Glide.with(activity)
                .load(R.drawable.icon)
                .apply(new RequestOptions().override(G.WIDTH/5))
                .into(iv_qr_small);
        dialog.show();
        Window window = dialog.getWindow();
        if(window != null) {
            android.view.WindowManager.LayoutParams p = window.getAttributes();
            p.height = WindowManager.LayoutParams.WRAP_CONTENT;
            p.width = WindowManager.LayoutParams.MATCH_PARENT;
            dialog.getWindow().setAttributes(p);     //设置生效
        }
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        save_pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                File file = ViewUtil.saveImage((View) iv_qr.getParent(), ClassFileHelper.DIR, System.currentTimeMillis()+".jpg");
                if(file != null) {
                    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    Uri uri = Uri.fromFile(file);
                    intent.setData(uri);
                    activity.sendBroadcast(intent); // 发送广播通知相册
                } else {
                    ViewUtil.sysSaveImage((View) iv_qr.getParent(), "小绵羊", "二维码分享");
                }
                G.showToast("已保存");
            }
        });

    }
    /**
     * 分享对话框
     * @param activity
     * @param link
     */
    public static void shareLink(final Activity activity, final String link) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        View view = View.inflate(activity, R.layout.x_recommend_dialog, null);
        builder.setView(view);

        final AlertDialog dialog = builder.create();
        ImageView iv = view.findViewById(R.id.iv_close);
        TextView withdrawal = view.findViewById(R.id.withdrawal);
        TextView tv_link = view.findViewById(R.id.tv_link);
        TextView save_pic = view.findViewById(R.id.save_pic);
        final ImageView iv_qr = view.findViewById(R.id.iv_qr);

        tv_link.setText(link);

        Glide.with(activity)
                .load(AppUtil.getQRLink(link, 800))
                .apply(new RequestOptions().override(800, 800))
                .into(iv_qr);
        dialog.show();
        Window window = dialog.getWindow();
        if(window != null) {
            android.view.WindowManager.LayoutParams p = window.getAttributes();
            p.height = WindowManager.LayoutParams.WRAP_CONTENT;
            p.width = WindowManager.LayoutParams.MATCH_PARENT;
            dialog.getWindow().setAttributes(p);     //设置生效
        }
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        withdrawal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StringUtils.CopyText(activity, link);
                G.showToast("复制链接成功");
            }
        });

        save_pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                File file = ViewUtil.saveImage((View) iv_qr.getParent(), ClassFileHelper.DIR, System.currentTimeMillis()+".jpg");
                if(file != null) {
                    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    Uri uri = Uri.fromFile(file);
                    intent.setData(uri);
                    activity.sendBroadcast(intent); // 发送广播通知相册
                } else {
                    ViewUtil.sysSaveImage((View) iv_qr.getParent(), "小绵羊", "二维码分享");
                }
                G.showToast("已保存");
            }
        });

    }

    /**
     * 获取一个 View 的缓存视图
     *
     * @param view
     * @return
     */
    public static Bitmap getCacheBitmapFromView(View view) {
        final boolean drawingCacheEnabled = true;
        view.setDrawingCacheEnabled(drawingCacheEnabled);
        view.buildDrawingCache(drawingCacheEnabled);
        final Bitmap drawingCache = view.getDrawingCache();
        Bitmap bitmap;
        if (drawingCache != null) {
            bitmap = Bitmap.createBitmap(drawingCache);
            view.setDrawingCacheEnabled(false);
        } else {
            bitmap = null;
        }
        return bitmap;
    }
    public static void sysSaveImage(View view, String title, String description) {
        MediaStore.Images.Media.insertImage(view.getContext().getContentResolver(), getCacheBitmapFromView(view), title, description);
    }
    public static File saveImage(View view, String dir, String fileName) {
        return saveImage(getCacheBitmapFromView(view), dir, fileName);
    }
    public static File saveImage(Bitmap bmp, String dir, String fileName) {
        File appDir = new File(dir);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            return file;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void setH5Text(TextView textView, String content){
        textView.setText(Html.fromHtml(content));
        textView.setMovementMethod(new ScrollingMovementMethod());
    }
    public static void loadDataWithBaseURL(WebView webView, String content){
        webView.loadDataWithBaseURL(null,
                new StringBuilder("<html><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, minimum-scale=0.5, maximum-scale=2.0, user-scalable=yes\" /><style>img{max-width:100% !important;height:auto !important;}</style><style>body{max-width:100% !important;}</style></head><body>").append(content).append("</body></html>").toString()
                , "text/html", "utf-8", null);
    }
}
