package com.beanpodtech.allinone.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.viewpager.widget.ViewPager;

import com.beanpodtech.allinone.activity.FaceToFaceVideoActivity;
import com.beanpodtech.allinone.activity.FreetrialActivity;
import com.beanpodtech.allinone.activity.IncreasedclassActivity;
import com.beanpodtech.allinone.activity.LoginActivity;
import com.beanpodtech.allinone.activity.StudyplanActivity;
import com.beanpodtech.allinone.R;
import com.beanpodtech.allinone.adapter.Classdisplay;
import com.beanpodtech.allinone.bean.AllClassdisplay;
import com.beanpodtech.allinone.bean.Carousel;
import com.beanpodtech.allinone.http.UrlConfig;
import com.beanpodtech.allinone.utils.Contants;
import com.beanpodtech.allinone.utils.HttpUtils;
import com.beanpodtech.allinone.utils.OkGoBuilder;
import com.beanpodtech.allinone.utils.OkGoUtil;
import com.beanpodtech.allinone.utils.SpUtil;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.lzy.okgo.model.Response;

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

import cn.bingoogolapple.bgabanner.BGABanner;
import okhttp3.RequestBody;


public class HomeFragment extends Fragment {
    private final String TAG = "HomeFragment";
    private Context mContext;
    List<AllClassdisplay.ListBean> list_classdisplay;
    Intent intent;
    TextView data;
    String userId = SpUtil.getInstace().getString(Contants.USER_ID, null);
    HashMap<String, String> map = new HashMap<>();
    ImageButton add;
    Bundle bundle;
    List<Carousel.ListBean.UrlBean> list;
    private OnButtonClick onButtonClick;
    private Message message;
    private RecyclerView mRecyclerView;
    Classdisplay classdisplay;
    View view;
    ImageView nineClass, studyPlan, freeTrialArea, videoFaceToFace;
    private int[] images = new int[]{R.drawable.carousel};
    private Animation[] animation = new Animation[2];
    private RequestOptions requestOptions;
    private Gson gson;
    private int delayTime = 0;
    private BGABanner banner;


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        requestOptions = new RequestOptions()
                .placeholder(R.drawable.banner_temp)
//                .skipMemoryCache(true)//跳过内存缓存
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE);
//                .diskCacheStrategy(DiskCacheStrategy.NONE);
        view = inflater.inflate(R.layout.home_fragment, container, false);
        banner = view.findViewById(R.id.banner);
        carouselHttp(view);
//        viewFlipper = view.findViewById(R.id.viewFlipper);
        nineClass = view.findViewById(R.id.nine_classes);
        studyPlan = view.findViewById(R.id.study_plan);
        videoFaceToFace = view.findViewById(R.id.video_face_to_face_iv);
        mRecyclerView = view.findViewById(R.id.home_recycview);
        gson = new Gson();
        freeTrialArea = view.findViewById(R.id.free_trial_area);
        add = view.findViewById(R.id.increase);
        nineClass.setOnClickListener(click);
        add.setOnClickListener(click);
        studyPlan.setOnClickListener(click);
        freeTrialArea.setOnClickListener(click);
        videoFaceToFace.setOnClickListener(click);

        return view;
    }

    public void initdata() {
        boolean stat = SpUtil.getInstace().getBoolean(Contants.LOGIN_STATE, true);
        if (stat == false) {
            if (userId != null) {
                map.put("userId", userId);
                final RequestBody body = HttpUtils.getRequestJson(map);
                OkGoBuilder.getInstance().url(UrlConfig.CLASSDISPLAY).method(OkGoBuilder.PSOT).cls(AllClassdisplay.class).
                        Builder(getActivity()).requestBody(body).callback(new OkGoUtil<AllClassdisplay>(AllClassdisplay.class) {
                    @Override
                    public void onSuccess(Response<AllClassdisplay> response) {
                        if (response.body() instanceof AllClassdisplay) {
                            AllClassdisplay body = response.body();
                            list_classdisplay = body.getList();
                            mRecyclerView.setAdapter(classdisplay = new Classdisplay(list_classdisplay, mContext));
                            mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(1,
                                    StaggeredGridLayoutManager.HORIZONTAL));
                            mRecyclerView.setItemAnimator(new DefaultItemAnimator());
                        }
                    }
                }).build();
            }

        }
    }

    View.OnClickListener click = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            boolean stat = SpUtil.getInstace().getBoolean(Contants.LOGIN_STATE, true);
            if (stat == false) {
                switch (view.getId()) {
                    case R.id.increase:
                        intent = new Intent();
                        intent.setClass(getActivity(), IncreasedclassActivity.class);
                        intent.putExtra("list", (Serializable) list_classdisplay);
                        startActivity(intent);
                        break;
                    case R.id.free_trial_area:
                        Bundle bundle = new Bundle();
                        bundle.putString(Contants.CLASS_NAME, "免费体验区");
                        FreetrialActivity.startActivity(getActivity(), bundle);
                        break;
                    case R.id.nine_classes:
                        if (onButtonClick != null) {
                            onButtonClick.onClick(nineClass);
                        }
                        break;
                    case R.id.study_plan:
                        intent = new Intent(getActivity(), StudyplanActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.video_face_to_face_iv:
                        intent = new Intent(getActivity(), FaceToFaceVideoActivity.class);
                        startActivity(intent);
//                        try {
//                            intent = view.getContext().getPackageManager().getLaunchIntentForPackage("cn.eeo.classin");
//                            intent.addCategory(Intent.CATEGORY_LAUNCHER);
//                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
//                                    | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
//                            view.getContext().startActivity(intent);
//                        } catch (Exception e) {
//                            Log.e(TAG, "catch exception when start plaso app");
//                            e.printStackTrace();
//                        }
                        break;
                }
            } else {
                AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                        .setTitle("登录")
                        .setMessage("您还未登录,请前往登录")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Intent intent = new Intent(getActivity(), LoginActivity.class);
                                startActivityForResult(intent, 0X11);
                            }
                        })

                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加取消
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                            }
                        })
                        .create();
                alertDialog.show();
            }
        }
    };

    private void setCarouselNotNetWork(View view) {
        String carouselListString = SpUtil.getInstace().getString(Contants.CAROUSEL_LIST, null);
        if (carouselListString != null && !TextUtils.isEmpty(carouselListString)) {
            Carousel carousel = gson.fromJson(carouselListString, Carousel.class);
            if (carousel != null) {
//                handler.removeCallbacksAndMessages(null);
//                carousel.getList().getUrl()
                list = carousel.getList().getUrl();
                carousel(view);
            }
        }
    }

    public void carouselHttp(final View view) {
        map.put("userId", userId);
        final RequestBody body = HttpUtils.getRequestJson(map);
        OkGoBuilder.getInstance().url(UrlConfig.CAROUSEL).method(OkGoBuilder.PSOT).cls(Carousel.class).Builder((Activity) mContext).requestBody(body).callback(new OkGoUtil<Carousel>(Carousel.class) {
            @Override
            public void onSuccess(Response<Carousel> response1) {
                if (response1.body() instanceof Carousel) {
                    Carousel body1 = response1.body();
                    if (body1 != null) {
                        String json = gson.toJson(body1);
//                        delayTime = body1.getList().getTime();
                        list = body1.getList().getUrl();
                        List<String> listUrl = new ArrayList<>();
                        List<Integer> listDelayTime = new ArrayList<>();
                        for (int i = 0; i < list.size(); i++) {
                            listUrl.add(list.get(i).getCarouselUrl());
                            listDelayTime.add(list.get(i).getTime());
                        }
                        if (listDelayTime.size() != 0) {
                            banner.setAutoPlayInterval(listDelayTime.get(0));
                        }
                        banner.setPageChangeDuration(2000);
                        banner.setAdapter(new BGABanner.Adapter<ImageView, String>() {
                            @Override
                            public void fillBannerItem(BGABanner banner, ImageView itemView, String model, int position) {
                                itemView.setScaleType(ImageView.ScaleType.FIT_XY);
                                Glide.with(mContext).load(model).apply(requestOptions).into(itemView);
                            }
                        });
                        banner.setData(listUrl, null);
                        banner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                            @Override
                            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//                                Log.i("TAG", "=====onPageScrolled=" + position);
                            }

                            @Override
                            public void onPageSelected(int position) {
//                                Log.i("TAG", "=====onPageSelected=" + position);
                                banner.setAutoPlayInterval(listDelayTime.get(position));

                            }

                            @Override
                            public void onPageScrollStateChanged(int state) {

                            }
                        });
//                        handler.removeCallbacksAndMessages(null);
//                        List<Carousel.ListBean.UrlBean> url = body1.getList().getUrl();

                        SpUtil.getInstace().save(Contants.CAROUSEL_LIST, json);
//                        carousel(view);
                    }
                }
            }
        }).build();
    }

    @Override
    public void onAttach(Context context) {
        mContext = context;
        super.onAttach(context);
    }

    public void carousel(View view) {

//        if (list == null || list.size() == 0) {
//            Log.e(TAG, "CAROUSEL response is null or size is 0");
//        } else {
//            viewFlipper.removeAllViews();
//            ImageView[] ivs = new ImageView[list.size()];
//            for (int i = 0; i < list.size(); i++) {
//                ivs[i] = new ImageView(mContext);
//            }
//            for (int i = 0; i < list.size(); i++) {
////                ImageView imageView = new ImageView(mContext);
//                Glide.with(mContext).load(list.get(i).getCarouselUrl()).apply(requestOptions).into(ivs[i]);
//                ivs[i].setScaleType(ImageView.ScaleType.FIT_XY);
//                viewFlipper.addView(ivs[i]);
//            }
//            animation[0] = AnimationUtils.loadAnimation(mContext, R.anim.slide_in_right);
//            animation[1] = AnimationUtils.loadAnimation(mContext, R.anim.slide_out_left);
//            viewFlipper.setInAnimation(animation[0]);
//            viewFlipper.setOutAnimation(animation[1]);
//            message = Message.obtain();
//            message.what = FLAG_MSG;
//            handler.sendMessage(message);
//        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x11 && resultCode == 0x11) {
            Intent intent = getActivity().getIntent();
            getActivity().finish();
            startActivity(intent);
        }
    }

    public OnButtonClick getOnButtonClick() {
        return onButtonClick;
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    public void setOnButtonClick(OnButtonClick onButtonClick) {
        this.onButtonClick = onButtonClick;

    }

    @Override
    public void onStart() {
        super.onStart();
        initdata();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        handler.removeCallbacksAndMessages(null);
    }

    public interface OnButtonClick {
        void onClick(View view);
    }

}
