package com.fxy.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.elvishew.xlog.XLog;
import com.fxy.baselibrary.util.RxFileTool;
import com.fxy.baselibrary.util.RxImageTool;
import com.fxy.baselibrary.views.dialog.RxDialogChooseImage;
import com.fxy.baselibrary.views.dialog.RxDialogZoomImageView;
import com.fxy.adapter.ShowImgAdapter;

import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * 遗弃
 */

@SuppressLint("Registered")
public class ShowImgActivity extends Activity {
    private String prefix="tally";
    private Context mContext;
    private RecyclerView mRvShowImg ;
    private ShowImgAdapter mPhotoAdapter;
    private ArrayList<String>imgPathList=new ArrayList<>();
    private ArrayList<String> ossPhotoList =new ArrayList<>();


    private int imgCount = 0;
    protected static final int REQUESTCODE_CAMERA = 5001 ;
    protected static final int GET_IMAGE_BY_CAMERA = 5002 ;


    private RxDialogChooseImage rxDialogChooseImage;



    public ShowImgActivity(Context context, RecyclerView rvShowImg){
        mContext = context;
        mRvShowImg = rvShowImg;
        initAdapter();
    }

    public ArrayList getPhotoList(){
        return  ossPhotoList;
    }


    public void remove(){
        uploadHandler.removeCallbacksAndMessages(null);
    }

    public void emptyRemake(){
        imgPathList.clear();
        ossPhotoList.clear();
        imgPathList.add(mPhotoAdapter.getFirst());
        mPhotoAdapter.notifyDataSetChanged();
    }

    public void setMaxNum(int num){
        mPhotoAdapter.setMaxNum(num);
    }
    public void setPrefix(String str){
        prefix = str;
    }

    private void initAdapter() {

        mPhotoAdapter = new ShowImgAdapter(mContext, imgPathList);
        mPhotoAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);

        //用于实现网格布局
        GridLayoutManager manager = new GridLayoutManager(mContext, 3);
        manager.setOrientation(GridLayoutManager.VERTICAL);
        mRvShowImg.setLayoutManager(manager);


        mRvShowImg.setAdapter(mPhotoAdapter);
        //XLog.d("imgList: " +imgPathList.toString());
        mPhotoAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (position<imgPathList.size()-1){
                    RxDialogZoomImageView rxDialogZoomImageView = new RxDialogZoomImageView(mContext);
                    rxDialogZoomImageView.setImagePath(imgPathList.get(position));
                    rxDialogZoomImageView.show();
                }else{
                    rxDialogChooseImage = new RxDialogChooseImage((Activity) mContext);
                    rxDialogChooseImage.show();
                }
            }
        });
        imgPathList.add(mPhotoAdapter.getFirst());
        mPhotoAdapter.notifyDataSetChanged();
    }


    public void getFile(int requestCode, int resultCode, Intent data){
        switch(requestCode) {
            case REQUESTCODE_CAMERA:
                // 设置显示的图片
                //mUploadView.getProgressImage().setImageBitmap(bitmap);
                //final Bitmap photo = data.getParcelableExtra("data");

                if (data != null) {
                    try {
                        if (data.getData() != null)
                        {
                            Uri imageUri = data.getData();
                            File file =  RxFileTool.getFilePhotoFromUri((Activity) mContext,imageUri);
                            String filePath = file.getPath();
                            new UploadThread(filePath);
//                            OssUploadUtil ossUploadUtil = new OssUploadUtil(mContext,prefix);
//                            OSSAsyncTask task = ossUploadUtil.uploadFiledUrl(filePath,new JSONObject(),uploadHandler);
                            return;
                        }
                        Bundle bundle = data.getExtras();
                        Bitmap bitmap = (Bitmap) bundle.get("data"); //get bitmap


//                        Uri imageUri = Uri.parse(MediaStore.Images.Media.insertImage(mContext.getContentResolver(),bitmap,null,null));
//                        File file =  RxFileTool.getFilePhotoFromUri((Activity) mContext,imageUri);
//                        new UploadThread(file.getPath());

                        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                            String name = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
                            String cameraFilePath = Environment.getExternalStorageDirectory().toString()+ File.separator+"temp/image/"+name+".jpg";
                            RxImageTool.save(bitmap,cameraFilePath,Bitmap.CompressFormat.JPEG);
                            new UploadThread(cameraFilePath);
                        } else {
                            Toast.makeText(mContext, "保存失败，SD卡无效", Toast.LENGTH_LONG).show();
                        }
                    } catch (Exception e) {
                        XLog.e("拍照获取图片错误，错误原因："+e.getMessage());
                    }
                } else {
                    //无法获取
                    Toast.makeText(mContext, "err****", Toast.LENGTH_LONG).show();
                    return;
                }

                break;
            case GET_IMAGE_BY_CAMERA:

                try {
                    if (resultCode == RESULT_CANCELED) {
                        Toast.makeText(mContext, "点击取消从相册选择", Toast.LENGTH_LONG).show();
                        return;
                    }
                    if(resultCode == RESULT_OK){
                        Uri imageUri = data.getData();
                        File file =  RxFileTool.getFilePhotoFromUri((Activity) mContext,imageUri);
//                        String filePath = file.getPath();
//                        OssUploadUtil ossUploadUtil = new OssUploadUtil(mContext,prefix);
//                        OSSAsyncTask task = ossUploadUtil.uploadFiledUrl(filePath,new JSONObject(),uploadHandler);
                        new UploadThread(file.getPath());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    XLog.e("错误图片错误，错误原因："+e.getMessage());
                }



        }

        // task.cancel(); // 可以取消任务。
        //task.waitUntilFinished(); // 等待任务完成。

    }



    // 开启子进程上传
    class UploadThread extends Thread {
        UploadThread(String filePath) {
//            OssUploadUtil ossUploadUtil = new OssUploadUtil(mContext,prefix);
//            OSSAsyncTask task = ossUploadUtil.uploadFiledUrl(filePath,new JSONObject(),uploadHandler);
//            task.waitUntilFinished();
        }
    }

    //接收图片上传
    @SuppressLint("HandlerLeak")
    private Handler uploadHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            try {
                XLog.e(msg);
                //String data = (String) msg.obj;
                JSONObject jsonObject = (JSONObject) msg.obj;

                if (jsonObject.has("uploadFilePath")){
                    imgCount = imgPathList.size();
                    imgPathList.remove(imgCount-1);
                    imgPathList.add(jsonObject.getString("uploadFilePath"));
                    imgPathList.add(mPhotoAdapter.getFirst());
                    ossPhotoList.add("/"+jsonObject.getString("fieldName"));
                    mPhotoAdapter.notifyDataSetChanged();
                }
            } catch (Exception e) {
                XLog.e(e.getMessage());
                e.printStackTrace();
            }
        }
    };


}
