package com.yidianling.dynamic.common.browsePictures;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.luck.picture.lib.photoview.PhotoView;
import com.miracle.view.imageeditor.utils.FileUtils;
import com.ydl.ydl_image.module.GlideApp;
import com.ydl.ydlcommon.base.BaseActivity;
import com.ydl.ydlcommon.data.http.RxUtils;
import com.ydl.ydlcommon.ui.ParcelableImage;
import com.yidianling.common.tools.ToastUtil;
import com.yidianling.dynamic.R;
import com.yidianling.dynamic.bean.DynamicConstants;
import com.yidianling.dynamic.common.net.DynamicApiUtils;
import com.yidianling.dynamic.common.tool.DownLoadImageService;
import com.yidianling.dynamic.common.tool.ImageDownLoadCallBack;
import com.yidianling.dynamic.model.Command;

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

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 预览大图
 */
public class BrowsePicturesActivity extends BaseActivity implements ViewPager.OnPageChangeListener {

    int iposition;
    private ArrayList<ParcelableImage> trendImages = new ArrayList<>();

    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 savelodingDialog;
    boolean chane_state;
    String trend_id;

    @SuppressLint("WrongConstant")
    @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();

        browse_type = intent.getStringExtra("browse_type");
        Bundle allTrendImages_bd = intent.getBundleExtra("allTrendImages_bd");

        List<ParcelableImage> temptrendImages = allTrendImages_bd.getParcelableArrayList("allTrendImages");
        if (temptrendImages != null) {
            trendImages.addAll(temptrendImages);
        }
        if ("browse".equals(browse_type)) {//动态列表
            iposition = intent.getIntExtra("position", 0);
            save_tv.setText("保存");
            trend_id = intent.getStringExtra("trend_id");
            RecordVisit();
        } else if ("preview".equals(browse_type)) {//发布动态
            iposition = intent.getIntExtra("position", 0);
            save_tv.setText("删除");
        } else if ("member".equals(browse_type)) {//个人主页
            save_tv.setVisibility(View.GONE);
            title_tv.setVisibility(View.GONE);
        }

        //将图片装载到数组中
        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) {
                back();
            }
        });
        save_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("browse".equals(browse_type)) {//保存
                    DownLoadImageService downloadService = new DownLoadImageService(BrowsePicturesActivity.this,
                            trendImages.get(iposition).getImage_url(),
                            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);
                        }
                    });
                    showProgressDialog(null);
//                    savelodingDialog = LodingDialog.getInstance(BrowsePicturesActivity.this);
//                    savelodingDialog.setMessage("保存中...");
//                    savelodingDialog.setSpinnerType(LodingDialog.SIMPLE_ROUND_SPINNER);
//                    savelodingDialog.show();
                    new Thread(downloadService).start();
                } else if ("preview".equals(browse_type)) {//删除
                    chane_state = true;
                    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 {
                        myAdapter.removie(iposition);
                        back();
                    }
                }

            }
        });
        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);
    }

    private void back() {
        if ("browse".equals(browse_type)) {
        } else if ("preview".equals(browse_type)) {
            Intent intent = getIntent();
            Bundle bundle = new Bundle();
//            intent.setClass(BrowsePicturesActivity.this, PublishTrendActivity.class);
            intent.putExtra("chane_state", chane_state);
            bundle.putParcelableArrayList("publish_img", (ArrayList<? extends Parcelable>) trendImages);
            intent.putExtra("bundle", bundle);
            setResult(RESULT_OK, intent);
        }
        finish();
    }

    /**
     * 记录浏览量
     */
    private void RecordVisit() {
        Command.UserAndTrendVisitCmd cmd = new Command.UserAndTrendVisitCmd("2", trend_id);
        DynamicApiUtils.visitCounter(cmd)
                .subscribeOn(Schedulers.io())
                .compose(RxUtils.INSTANCE.resultData())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(resp -> {
                }, throwable -> {
                    DynamicApiUtils.handleError(BrowsePicturesActivity.this, throwable);
                });
    }


    @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(BrowsePicturesActivity.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() {
        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() {
        @SuppressLint("WrongConstant")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DynamicConstants.REQUEST_SAVE_IMG_SUCCESS:
                    dismissProgressDialog();
                    ToastUtil.toastShort(BrowsePicturesActivity.this, "保存成功");
                    break;
                case DynamicConstants.REQUEST_SAVE_IMG_FAIL:
                    dismissProgressDialog();
                    ToastUtil.toastShort(BrowsePicturesActivity.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<ParcelableImage> mImages;

        public MyAdapter(Context mContext, List<PhotoView> mDatas, List<ParcelableImage> 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) {
            trendImages.remove(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) {
            Uri uri = FileUtils.INSTANCE.getUriByPath(container.getContext(), mImages.get(position).getImage_url());

            GlideApp.with(mContext)
                    .load(mImages.get(position).getImage_url())
                    .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;
        }


    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            back();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
