package com.yidianling.dynamic.common.browsePictures;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.luck.picture.lib.photoview.PhotoView;
import com.ydl.ydl_image.module.GlideApp;
import com.ydl.ydlcommon.base.BaseActivity;
import com.yidianling.common.tools.ToastUtil;
import com.yidianling.dynamic.DynamicConstants;
import com.yidianling.dynamic.R;
import com.yidianling.dynamic.common.tool.DownLoadImageService;
import com.yidianling.dynamic.common.tool.ImageDownLoadCallBack;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
 * 预览大图 2 集合范型为String
 */
public class BrowsePicturesActivity2 extends BaseActivity implements ViewPager.OnPageChangeListener {

    int iposition;
    private ArrayList<String> trendImages;

    private ViewPager browse_pictures_vp;
    private ImageView back_iv;
    private TextView title_tv,save_tv;
    String browse_type;
    /**
     * 装ImageView数组
     */
    private List<PhotoView> mImageViews;
    MyAdapter myAdapter;

//    LodingDialog lodingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dynamic_activity_browse_pictures);
        browse_pictures_vp=(ViewPager) findViewById(R.id.browse_pictures_vp);
        back_iv=(ImageView)findViewById(R.id.browse_pictures_back_iv);
        title_tv=(TextView)findViewById(R.id.browse_pictures_num_tv);
        save_tv=(TextView)findViewById(R.id.browse_pictures_save_tv);
        initWindows();
        Intent intent = getIntent();
        iposition=intent.getIntExtra("position",0);
        browse_type=intent.getStringExtra("browse_type");
        trendImages=intent.getStringArrayListExtra("allTrendImages");
        if("browse".equals(browse_type)){
            save_tv.setText("保存");
        }else  if("preview".equals(browse_type)){
            save_tv.setText("删除");
        }

        //将图片装载到数组中
        mImageViews = new ArrayList<PhotoView>();
        for(int i=0; i<trendImages.size(); i++){
            PhotoView imageView = new PhotoView(this);
            mImageViews.add(imageView);

        }
        back_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        save_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if("browse".equals(browse_type)){//保存
                    DownLoadImageService downloadService=new DownLoadImageService(BrowsePicturesActivity2.this, trendImages.get(iposition), new ImageDownLoadCallBack() {
                        @Override
                        public void onDownLoadSuccess(File file) {

                        }

                        @Override
                        public void onDownLoadSuccess(Bitmap bitmap) {
                            mHandler.sendEmptyMessage(DynamicConstants.REQUEST_SAVE_IMG_SUCCESS);
                        }

                        @Override
                        public void onDownLoadFailed() {
                            mHandler.sendEmptyMessage(DynamicConstants.REQUEST_SAVE_IMG_FAIL);
                        }
                    });
                    new Thread(downloadService).start();
                }else  if("preview".equals(browse_type)){//删除

                    if(trendImages.size()>1){
                        if(iposition<trendImages.size()-1){
                            myAdapter.removie(iposition);
                            title_tv.setText((iposition+1)+"/"+trendImages.size());

                        }else {
                            myAdapter.removie(iposition);
                            title_tv.setText((iposition+1)+"/"+trendImages.size());
                        }

                    }else {
                        trendImages.clear();
                        mImageViews.clear();
                        finish();
                    }
                }

            }
        });
        title_tv.setText((iposition+1)+"/"+trendImages.size());
        //设置Adapter
        if(myAdapter==null){
            myAdapter=new MyAdapter(this,mImageViews,trendImages);
        }else {
            myAdapter.notifyDataSetChanged();
        }
        browse_pictures_vp.setAdapter(myAdapter);
        //设置监听，主要是设置点点的背景
        browse_pictures_vp.setOnPageChangeListener(this);
        //设置ViewPager的默认项, 设置为长度的100倍，这样子开始就能往左滑动
        browse_pictures_vp.setCurrentItem(iposition);
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        iposition=position;
        title_tv.setText((iposition+1)+"/"+trendImages.size());
//        if (lodingDialog == null) {
//            lodingDialog = LodingDialog.getInstance(BrowsePicturesActivity2.this);
//            lodingDialog.setMessage("加载中");
//            lodingDialog.setSpinnerType(LodingDialog.SIMPLE_ROUND_SPINNER);
//            lodingDialog.show();
//        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
//        if (lodingDialog != null) {
//            lodingDialog.dismiss();
//            lodingDialog = null;
//        }
    }

    private void initWindows() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
//            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DynamicConstants.REQUEST_SAVE_IMG_SUCCESS:
                    ToastUtil.toastShort(BrowsePicturesActivity2.this,"保存成功");
                    break;
                case DynamicConstants.REQUEST_SAVE_IMG_FAIL:
                    ToastUtil.toastShort(BrowsePicturesActivity2.this,"保存失败");
                    break;
            }
        }
    };

    @Override
    protected int layoutResId() {
        return 0;
    }

    @Override
    protected void initDataAndEvent() {

    }

    public class MyAdapter extends PagerAdapter {
        private Context mContext;
        private List<PhotoView> mDatas;
        private List<String> mImages;

        public MyAdapter(Context mContext, List<PhotoView> mDatas, List<String> mImages) {
            this.mContext = mContext;
            this.mDatas = mDatas;
            this.mImages = mImages;
        }

        @Override
        public int getCount() {
            return mDatas.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(View container, int position, Object object) {
            View view = (View)object;
            ((ViewPager) container).removeView(view);
            view = null;
//            ((ViewPager)container).removeView((View) mDatas.get(position));

        }
        public void updateDate(List<PhotoView> datas) {
            this.mDatas = datas;
            notifyDataSetChanged();
        }
        public void removie(int p) {
            mImages.remove(p);
            mDatas.remove(p);
            notifyDataSetChanged();
        }

        @Override
        public int getItemPosition(Object object) {
            return FragmentPagerAdapter.POSITION_NONE;
        }

//        /**
//         * 载入图片进去，用当前的position 除以 图片数组长度取余数是关键
//         */
//        @Override
//        public Object instantiateItem(View container, int position) {
//            ((ViewPager)container).addView(mDatas.get(position % mDatas.size()), 0);
//            return mDatas.get(position % mDatas.size());
//        }
        @Override
        public Object instantiateItem(View container, int position) {
            GlideApp.with(mContext)
                    .load(mImages.get(position))
                    .error(R.drawable.dynamic_default_img)
                    .into(mDatas.get(position));
            mDatas.get(position).setOnPhotoTapListener((imageView, v, v1) -> finish());
            ((ViewPager)container).addView(mDatas.get(position), 0);
//            if (lodingDialog != null) {
//                lodingDialog.dismiss();
//                lodingDialog = null;
//            }
            return mDatas.get(position);
        }

        @Override
        public Parcelable saveState() {
            return null;
        }


    }

}
