package io.openim.android.ouimoments.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.DrawableImageViewTarget;
import com.bumptech.glide.request.transition.Transition;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import io.openim.android.ouicore.entity.LoginCertificate;
import io.openim.android.ouicore.utils.Common;
import io.openim.android.ouicore.utils.Constants;
import io.openim.android.ouicore.utils.OnDedrepClickListener;
import io.openim.android.ouicore.utils.SinkHelper;
import io.openim.android.ouimoments.R;
import io.openim.android.ouimoments.bean.CircleItem;
import io.openim.android.ouimoments.bean.CommentConfig;
import io.openim.android.ouimoments.bean.CommentItem;
import io.openim.android.ouimoments.bean.FavortItem;
import io.openim.android.ouimoments.bean.PhotoInfo;
import io.openim.android.ouimoments.mvp.contract.CircleContract;
import io.openim.android.ouimoments.mvp.presenter.CirclePresenter;
import io.openim.android.ouimoments.utils.UrlUtils;
import io.openim.android.ouimoments.widgets.CommentListView;

/**
 * 查看个人朋友圈图片信息
 */
public class ImagePagerPersonActivity extends AppCompatActivity implements CircleContract.View {
    public static final String INTENT_IMGURLS = "imgurls";
    public static final String INTENT_POSITION = "position";
    public static final String INTENT_IMAGESIZE = "imagesize";
    public static final String INTENT_ITEM = "item";
    public static final String INTENT_CIRCLE_POSITION = "circlePosition";

    private List<View> guideViewList = new ArrayList<>();
    private LinearLayout guideGroup;
    public ImageSize imageSize;
    private int startPos = 0;
    private ArrayList<String> imgUrls;
    private GestureDetector mGestureDetector;
    private CircleItem circleItem;
    public CirclePresenter presenter;
    public int circlePosition;
    private ImageView ivLikeState;
    private TextView tvLikeCount;
    private TextView tvComment;
    private EditText editText;
    private LinearLayout edittextbody;

    public static void startImagePagerActivity(Context context, List<String> imgUrls, int position, ImageSize imageSize) {
        Intent intent = new Intent(context, ImagePagerPersonActivity.class);
        intent.putStringArrayListExtra(INTENT_IMGURLS, new ArrayList<String>(imgUrls));
        intent.putExtra(INTENT_POSITION, position);
        intent.putExtra(INTENT_IMAGESIZE, imageSize);
        context.startActivity(intent);
    }

    public static void startImagePagerActivity(Context context, CircleItem circleItem, int circlePosition) {
        Intent intent = new Intent(context, ImagePagerPersonActivity.class);
        intent.putExtra(INTENT_ITEM, circleItem);
        intent.putExtra(INTENT_CIRCLE_POSITION, circlePosition);
        context.startActivity(intent);
    }

    private void getIntentData() {
        circleItem = (CircleItem) getIntent().getSerializableExtra(INTENT_ITEM);
        startPos = getIntent().getIntExtra(INTENT_POSITION, 0);
        circlePosition = getIntent().getIntExtra(INTENT_CIRCLE_POSITION, 0);
        imgUrls = getIntent().getStringArrayListExtra(INTENT_IMGURLS);
        imageSize = (ImageSize) getIntent().getSerializableExtra(INTENT_IMAGESIZE);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        presenter = new CirclePresenter(this);
        ActionBar actionBar = getSupportActionBar();
        if (null != actionBar) actionBar.hide();
        setContentView(R.layout.activity_imagepager_person);
        SinkHelper.get(this).setTranslucentStatus(null);
        CardView cardView = (CardView) findViewById(R.id.titleBar);
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) cardView.getLayoutParams();
        params.setMargins(0, SinkHelper.getStatusBarHeight(), 0, 0);
        cardView.setLayoutParams(params);
        TextView tvTitle = findViewById(R.id.tvTitle);
        TextView tvCurrent = findViewById(R.id.tvCurrent);
        TextView tvContent = findViewById(R.id.tvContent);
        tvLikeCount = findViewById(R.id.tvLikeCount);
        ivLikeState = findViewById(R.id.ivLikeState);
        tvComment = findViewById(R.id.tvComment);
        TextView tvDetail = findViewById(R.id.tvDetail);
        editText = findViewById(R.id.circleEt);
        edittextbody = findViewById(R.id.editTextBodyLl);
        LinearLayout llLike = findViewById(R.id.llLike);
        llLike.setOnClickListener(new OnDedrepClickListener() {
            @Override
            public void click(View v) {
                if (presenter != null && circleItem != null) {
                    if (isLike()) {
                        //取消点赞
                        presenter.deleteFavort(circlePosition, circleItem.getId());
                    } else {
                        presenter.addFavort(circlePosition, circleItem.getId());

                    }
                }
            }
        });
        LinearLayout llComment = findViewById(R.id.llComment);
        llComment.setOnClickListener(new OnDedrepClickListener() {
            @Override
            public void click(View v) {
                startActivity(new Intent(ImagePagerPersonActivity.this, MomentsDetailActivity.class).putExtra(Constants.K_ID, circleItem.getId()));
                finish();
            }
        });

        tvDetail.setOnClickListener(new OnDedrepClickListener() {
            @Override
            public void click(View v) {
                startActivity(new Intent(ImagePagerPersonActivity.this, MomentsDetailActivity.class).putExtra(Constants.K_ID, circleItem.getId()));
                finish();
            }
        });
        ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
        guideGroup = (LinearLayout) findViewById(R.id.guideGroup);
        getIntentData();
        mGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
//                finish();
                return false;
            }
        });
        if (circleItem != null) {
            ArrayList<String> photoUrls = new ArrayList<String>();
            for (PhotoInfo photoInfo : circleItem.getPhotos()) {
                photoUrls.add(photoInfo.url);
            }
            imgUrls = photoUrls;
            String createTime = circleItem.getCreateTime();
            long time = TimeUtils.string2Millis(createTime, "yyyy/MM/dd HH:mm");
            tvTitle.setText(TimeUtils.getFriendlyTimeSpanByNow(time));
            String content = circleItem.getContent();
            tvContent.setText(UrlUtils.formatUrlString(content));
            notifyLike();
            notifyComment();

        }

        ImageAdapter mAdapter = new ImageAdapter(this);
        mAdapter.setDatas(imgUrls);
        mAdapter.setImageSize(imageSize);
        viewPager.setAdapter(mAdapter);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

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

            }

            @Override
            public void onPageSelected(int position) {
                int current = position + 1;
                tvCurrent.setText(current + "/" + imgUrls.size());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        viewPager.setCurrentItem(startPos);
        if (imgUrls.size() > 1) {
            tvCurrent.setText(startPos + 1 + "/" + imgUrls.size());
        }


    }

    public void toBack(View view) {
        finish();
    }

    private void notifyLike() {
        List<FavortItem> favortDatas = circleItem.getFavorters();
        if (ivLikeState != null) {
            ivLikeState.setImageResource(isLike() ? R.drawable.ic_comment_like_sel : R.drawable.ic_comment_like_unsel);
        }
        if (tvLikeCount != null) {
            tvLikeCount.setText(favortDatas.isEmpty() ? getString(io.openim.android.ouicore.R.string.like) : favortDatas.size() + "");
        }
    }

    private void notifyComment() {
        final List<CommentItem> commentsDatas = circleItem.getComments();
        tvComment.setText(commentsDatas.isEmpty() ? getString(io.openim.android.ouicore.R.string.comment) : commentsDatas.size() + "");
    }

    private boolean isLike() {
        List<FavortItem> favortDatas = circleItem.getFavorters();
        LoginCertificate loginCertificate = LoginCertificate.getCache(this);
        boolean hasFavort = false;
        if (loginCertificate != null) {
            for (FavortItem item : favortDatas) {
                if (item.getUser().getId().equals(loginCertificate.userID)) {
                    hasFavort = true;
                    break;
                }
            }
        }
        return hasFavort;
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        mGestureDetector.onTouchEvent(ev);
        try {
            return super.dispatchTouchEvent(ev);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void updateAdapterIndex(int index) {

    }

    @Override
    public void update2DeleteCircle(String circleId) {

    }

    //点赞回调
    @Override
    public void update2AddFavorite(int circlePosition, FavortItem addItem) {
        circleItem.getFavorters().add(addItem);
        notifyLike();


    }

    //取消点赞回调
    @Override
    public void update2DeleteFavort(int circlePosition, String favortId) {
        for (int i = 0; i < circleItem.getFavorters().size(); i++) {
            if (circleItem.getFavorters().get(i).getId().equals(favortId)) {
                circleItem.getFavorters().remove(i);
                break;
            }
        }
        notifyLike();

    }

    @Override
    public void update2AddComment(int circlePosition, CommentItem addItem) {

    }

    @Override
    public void update2DeleteComment(int circlePosition, String commentId) {

    }

    //隐藏显示键盘
    @Override
    public void updateEditTextBodyVisible(int visibility, CommentConfig commentConfig) {
////        this.commentConfig = commentConfig;
//        edittextbody.setVisibility(visibility);
//
////        measureCircleItemHighAndCommentItemOffset(commentConfig);
//
//        if (View.VISIBLE == visibility) {
//            editText.requestFocus();
//            KeyboardUtils.showSoftInput(editText);
//            //弹出键盘
////            Common.UIHandler.postDelayed(() -> Common.pushKeyboard(this), 100);
//        } else if (View.GONE == visibility) {
//            //隐藏键盘
//            Common.hideKeyboard(this, editText);
//        }

    }
    @Override
    public void update2loadData(int loadType, List<CircleItem> datas) {

    }

    @Override
    public void setRefreshing(Boolean isRefresh) {

    }

    @Override
    public List<CircleItem> getAdapterData() {
        return Collections.emptyList();
    }

    @Override
    public void showLoading(String msg) {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showError(String errorMsg) {

    }

    private static class ImageAdapter extends PagerAdapter {

        private List<String> datas = new ArrayList<String>();
        private LayoutInflater inflater;
        private Context context;
        private ImageSize imageSize;
        private ImageView smallImageView = null;

        public void setDatas(List<String> datas) {
            if (datas != null) this.datas = datas;
        }

        public void setImageSize(ImageSize imageSize) {
            this.imageSize = imageSize;
        }

        public ImageAdapter(Context context) {
            this.context = context;
            this.inflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            if (datas == null) return 0;
            return datas.size();
        }


        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            View view = inflater.inflate(R.layout.item_pager_image, container, false);
            if (view != null) {
                final ImageView imageView = (ImageView) view.findViewById(R.id.image);

                if (imageSize != null) {
                    //预览imageView
                    smallImageView = new ImageView(context);
                    FrameLayout.LayoutParams layoutParams;
                    if (null == imageSize) {
                        layoutParams =
                                new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
                                        FrameLayout.LayoutParams.WRAP_CONTENT);
                    } else {
                        layoutParams = new FrameLayout.LayoutParams(imageSize.getWidth(),
                                imageSize.getHeight());
                    }
                    layoutParams.gravity = Gravity.CENTER;
                    smallImageView.setLayoutParams(layoutParams);
                    smallImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    ((FrameLayout) view).addView(smallImageView);
                }

                //loading
                final ProgressBar loading = new ProgressBar(context);
                FrameLayout.LayoutParams loadingLayoutParams =
                        new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                                ViewGroup.LayoutParams.WRAP_CONTENT);
                loadingLayoutParams.gravity = Gravity.CENTER;
                loading.setLayoutParams(loadingLayoutParams);
                ((FrameLayout) view).addView(loading);

                final String imgurl = datas.get(position);

                Glide.with(context).load(imgurl).centerInside().diskCacheStrategy(DiskCacheStrategy.ALL)//缓存多个尺寸
                        .thumbnail(0.1f)//先显示缩略图  缩略图为原图的1/10
                        .into(new DrawableImageViewTarget(imageView) {
                            @Override
                            public void onLoadStarted(Drawable placeholder) {
                                super.onLoadStarted(placeholder);
                               /* if(smallImageView!=null){
                                    smallImageView.setVisibility(View.VISIBLE);
                                    Glide.with(context).load(imgurl).into(smallImageView);
                                }*/
                                loading.setVisibility(View.VISIBLE);
                            }

                            @Override
                            public void onLoadFailed(Drawable errorDrawable) {
                                super.onLoadFailed(errorDrawable);
                                /*if(smallImageView!=null){
                                    smallImageView.setVisibility(View.GONE);
                                }*/
                                loading.setVisibility(View.GONE);
                            }

                            @Override
                            public void onResourceReady(@NonNull Drawable resource,
                                                        @Nullable Transition<? super Drawable> transition) {
                                super.onResourceReady(resource, transition);
                                loading.setVisibility(View.GONE);
                                /*if(smallImageView!=null){
                                    smallImageView.setVisibility(View.GONE);
                                }*/
                            }
                        });

                container.addView(view, 0);
            }
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view.equals(object);
        }

        @Override
        public void restoreState(Parcelable state, ClassLoader loader) {
        }

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


    }

    @Override
    protected void onDestroy() {
        guideViewList.clear();
        super.onDestroy();
    }

    public static class ImageSize implements Serializable {

        private int width;
        private int height;

        public ImageSize(int width, int height) {
            this.width = width;
            this.height = height;
        }

        public int getHeight() {
            return height;
        }

        public void setHeight(int height) {
            this.height = height;
        }

        public int getWidth() {
            return width;
        }

        public void setWidth(int width) {
            this.width = width;
        }
    }
}
