package com.danding.yang800;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
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.bumptech.glide.request.target.Target;
import com.danding.yang800.Adapter.DocumentRecyAdapter;
import com.danding.yang800.Entity.ThumbViewInfo;
import com.danding.yang800.General.DocumentSpaceItemDecoration;
import com.danding.yang800.Presenter.DocumentActivityPresenter;
import com.danding.yang800.Util.ImgUtils;
import com.danding.yang800.Util.LogUtil;
import com.danding.yang800.Util.StatusColorUtil;
import com.danding.yang800.Util.ToastUtil;
import com.danding.yang800.View.EllipsizingTextView;
import com.danding.yang800.View.NetworkProgressDialog;
import com.danding.yang800.View.PreviewLayout;
import com.yanzhenjie.sofia.Sofia;

import java.util.ArrayList;
import java.util.List;

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

public class DocumentActivity extends BaseActivity {
    @BindView(R.id.document_contentTv)
    TextView document_contentTv;
    @BindView(R.id.document_backTv)
    TextView document_backTv;
    @BindView(R.id.document_copyUrlLayout)
    RelativeLayout document_copyUrlLayout;
    @BindView(R.id.document_copyContentLayout)
    RelativeLayout document_copyContentLayout;
    @BindView(R.id.document_saveImageLayout)
    RelativeLayout document_saveImageLayout;
    @BindView(R.id.document_recycler_view)
    RecyclerView document_recycler_view;
    @BindView(R.id.document_titleTv)
    TextView document_titleTv;
    @BindView(R.id.document_View)
    LinearLayout document_View;
    private FrameLayout mContentContainer;
    private int mStatusBarHeight;
    private LinearLayout.LayoutParams mLayoutParams;
    private List<ThumbViewInfo> mThumbViewInfoList = new ArrayList<>();
    private GridLayoutManager mGridLayoutManager;
    private PreviewLayout mPreviewLayout;
    private int mSolidWidth = 0;
    private int mSolidHeight = 0;
    private int[] mPadding = new int[4];
    private Rect mRVBounds = new Rect();
    DocumentRecyAdapter adapter;
    NetworkProgressDialog pd;
    DocumentActivityPresenter presenter;
    String ifUp;
    String goodsUrl;
    SharedPreferences sp;
    @BindView(R.id.document_scollView)
    ScrollView document_scollView;
    @BindView(R.id.document_scollLayout)
    LinearLayout document_scollLayout;

    @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_document);
        Sofia.with(this).statusBarDarkFont().statusBarBackground(ContextCompat.getColor(this, R.color.white));
        sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
        ButterKnife.bind(this);
//        findView();
        presenter = new DocumentActivityPresenter(this);
        Intent intent = getIntent();
        String goodsSn = intent.getStringExtra("goodsSn");
        ifUp = intent.getStringExtra("ifUp");
        goodsUrl = intent.getStringExtra("goodsUrl");
        int resId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        mStatusBarHeight = getResources().getDimensionPixelSize(resId);
        mContentContainer = (FrameLayout) findViewById(android.R.id.content);
        DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
        mLayoutParams = new LinearLayout.LayoutParams(metrics.widthPixels / 3, metrics.widthPixels / 3);
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        int screenWidth = display.getWidth();
        int space = 9 * screenWidth / 750;
        document_recycler_view.addItemDecoration(new DocumentSpaceItemDecoration(space));
        mGridLayoutManager = new GridLayoutManager(this, 3);
        document_recycler_view.setLayoutManager(mGridLayoutManager);
        document_recycler_view.setHasFixedSize(true);
        presenter.query(sp.getString("storeId", ""), goodsSn);
//        for (int i = 0; i < 6; i++) {
//            mThumbViewInfoList.add(new ThumbViewInfo("http://www.hibigoo.com/statics/attachment//store/0/goods/201612221402517814_thumbnail.jpg", i));
//        }
//        adapter = new DocumentRecyAdapter(this, mThumbViewInfoList, mContentContainer);
//        document_recycler_view.setAdapter(adapter);
//        adapter.notifyDataSetChanged();
//        document_recycler_view.setAdapter(adapter);
//        document_recycler_view.addOnItemTouchListener(new OnItemClickListener() {
//            @Override
//            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
//                mPreviewLayout = new PreviewLayout(DocumentActivity.this);
//                mPreviewLayout.setData(mThumbViewInfoList, position);
//                mPreviewLayout.startScaleUpAnimation();
//                mContentContainer.addView(mPreviewLayout);
//            }
//        });
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            //if (mThumbViewInfoList != null && mThumbViewInfoList.size() > 0) {
            document_recycler_view.getGlobalVisibleRect(mRVBounds);
//                assembleDataList();
//            }
        }
    }

//    private void findView() {
//        document_contentTv.setMaxLines(3);
//        document_contentTv.setMaxLength(65);
//    }

    @OnClick({R.id.document_backTv, R.id.document_copyUrlLayout, R.id.document_copyContentLayout,
            R.id.document_saveImageLayout})
    public void onViewClicked(View view) {
        ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        switch (view.getId()) {
            case R.id.document_backTv:
                finish();
                break;
            case R.id.document_copyUrlLayout:
                if (ifUp.equals("已上架")) {
                    cm.setText(goodsUrl);
                    ToastUtil.show(DocumentActivity.this, "复制链接成功");
                } else {
                    ToastUtil.show(DocumentActivity.this, "请先上架商品");
                }
                break;
            case R.id.document_copyContentLayout:
                cm.setText(document_contentTv.getText());
                ToastUtil.show(DocumentActivity.this, "复制文案成功");
                break;
            case R.id.document_saveImageLayout:
                initDialog();
                if (mThumbViewInfoList != null) {
                    if (mThumbViewInfoList.size() > 0) {
                        for (int i = 0; i < mThumbViewInfoList.size(); i++) {
                            Glide.with(this)
                                    .load(mThumbViewInfoList.get(i).getUrl())
                                    .asBitmap()
                                    .dontAnimate()
                                    .into(new SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {
                                        @Override
                                        public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
                                            boolean save = ImgUtils.saveImageToGallery(DocumentActivity.this, resource);
                                            if (save) {
                                                dismissDialog();
                                                ToastUtil.show(DocumentActivity.this, "保存成功");
                                            }
                                        }
                                    });
                        }
                    } else {
                        dismissDialog();
                    }
                } else {
                    dismissDialog();
                }
                break;
        }
    }

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

    private void assembleDataList() {
        computeBoundsForward(0);
        computeBoundsBackward(0);
    }

    /**
     * 从第一个完整可见item顺序遍历
     */
    private void computeBoundsForward(final int firstCompletelyVisiblePos) {
        document_View.post(new Runnable() {
            @Override
            public void run() {
//        document_View.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
//            @Override
//            public void onGlobalLayout() {
                for (int i = firstCompletelyVisiblePos; i < mThumbViewInfoList.size(); i++) {
                    View itemView = mGridLayoutManager.findViewByPosition(i);
                    Rect bounds = new Rect();
                    if (itemView != null) {
                        ImageView thumbView = (ImageView) itemView.findViewById(R.id.document_itemIv);
                        thumbView.getGlobalVisibleRect(bounds);
                        if (mSolidWidth * mSolidHeight == 0) {
                            mPadding[0] = thumbView.getPaddingLeft();
                            mPadding[1] = thumbView.getPaddingTop();
                            mPadding[2] = thumbView.getPaddingRight();
                            mPadding[3] = thumbView.getPaddingBottom();
                            mSolidWidth = bounds.width();
                            mSolidHeight = bounds.height();
                        }
                        bounds.left = bounds.left + mPadding[0];
                        bounds.top = bounds.top + mPadding[1];
                        bounds.right = bounds.left + mSolidWidth - mPadding[2];
                        bounds.bottom = bounds.top + mSolidHeight - mPadding[3];
                    } else {
                        bounds.left = i % 3 * mSolidWidth + mPadding[0];
                        bounds.top = mRVBounds.bottom + mPadding[1];
                        bounds.right = bounds.left + mSolidWidth - mPadding[2];
                        bounds.bottom = bounds.top + mSolidHeight - mPadding[3];
                    }
                    bounds.offset(0, -mStatusBarHeight);

                    mThumbViewInfoList.get(i).setBounds(bounds);
//                    if (Build.VERSION.SDK_INT >= 16) {
//                        document_View.getViewTreeObserver().removeOnGlobalLayoutListener(this);
//                    } else {
//                        document_View.getViewTreeObserver().removeGlobalOnLayoutListener(this);
//                    }
                }
            }
        });
    }

    /**
     * 从第一个完整可见item逆序遍历，如果初始位置为0，则不执行方法内循环
     */
    private void computeBoundsBackward(int firstCompletelyVisiblePos) {
        for (int i = firstCompletelyVisiblePos - 1; i >= 0; i--) {
            View itemView = mGridLayoutManager.findViewByPosition(i);
            Rect bounds = new Rect();
            if (itemView != null) {
                ImageView thumbView = (ImageView) itemView.findViewById(R.id.document_itemIv);

                thumbView.getGlobalVisibleRect(bounds);

                bounds.left = bounds.left + mPadding[0];
                bounds.bottom = bounds.bottom - mPadding[3];
                bounds.right = bounds.left + mSolidWidth - mPadding[2];
                bounds.top = bounds.bottom - mSolidHeight + mPadding[1];
            } else {
                bounds.left = i % 3 * mSolidWidth + mPadding[0];
                bounds.bottom = mRVBounds.top - mPadding[3];
                bounds.right = bounds.left + mSolidWidth - mPadding[2];
                bounds.top = bounds.bottom - mSolidHeight + mPadding[1];
            }
            bounds.offset(0, -mStatusBarHeight);

            mThumbViewInfoList.get(i).setBounds(bounds);

        }
    }

    @Override
    public void onBackPressed() {
        if (mContentContainer.getChildAt(mContentContainer.getChildCount() - 1) instanceof PreviewLayout) {
            mPreviewLayout.startScaleDownAnimation();
            return;
        }
        super.onBackPressed();
    }

    public void openImage(int position) {
        mPreviewLayout = new PreviewLayout(this);
        mPreviewLayout.setData(mThumbViewInfoList, position);
        mPreviewLayout.startScaleUpAnimation();
        mContentContainer.addView(mPreviewLayout);
    }

    public void updateData(String title, String content, List<ThumbViewInfo> list) {
//        document_recycler_view.getGlobalVisibleRect(mRVBounds);
//        assembleDataList();
        boolean canscoll = canScoll(content, list.size());
        if (!canscoll) {
            document_scollView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    return true;
                }
            });
        }
        document_titleTv.setText(title);
        document_contentTv.setText(content);
        mThumbViewInfoList.addAll(list);
        adapter = new DocumentRecyAdapter(this, mThumbViewInfoList, mContentContainer);
        document_recycler_view.setAdapter(adapter);
        // adapter.notifyDataSetChanged();
        //  document_recycler_view.getGlobalVisibleRect(mRVBounds);
        assembleDataList();
    }

    public boolean canScoll(String content, int size) {
        int line;
        if (size <= 3) {
            line = 1;
        } else if (size > 3 && size <= 6) {
            line = 2;
        } else {
            line = 3;
        }
        int height = 123 + content.length() / 26 * 24 + line * 220;
        boolean scoll = height > 807 ? true : false;
        return scoll;
    }
}
