package com.tjzhxx.union.activity;

import android.content.Intent;
import android.graphics.Matrix;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.Lifecycle;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.tjzhxx.union.R;
import com.tjzhxx.union.entity.BannerEntity;
import com.tjzhxx.union.entity.BaseResponse;
import com.tjzhxx.union.fragment.ActivityListFragment;
import com.tjzhxx.union.fragment.NewListFragment;
import com.tjzhxx.union.public_store.ConstDefine;
import com.tjzhxx.union.public_store.ScreenUtils;
import com.tjzhxx.union.public_store.fragment.FragmentPager;
import com.tjzhxx.union.public_store.fragment.FragmentTab;
import com.tjzhxx.union.public_store.retrofit.RetrofitUtils;
import com.tjzhxx.union.public_store.retrofit.UnionServices;
import com.tjzhxx.union.public_store.rx.DefaultSubscriber;
import com.tjzhxx.union.system.BaseActivity;
import com.tjzhxx.union.system.WebviewActivity;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;

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

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.bgabanner.BGABanner;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 描述:
 *
 * @author yhx
 * @create 2021/9/2  8:57 AM
 */
public class NewListActivity extends BaseActivity implements FragmentPager.FragmentPagerListener {

    @BindView(R.id.bga_banner)
    BGABanner bgaBanner;
    @BindView(R.id.news)
    TextView news;
    @BindView(R.id.activity)
    TextView activity;
    @BindView(R.id.iv_header_cursor)
    ImageView ivCursor;
    @BindView(R.id.fragment_continer)
    FragmentPager fragmentPager;
    private FragmentTab fragmentTab;
    private List<BannerEntity> bannerEntities = new ArrayList<>();
    public int currIndex = 0;
    private FragmentTab[] majorTabs;
    private Class<? extends Fragment>[] fragments;
    private float offset = 0;
    private UnionServices services;

    @Override
    public int getContentViewLayoutID() {
        return R.layout.activity_new_list;
    }

    @Override
    public void bindViewAndEvent(Bundle savedInstanceState) {
        initTitle("工会新闻");
        fragmentTab = new FragmentTab(this);
        majorTabs = new FragmentTab[]{fragmentTab, fragmentTab};
        fragments = new Class[]{NewListFragment.class, ActivityListFragment.class};
        fragmentPager.init(this.getSupportFragmentManager(), this)
                .setTabAndFragmentData(majorTabs, fragments)
                .setCanScroll(true);
        initCursor();
        fragmentPager.setOffscreenPageLimit(5);
        fragmentPager.setCurrentItem(0);
        init();
    }


    private void init() {
        services = RetrofitUtils.createApi(UnionServices.class, ConstDefine.HttpAdress);
        bgaBanner.setAdapter(new BGABanner.Adapter<ImageView, String>() {
            @Override
            public void fillBannerItem(BGABanner banner, ImageView itemView, String model, int position) {
                Glide.with(NewListActivity.this)
                        .load(model)
                        .placeholder(R.mipmap.bg_placeholder)
                        .error(R.mipmap.bg_placeholder)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .centerCrop()
                        .dontAnimate()
                        .into(itemView);
            }
        });
        bgaBanner.setDelegate(new BGABanner.Delegate() {
            @Override
            public void onBannerItemClick(BGABanner banner, View itemView, Object model, int position) {
                if (bannerEntities != null && bannerEntities.size() > 0) {
                    BannerEntity entity = bannerEntities.get(position);
                    Intent intent = new Intent();
                    intent.setClass(NewListActivity.this, WebviewActivity.class);
                    intent.putExtra("url", entity.getWxurl());
                    intent.putExtra("title", "工会新闻");
                    startActivity(intent);
                }
            }
        });
        getBanners();
    }
    /**
     * 加载广告
     */
    private void getBanners() {
        services.querytitlelist()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(AutoDispose.<BaseResponse<List<BannerEntity>>>autoDisposable(AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)))
                .subscribe(new DefaultSubscriber<BaseResponse<List<BannerEntity>>>(this) {
                    @Override
                    public void success(BaseResponse<List<BannerEntity>> value) {
                        bannerEntities = value.getData();
                        List<String> urls = new ArrayList<>();
                        List<String> titles = new ArrayList<>();
                        if (value.getData() != null) {
                            for (BannerEntity entity : value.getData()) {
                                if (!TextUtils.isEmpty(entity.getPicurl())) {
                                    urls.add(entity.getPicurl());
                                    titles.add(entity.getWxtitle());
                                }
                            }
                            bgaBanner.setData(urls, titles);
                        }
                    }

                });
    }

    @OnClick({R.id.news, R.id.activity})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.news:
                fragmentPager.setCurrentItem(0);
                break;
            case R.id.activity:
                fragmentPager.setCurrentItem(1);
                break;
        }
    }

    private void setTab(int olditem, int index) {
        if (index == 0) {
            initTab();
            news.setTextColor(getResources().getColor(R.color.red));
            news.setTextSize(ScreenUtils.sp2px(this,7));
        } else if (index == 1) {
            initTab();
            activity.setTextColor(getResources().getColor(R.color.red));
            activity.setTextSize(ScreenUtils.sp2px(this,7));
        }
        anim(olditem, index);
    }

    private void initTab() {
        news.setTextColor(getResources().getColor(R.color.text_black_333));
        news.setTextSize(ScreenUtils.sp2px(this,6));
        activity.setTextColor(getResources().getColor(R.color.text_black_333));
        activity.setTextSize(ScreenUtils.sp2px(this,6));
    }

    private void anim(int olditem, int newitem) {
        Animation animation = null;
        animation = new TranslateAnimation(olditem * offset, newitem * offset, 0, 0);
        animation.setFillAfter(true);// True:图片停在动画结束位置
        animation.setDuration(200);
        ivCursor.startAnimation(animation);
    }

    private void initCursor() {
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenW = dm.widthPixels;// 获取分辨率宽度
        offset = screenW / 2;// 计算偏移量
        Matrix matrix = new Matrix();
        matrix.postTranslate(offset, 0);
        ivCursor.setImageMatrix(matrix);// 设置动画初始位置
        LinearLayout.LayoutParams lp_ivcursor = (LinearLayout.LayoutParams) ivCursor.getLayoutParams();
        int width = lp_ivcursor.width;
        lp_ivcursor.setMargins((int) (offset - width) / 2, 0, 0, 0);
        ivCursor.setLayoutParams(lp_ivcursor);
    }

    @Override
    public void onItemChanged(int oldItem, int newItem, String tabDiscription) {
        currIndex = newItem;
        setTab(oldItem, newItem);
    }

    @Override
    public boolean boforeItemChangedItemEnable(int currentItem) {
        return true;
    }

    @Override
    public void controlItemEnable(int item, boolean enable) {

    }
}
