package com.mayi.demo;


import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.mayi.fastdevelop.base.BaseActivity;
import com.mayi.fastdevelop.util.BitmapUtil;
import com.mayi.fastdevelop.util.DrawableUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RecyclerView listView = findViewById(R.id.list);
        listView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        final List<ItemBean> list = new ArrayList<>();
        list.add(new ItemBean("常用控件", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoActivity(ViewActviity.class);
            }
        }));
        list.add(new ItemBean("常用功能", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoActivity(FunctionActivity.class);
            }
        }));
        list.add(new ItemBean("常用页面", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoActivity(PageActivity.class);
            }
        }));
        list.add(new ItemBean("图片裁剪", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoActivity(CutPicturesActivity.class);
            }
        }));

        listView.setAdapter(new RecyclerView.Adapter<MyViewHolder>() {
            @NonNull
            @Override
            public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
                return new MyViewHolder(new Button(viewGroup.getContext()));
            }

            @Override
            public void onBindViewHolder(@NonNull MyViewHolder viewHolder, int i) {
                viewHolder.tv.setOnClickListener(list.get(i).getClickListener());
                viewHolder.tv.setText(list.get(i).getText());
                DrawableUtils.setStatePressedDrawable(viewHolder.tv, "#555555", "#F00000", "#999999");
            }

            @Override
            public int getItemCount() {
                return list.size();
            }
        });
    }

    class MyViewHolder extends RecyclerView.ViewHolder {

        Button tv;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            tv = (Button) itemView;
        }
    }

    private Uri uri;
    private File cameraSavePath;

    //激活相机操作
    private void goCamera() {
        cameraSavePath = new File(Environment.getExternalStorageDirectory().getPath() + "/" + getPackageName() + "/" + System.currentTimeMillis() + ".jpg");
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(MainActivity.this, getPackageName() + ".uri", cameraSavePath);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            uri = Uri.fromFile(cameraSavePath);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        MainActivity.this.startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1 && resultCode == RESULT_OK) {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(MainActivity.this, getPackageName() + ".uri", cameraSavePath);
            } else {
                uri = Uri.fromFile(cameraSavePath);
            }
            photoClip(uri);
        } else if (requestCode == 2 && resultCode == RESULT_OK) {
//            photoPath = getPhotoFromPhotoAlbum.getRealPathFromUri(this, data.getData());
            Log.d("相册返回图片路径:", data.getData() + "");
            photoClip(data.getData());
//            Glide.with(MainActivity.this).load(photoPath).into(ivTest);
        } else if (requestCode == 3 && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();

            if (bundle != null) {
                //在这里获得了剪裁后的Bitmap对象，可以用于上传
                Bitmap image = bundle.getParcelable("data");
                BitmapUtil.saveBitmapToFormat(image, Environment.getExternalStorageDirectory().getPath() + "/Download/11111.jpg");
//                //设置到ImageView上
//                ivTest.setImageBitmap(image);
//                //也可以进行一些保存、压缩等操作后上传
//                String path = saveImage("头像", image);
//                Log.d("裁剪路径:", path);
            }


        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    private void photoClip(Uri uri) {
        // 调用系统中自带的图片剪裁
        Intent intent1 = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent1.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        /*设置调用裁剪工具的action*/
        intent1.setAction("com.android.camera.action.CROP");
        /*创建一个指向需要操作文件（filename）的文件流。（可解决无法“加载问题”）*/
        intent1.setDataAndType(uri, "image/*");
        intent1.putExtra("crop", "true");
        intent1.putExtra("scale", true);
        intent1.putExtra("return-data", false);
        Uri uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + System.currentTimeMillis() + ".jpg");
        intent1.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
        intent1.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent1.putExtra("noFaceDetection", true);
        MainActivity.this.startActivityForResult(intent1, 3);
    }

}
