package com.sheep.gamegroup.view.activity;

import android.annotation.SuppressLint;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.kfzs.duanduan.utils.StatusBarUtils;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.absBase.BaseUMActivity;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.FriendAndAwardEntity;
import com.sheep.gamegroup.model.entity.PictureInvitationEntity;
import com.sheep.gamegroup.model.entity.UserEntity;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.transformer.ScaleTransformer;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.GlideImageLoader;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.ViewHolder;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.util.share.ShareLinkConfig;
import com.sheep.gamegroup.view.adapter.AdbCommonRecycler;
import com.sheep.gamegroup.view.adapter.ArrayPagerAdapter;
import com.sheep.jiuyan.samllsheep.BuildConfig;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.ClassFileHelper;
import com.sheep.jiuyan.samllsheep.utils.FileUtil;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;

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

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import rx.functions.Action1;

import static com.sheep.gamegroup.util.ViewUtil.getNetImgByName;

/**
 * Created by realicing on 2018/9/7.
 * realicing@sina.com
 */
public class ActInvitation extends BaseUMActivity {
    @BindView(R.id.ask_share_list)
    RecyclerView ask_share_list;

    GridLayoutManager gridLayoutManager;
    UserEntity userEntity = DataUtil.getInstance().getUserEntity();
    private FriendAndAwardEntity friendAndAwardEntity;
    @BindView(R.id.act_invitation_rl)
    View act_invitation_rl;
    @BindView(R.id.act_invitation_cvp)
    ViewPager viewPager;
    @BindView(R.id.main_layout)
    ConstraintLayout main_layout;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        StatusBarUtils.setTranslucent(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.act_invitation;
    }

    private List<PictureInvitationEntity> mPictureList = new ArrayList<>();
    private List<View> viewArrayList = new ArrayList<>();
    private SparseArray<BitmapFactory.Options> optionsList = new SparseArray<>();

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void initView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            main_layout.setPadding(0, 0, 0, G.getHasVirtualKey(this) - G.getNoHasVirtualKey(this));
        }
        TitleBarUtils.getInstance().setShowOrHide(this, true)
                .setTitle(this, "分享")
                .setTitleFinish(this);
    }

    public void initListener() {
        act_invitation_rl.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return viewPager.dispatchTouchEvent(event);
            }
        });
    }

    @Override
    public void initData() {
        showProgress();
        if (userEntity == null) {
            CommonUtil.getInstance().callActionWithUserInfo(new Action1<UserEntity>() {
                @Override
                public void call(UserEntity userEntity) {
                    load++;
                    checkLoadFinish();
                    checkLoadLinkAndDesFinish();
                }
            });
        } else {
            load++;
        }
        SheepApp.getInstance()
                .getNetComponent()
                .getApiService()
                .getSharePicture()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        load++;
                        mPictureList.addAll(baseMessage.getDataList(PictureInvitationEntity.class));
                        loadData();
                        checkLoadFinish();
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        load++;
                        checkLoadFinish();
                        G.showToast(baseMessage);
                    }
                });

        SheepApp.getInstance().getNetComponent().getApiService().FriendCountAndAward()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        load++;
                        if (BuildConfig.DEBUG)
                            G.showToast(baseMessage);
                        checkLoadFinish();
                        checkLoadLinkAndDesFinish();
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        load++;
                        if (baseMessage != null) {
                            friendAndAwardEntity = baseMessage.getData(FriendAndAwardEntity.class);
                        }
                        checkLoadFinish();
                        checkLoadLinkAndDesFinish();

                    }
                });
    }

    private int load = 0;

    private void checkLoadLinkAndDesFinish() {
        if (userEntity != null && friendAndAwardEntity != null) {
            init(userEntity.getShareLink(), friendAndAwardEntity.getShare_desc());
        }
    }

    private void checkLoadFinish() {
        if (load == 3) {
            hideProgress();
        }
    }

    private void loadData() {
        int size = 0;
        for (final PictureInvitationEntity item : mPictureList) {
            final View itemView = LayoutInflater.from(SheepApp.getInstance()).inflate(R.layout.item_image2, null);

            final View image_container = itemView.findViewById(R.id.image_container);
            final ImageView image_full = itemView.findViewById(R.id.image_full);
            final View image_bottom_top = itemView.findViewById(R.id.image_bottom_top);
            final ImageView image_bottom = itemView.findViewById(R.id.image_bottom);
            final ImageView image_logo = itemView.findViewById(R.id.image_logo);
            final TextView image_tip = itemView.findViewById(R.id.image_tip);
            final RequestListener<Drawable> listener = new RequestListener<Drawable>() {
                @Override
                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                    item.setLoaded(false);
                    return false;
                }

                @Override
                public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                    item.setLoaded(true);
                    return false;
                }
            };
            String name = String.valueOf(item.getPicture().hashCode());

//            if(item.getPicture() != null)
//                GlideImageLoader.downloadAndRoundedImage(name, item.getPicture(), image_full, getResources().getDimensionPixelSize(R.dimen.content_padding_8), listener);
            final int index = size;
            viewArrayList.add(itemView);
            viewList.put(size, itemView);
            GlideImageLoader.downLoadImage(name, item.getPicture(), new Action1<File>() {
                @Override
                public void call(File file) {
                    if (file == null) {
                        return;
                    }
                    BitmapFactory.Options options = FileUtil.getImageOptions(file);
                    final int w = options.outWidth;
                    final int h = options.outHeight;
                    optionsList.put(index, options);
//                int w = width;
//                int h = width * options.outHeight / options.outWidth;
                    Glide.with(SheepApp.getInstance())
                            .load(file)
                            .listener(listener)
                            .apply(new RequestOptions().disallowHardwareConfig().override(w, h).transform(new RoundedCorners(getResources().getDimensionPixelSize(R.dimen.content_padding_8))))
                            .into(image_full);
                    updateLayoutParams(index, 500L);
                }
            });
            //之前的方法实际上没有实现圆角效果
//            Glide.with(SheepApp.getInstance())
//                    .load(item.getPicture())
//                    .listener(listener)
//                    .apply(new RequestOptions().transform(new RoundedCorners((int) getResources().getDimension(R.dimen.content_padding_8))).fitCenter())
//                    .into(image_full);
            size++;
        }
        ArrayPagerAdapter adapter = new ArrayPagerAdapter(viewArrayList);
        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(size);
        viewPager.setPageTransformer(true, new ScaleTransformer());
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                curPosition = position;
                updateLayoutParams(position, 50L);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        if (size > 2)
            viewPager.setCurrentItem((size - 1) / 2, false);
    }

    private void updateLayoutParams(int position, long time) {
        BitmapFactory.Options options = optionsList.get(position);
        if (options == null) {
            return;
        }
        View itemView = viewArrayList.get(position);
        final PictureInvitationEntity item = mPictureList.get(position);
        final int w = options.outWidth;
        final int h = options.outHeight;
        final View image_container = itemView.findViewById(R.id.image_container);
        final View image_bottom_top = itemView.findViewById(R.id.image_bottom_top);
        final ImageView image_bottom = itemView.findViewById(R.id.image_bottom);
        final ImageView image_logo = itemView.findViewById(R.id.image_logo);
        final TextView image_tip = itemView.findViewById(R.id.image_tip);
        if (viewPager != null) {
            viewPager.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (image_container == null || viewPager == null || image_bottom == null || image_logo == null || image_bottom_top == null || image_tip == null) {
                        return;
                    }
                    image_container.setVisibility(View.VISIBLE);
                    int vWidth = viewPager.getWidth();
                    int vHeight = viewPager.getHeight();
                    float imgWidth = vWidth;
                    float imgHeight = vHeight;
                    int imgHeightPadding = 0;
                    if (vHeight * 1.0F / vWidth > h * 1.0F / w) {//图片上下有padding
                        imgHeight = imgWidth * h / w;
                        imgHeightPadding = (int) ((vHeight - imgHeight) / 2);
                    } else {//图片左右有padding
                        imgWidth = imgHeight * w / h;
                    }

                    float containerWidthRadius = 60 / 216F;
                    float containerHeightRadius = 70 / 216F;
                    float rqRadius = 53 / 216F;
                    float tipRadius = 5 / 216F;
                    float radius = 4 / 216F;
                    float topRadius = 2 / 216F;
                    float logoRadius = rqRadius * 16 / 68;
                    GlideImageLoader.saveAndSetRqImageDisHardConfig(image_bottom, item.getLink(), (int) (imgWidth * rqRadius));
                    //重新设置logo的宽高
                    ViewGroup.LayoutParams layoutParams = image_logo.getLayoutParams();
                    layoutParams.width = (int) (imgWidth * logoRadius);
                    layoutParams.height = (int) (imgWidth * logoRadius);
                    image_logo.setLayoutParams(layoutParams);
                    //重新设置二维码上部的距离
                    ViewGroup.LayoutParams layoutParamsTop = image_bottom_top.getLayoutParams();
                    layoutParamsTop.height = (int) (imgWidth * topRadius);
                    image_bottom_top.setLayoutParams(layoutParamsTop);
                    //重新设置《扫我开始赚钱》的高度
                    ViewGroup.LayoutParams layoutParamsTip = image_tip.getLayoutParams();
                    layoutParamsTip.height = (int) (imgWidth * (tipRadius + topRadius * 3 / 2));
                    image_tip.setLayoutParams(layoutParamsTip);
                    image_tip.setTextSize(imgWidth * tipRadius / G.DENSITY);
                    //重新设置整个二维码外容器的高度
                    RelativeLayout.LayoutParams layoutParamsContainer = (RelativeLayout.LayoutParams) image_container.getLayoutParams();
                    layoutParamsContainer.width = (int) (imgWidth * containerWidthRadius);
                    layoutParamsContainer.height = (int) (imgWidth * containerHeightRadius);
                    layoutParamsContainer.bottomMargin = imgHeightPadding;
                    image_container.setLayoutParams(layoutParamsContainer);
                    Drawable bg = image_container.getBackground();
                    if (bg instanceof GradientDrawable) {
                        ((GradientDrawable) bg).setCornerRadius(imgWidth * radius);
                    }
                }
            }, time);
        }
    }

    private int curPosition = 0;
    private SparseArray<View> viewList = new SparseArray<>();

    private void init(final String url, final String description) {
        gridLayoutManager = new GridLayoutManager(this, 5);
        ask_share_list.setLayoutManager(gridLayoutManager);
        final List<String> list = ListUtil.emptyList();
        list.add(ShareLinkConfig.FACE_TO_FACE);
        list.add(ShareLinkConfig.WX);
        list.add(ShareLinkConfig.QQ);
        list.add(ShareLinkConfig.WEIXIN_CIRCLE);
        list.add(ShareLinkConfig.COPY_SHARE_LINK);
        final List<String> imgList = ListUtil.emptyList();
        imgList.add("share_face_to_face");
        imgList.add("share_wx");
        imgList.add("share_qq");
        imgList.add("share_weixin_circle");
        imgList.add("share_copy_share_link");
        final List<String> nameList = ListUtil.emptyList();
        nameList.add("面对面");
        nameList.add("微信");
        nameList.add("QQ好友");
        nameList.add("朋友圈");
        nameList.add("复制链接");
        AdbCommonRecycler<String> adapter = new AdbCommonRecycler<String>(this, list) {
            @Override
            public int getViewIdByType(int type) {
                return R.layout.ask_to_share_item;
            }

            @Override
            public void convert(ViewHolder holder, final String item) {
                View itemView = holder.itemView;
                if (item == null)
                    return;
                ImageView ask_to_share_item_img = itemView.findViewById(R.id.ask_to_share_item_img);
                TextView ask_to_share_item_name = itemView.findViewById(R.id.ask_to_share_item_name);
                final int position = holder.getAdapterPosition();
                GlideImageLoader.setImageDisHardConfig(ask_to_share_item_img, getNetImgByName(imgList.get(position)));
                ask_to_share_item_name.setText(nameList.get(position));
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        File file;
                        PictureInvitationEntity picItem = ListUtil.getItem(mPictureList, curPosition);
                        if (picItem != null && picItem.isLoaded()) {
                            try {
                                String fileName = String.format(Locale.CHINA, "share%d%s%d.jpg", curPosition, BuildConfig.FLAVOR, picItem.getPicture().hashCode());
                                file = new File(ClassFileHelper.DIR, fileName);
                                if (!file.exists()) {
                                    file = ViewUtil.saveImage(viewList.get(curPosition), ClassFileHelper.DIR, fileName);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                G.showToast(e.getMessage());
                                return;
                            }
                        } else {
                            G.showToast("图片正在加载中，请稍等");
                            return;
                        }
                        new ShareLinkConfig().setLink(url).setShareType(item).setDes(description).setFile(file).setType(ShareLinkConfig.IMG).toShare(ActInvitation.this);
                    }
                });
            }
        };
        ask_share_list.setAdapter(adapter);
    }

}
