package com.kfzs.duanduan.view;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.utils.G;

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


/**
 * @ Created by Dlg
 * @ <p>TiTle:  ImageGlarry</p>
 * @ <p>Description: 图片轮播功能，点击图片能预览</p>
 * @ date:  2016/5/16 20:21
 * @ QQ:    315096953
 */
public class ImageGlarry {

    private Activity mActivity;
    private ViewPager mViewPager;
    private RadioGroup mRadioGroup;
    private List<String> mList = new ArrayList<>();
    private int mIntDelayTime = 4000;
    private List<ImageView> mListImages = new ArrayList<>();
    private View mLastSelect;
    private boolean mIsMoved = false;

    public ImageGlarry(Activity activity, ViewPager viewPager, RadioGroup radioGroup) {
        mActivity = activity;
        mViewPager = viewPager;
        mRadioGroup = radioGroup;
    }


    public void setmIntDelayTime(int mIntDelayTime) {
        this.mIntDelayTime = mIntDelayTime;
    }

    public ImageGlarry init(String[] pics) {
        return init(pics, ImageView.ScaleType.CENTER_INSIDE);
    }

    /**
     * 初始化组件
     *
     * @param pics 图片Url完整地址。
     */
    public ImageGlarry init(String[] pics, ImageView.ScaleType scaleType) {
        int pos = 0;
        mList.clear();
        mListImages.clear();
        mLastSelect = null;
        mRadioGroup.removeAllViews();
        //防止loading图案被放得很大很大
        for (String pic : pics) {
            if (pic.length() < 2) {
                continue;
            }
            mList.add(pic);
            ImageView imageView = new ImageView(mActivity);
            imageView.setOnClickListener(new cls_main(pos));
            imageView.setScaleType(scaleType);
            Glide.with(mActivity).load(pic).apply(new RequestOptions().dontAnimate()).into(imageView);
            mListImages.add(imageView);


            RadioButton radioButton = (RadioButton) View.inflate(mActivity, R.layout.rbt_dot, null);
            mRadioGroup.addView(radioButton);
            LinearLayout.LayoutParams layoutParams = new LinearLayout
                    .LayoutParams(G.getRealPix(5
            ), G.getRealPix(5));
            layoutParams.setMargins(G.getRealPix(2), 0, G.getRealPix(2), 0);
            radioButton.setLayoutParams(layoutParams);
//            radioButton.setButtonDrawable(null);
//            radioButton.setBackgroundResource(R.drawable.sel_circle_dot);

            if (pos == 0) {
                selectPosition(0);
            }
            pos = pos + 1;
        }

        if (mList.size() > 1) {//有两张或以上图片，开始轮播
            if (!mIsMoved) {
                mIsMoved = true;
                handler.sendEmptyMessageDelayed(0, mIntDelayTime);
            }
            //handler.sendEmptyMessageDelayed(1, mIntDelayTime);
        } else if (mList.size() == 1) {//如果只有一个或没有，就隐藏Group
            mRadioGroup.setVisibility(View.GONE);
        } else {//说明是空的。
            mViewPager.setBackgroundColor(mActivity.getResources().getColor(R.color.white));
            return this;
        }

        mViewPager.setAdapter(pagerAdapter);
        mViewPager.setCurrentItem(0);
        mViewPager.addOnPageChangeListener(onPageChangeListener);
        return this;
    }

    /**
     * 设置当前选中项
     *
     * @param position
     */
    private void selectPosition(int position) {
        mLastSelect = mRadioGroup.getChildAt(position);
        mRadioGroup.check(mLastSelect.getId());
        LinearLayout.LayoutParams layoutParams = new LinearLayout
                .LayoutParams(G.getRealPix(10
        ), G.getRealPix(5));
        layoutParams.setMargins(G.getRealPix(2), 0, G.getRealPix(2), 0);
        mRadioGroup.getChildAt(position).setLayoutParams(layoutParams);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mActivity.isFinishing() || mList.size() < 2) {
                return;
            }
            if (mViewPager.getCurrentItem() >= mList.size() - 1) {
                mViewPager.setCurrentItem(0, true);
            } else {
                mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1, true);
            }
            sendEmptyMessageDelayed(0, mIntDelayTime);
        }
    };

    /**
     * 选取
     */
    private ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        /**
         * 改变dot的宽度等操作
         * @param position
         */
        @Override
        public void onPageSelected(int position) {
            if (mLastSelect != null) {
                LinearLayout.LayoutParams layoutParams = new LinearLayout
                        .LayoutParams(G.getRealPix(5
                ), G.getRealPix(5));
                layoutParams.setMargins(G.getRealPix(2), 0, G.getRealPix(2), 0);
                mLastSelect.setLayoutParams(layoutParams);
            }
            selectPosition(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };


    /**
     * ViewPager
     */
    private PagerAdapter pagerAdapter = new PagerAdapter() {
        @Override
        public int getCount() {
            return mList.size();
        }

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

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

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(mListImages.get(position));
            return mListImages.get(position);
        }
    };


    private AdapterView.OnItemClickListener onItemClickListener;

    /**
     * 设置点击回调，回调仅回传View和position
     *
     * @param onItemClickListener
     */
    public void setOnItemClickListener(AdapterView.OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    private class cls_main implements View.OnClickListener {
        private int position;

        public cls_main(int pos) {
            position = pos;
        }

        @Override
        public void onClick(View v) {
            if (onItemClickListener != null) {
                onItemClickListener.onItemClick(null, v, position, 0);
            }
        }
    }
}
