package com.danding.yang800;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.danding.yang800.Adapter.ImagePickerAdapter;
import com.danding.yang800.Entity.ImageItem;
import com.danding.yang800.General.GlideImageLoader;
import com.danding.yang800.General.ImageLoader;
import com.danding.yang800.General.ImagePicker;
import com.danding.yang800.General.Yang800App;
import com.danding.yang800.Presenter.PictureCheckActivityPresenter;
import com.danding.yang800.Util.StatusColorUtil;
import com.danding.yang800.Util.ToastUtil;
import com.danding.yang800.View.CropImageView;
import com.danding.yang800.View.NetworkProgressDialog;
import com.danding.yang800.View.SelectDialog;
import com.yanzhenjie.sofia.Sofia;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PictureCheckActivity extends BaseActivity implements View.OnClickListener, ImagePickerAdapter.OnRecyclerViewItemClickListener {
    @BindView(R.id.picturecheck_backTv)
    TextView picturecheck_backTv;
    @BindView(R.id.picture_exampleTv)
    TextView picture_exampleTv;
    @BindView(R.id.picture_savaTv)
    TextView picture_savaTv;
    private PopupWindow popupWindow;
    private int maxImgCount = 1;               //允许选择图片最大数
    private ArrayList<ImageItem> selImageList; //当前选择的所有图片
    public static final int IMAGE_ITEM_ADD = -1;
    private ImagePickerAdapter adapter;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    PictureCheckActivityPresenter presenter;
    ArrayList<ImageItem> images = null;
    private NetworkProgressDialog pd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        int type = StatusColorUtil.StatusBarLightMode(this);
//        if (type > 0) {
//            StatusColorUtil.setStatusBarColor(this, R.color.white);
//            StatusColorUtil.StatusBarLightMode(this, type);
//        }
        setContentView(R.layout.activity_picture_check);
        Sofia.with(this).statusBarDarkFont().statusBarBackground(ContextCompat.getColor(this, R.color.white));
        ButterKnife.bind(this);
        presenter = new PictureCheckActivityPresenter(this);
        if (sp.getString("uploadImgUrl", "").equals("")) {
            presenter.getUploadImgUrl();
        }
        initImagePicker();
        initWidget();
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(true);                           //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(maxImgCount);              //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    private void initWidget() {
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        selImageList = new ArrayList<>();
        adapter = new ImagePickerAdapter(this, selImageList, maxImgCount);
        adapter.setOnItemClickListener(this);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 1));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
    }


    @OnClick({R.id.picturecheck_backTv, R.id.picture_exampleTv, R.id.picture_savaTv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.picturecheck_backTv:
                finish();
                break;
            case R.id.picture_exampleTv:
                startActivity(ExampleActivity.class);
                break;
            case R.id.picture_savaTv:
                if (images == null) {
                    ToastUtil.show(this, "请选择一张图片！");
                    return;
                }
                try {
                    if (images.size() > 0) {
//                        myBitmap = Glide.with(this)
//                                .load(images.get(0).path)
//                                .asBitmap() //必须
//                                .centerCrop()
//                                .into(800, 800)
//                                .get();
                        initDialog();
                        Glide.with(this).load(images.get(0).path).asBitmap().into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                presenter.updateImg(resource, sp.getString("uploadImgUrl", ""), "files");
                            }
                        });
                    } else {
                        ToastUtil.show(this, "请选择一张图片！");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
        }
    }

    private void showWindow() {
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.layout_popupwindows_camera, null);
        popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT, true);
        TextView popupwindows_camera = (TextView) contentView
                .findViewById(R.id.popupwindows_camera);
        popupwindows_camera.setOnClickListener(this);
        TextView popupwindows_picture = (TextView) contentView
                .findViewById(R.id.popupwindows_picture);
        popupwindows_picture.setOnClickListener(this);
        TextView tv_popupwindows_off = (TextView) contentView
                .findViewById(R.id.tv_popupwindows_off);
        tv_popupwindows_off.setOnClickListener(this);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.popupwindows_camera:
                ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                Intent intent = new Intent(PictureCheckActivity.this, ImageGridActivity.class);
                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                startActivityForResult(intent, REQUEST_CODE_SELECT);
                popupWindow.dismiss();
                break;
            case R.id.popupwindows_picture:
                //打开选择,本次允许选择的数量
                ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                Intent intent1 = new Intent(PictureCheckActivity.this, ImageGridActivity.class);
                                /* 如果需要进入选择的时候显示已经选中的图片，
                                 * 详情请查看ImagePickerActivity
                                 * */
//                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                startActivityForResult(intent1, REQUEST_CODE_SELECT);
                popupWindow.dismiss();
                break;
            case R.id.tv_popupwindows_off:
                popupWindow.dismiss();
                break;
        }
    }


    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                showWindow();
                break;
            default:
                //打开预览
                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                break;
        }
    }

    private SelectDialog showDialog(SelectDialog.SelectDialogListener listener, List<String> names) {
        SelectDialog dialog = new SelectDialog(this, R.style
                .transparentFrameWindowStyle,
                listener, names);
        if (!this.isFinishing()) {
            dialog.show();
        }
        return dialog;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                    adapter.notifyDataSetChanged();
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    selImageList.clear();
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                    adapter.notifyDataSetChanged();
                }
            }
        }
    }

    public void initDialog() {
        if (pd == null) {
            pd = NetworkProgressDialog.createDialog(this);
            if (!pd.isShowing()) {
                pd.show();
            }
        }
    }

    public void dismissDialog() {
        if (pd != null) {
            pd.dismiss();
            pd = null;
            NetworkProgressDialog.clear();
        }
    }
}
