package com.uiuipad.appstore.fragment.featured;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.tencent.mmkv.MMKV;
import com.uiuipad.appstore.R;
import com.uiuipad.appstore.activity.ClassAppActivity;
import com.uiuipad.appstore.activity.MoreAppActivity;
import com.uiuipad.appstore.adapter.AppAdapter;
import com.uiuipad.appstore.adapter.BannerViewHolder;
import com.uiuipad.appstore.base.BaseFragment;
import com.uiuipad.appstore.bean.AdminAppInfo;
import com.uiuipad.appstore.bean.AppClassBean;
import com.uiuipad.appstore.common.CommonConfig;
import com.uiuipad.appstore.utils.DensityUtil;
import com.uiuipad.appstore.utils.LogUtils;
import com.uiuipad.appstore.utils.ToastUtil;
import com.zhpan.bannerview.BannerViewPager;
import com.zhpan.bannerview.constants.IndicatorSlideMode;
import com.zhpan.bannerview.holder.HolderCreator;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import butterknife.BindView;
import butterknife.ButterKnife;

public class FeaturedFragment extends BaseFragment implements FeaturedContact.FeaturedView {
    private static final String TAG = FeaturedFragment.class.getSimpleName();

    @BindView(R.id.featured_refresh_layout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.cl)
    ConstraintLayout cl;
    @BindView(R.id.iv_banner)
    ImageView iv_banner;
    @BindView(R.id.banner_view)
    BannerViewPager<String, BannerViewHolder> mViewPager;

    @BindView(R.id.cl_exclusive)
    ConstraintLayout cl_exclusive;
    @BindView(R.id.tv_exclusive_app)
    TextView tv_exclusive_app;
    @BindView(R.id.rv_exclusive)
    RecyclerView rv_exclusive;
    @BindView(R.id.iv_exclusive_nodata)
    ImageView iv_exclusive_nodata;

    @BindView(R.id.cl_popular)
    ConstraintLayout cl_popular;
    @BindView(R.id.tv_popular_app)
    TextView tv_popular_app;
    @BindView(R.id.rv_popular)
    RecyclerView rv_popular;
    @BindView(R.id.iv_popular_nodata)
    ImageView iv_popular_nodata;

    @BindView(R.id.cl_0)
    ConstraintLayout cl_0;
    @BindView(R.id.cl_1)
    ConstraintLayout cl_1;
    @BindView(R.id.cl_2)
    ConstraintLayout cl_2;
    @BindView(R.id.cl_3)
    ConstraintLayout cl_3;
    @BindView(R.id.cl_4)
    ConstraintLayout cl_4;

    @BindView(R.id.iv_0)
    ImageView iv_0;
    @BindView(R.id.iv_1)
    ImageView iv_1;
    @BindView(R.id.iv_2)
    ImageView iv_2;
    @BindView(R.id.iv_3)
    ImageView iv_3;
    @BindView(R.id.iv_4)
    ImageView iv_4;

    private AppAdapter mExclusiveAppAdapter;
    private AppAdapter mPopularAppAdapter;
    private List<AppClassBean> mAppClassList;

    public static final String EXCLUSIVE_APP = "专属应用";
    public static final String POPULAR_APP = "热门应用";

    private FeaturedPresenter mPresenter;
    private View rootView;
    private FragmentActivity mContext;
    private MMKV mMMKV = MMKV.mmkvWithID(CommonConfig.MMKV_ID, MMKV.MULTI_PROCESS_MODE);

    public FeaturedFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        Log.e(TAG, "onCreateView: ");
        if (null != rootView) {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (null != parent) {
                parent.removeView(rootView);
            }
        } else {  // 如ongoing果rootView为空 ，就实例化该视图
            rootView = inflater.inflate(R.layout.fragment_featured, container, false);
            mContext = (FragmentActivity) rootView.getContext();
            mPresenter = new FeaturedPresenter(mContext);
            mPresenter.attachView(this);
            mPresenter.setLifecycle(lifecycleSubject);
            ButterKnife.bind(this, rootView);
            initView();
        }
        return rootView;
    }

    public void initView() {
        mExclusiveAppAdapter = new AppAdapter(mContext);
        mExclusiveAppAdapter.setHasStableIds(true);
        mPopularAppAdapter = new AppAdapter(mContext);
        mPopularAppAdapter.setHasStableIds(true);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 2);
        rv_popular.setLayoutManager(gridLayoutManager);
        rv_popular.setAdapter(mPopularAppAdapter);
        GridLayoutManager gridLayoutManager2 = new GridLayoutManager(mContext, 2);
        rv_exclusive.setLayoutManager(gridLayoutManager2);
        rv_exclusive.setAdapter(mExclusiveAppAdapter);

        ((SimpleItemAnimator) rv_popular.getItemAnimator()).setSupportsChangeAnimations(false);
        setImageViewSize();
        mRefreshLayout.setEnableLoadMore(false);
        mRefreshLayout.setEnableRefresh(true);
        mRefreshLayout.setOnRefreshListener(refreshlayout -> mPresenter.getAdminApp());
        mRefreshLayout.autoRefresh();
        mViewPager.setIndicatorSlideMode(IndicatorSlideMode.SMOOTH)
                .setHolderCreator(new HolderCreator<BannerViewHolder>() {
                    @Override
                    public BannerViewHolder createViewHolder() {
                        return new BannerViewHolder();
                    }
                })
                .setIndicatorColor(getResources().getColor(R.color.white), getResources().getColor(R.color.colorAccent))
                .setOnPageClickListener(new BannerViewPager.OnPageClickListener() {
                    @Override
                    public void onPageClick(int position) {

                    }
                })
                .setInterval(5000);
        cl_0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openAppClass(0);
            }
        });
        cl_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openAppClass(1);
            }
        });
        cl_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openAppClass(2);
            }
        });
        cl_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openAppClass(3);
            }
        });
        cl_4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openAppClass(4);
            }
        });

        tv_exclusive_app.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, MoreAppActivity.class);
                intent.putExtra(CommonConfig.MORE_APP_TITLE, EXCLUSIVE_APP);
                startActivity(intent);
            }
        });
        tv_popular_app.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, MoreAppActivity.class);
                intent.putExtra(CommonConfig.MORE_APP_TITLE, POPULAR_APP);
                startActivity(intent);
            }
        });
    }

    private void setImageViewSize() {
        ViewGroup.LayoutParams ivParams = iv_banner.getLayoutParams();
        ViewGroup.LayoutParams clParams = cl.getLayoutParams();
        Log.e(TAG, "initView: getWidth: " + ivParams.width);
        Log.e(TAG, "initView: getHeight:" + ivParams.height);
        Log.e(TAG, "initView: getWidth: " + ivParams.width);
        Log.e(TAG, "initView: getHeight:" + ivParams.height);
        //获取屏幕宽度
        WindowManager m = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        m.getDefaultDisplay().getMetrics(outMetrics);
        Log.e(TAG, "initView: widthPixels: " + outMetrics.widthPixels);
        Log.e(TAG, "initView: heightPixels: " + outMetrics.heightPixels);

        int screenWidth = outMetrics.widthPixels;
        int imageViewWidth = screenWidth - DensityUtil.dpToPx(mContext, 20);
        //获取屏幕像素
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        opts.inSampleSize = 1;
        opts.inJustDecodeBounds = false;
        int w = opts.outWidth;
        int h = opts.outHeight;
        Log.e(TAG, "initView: w: " + w);
        Log.e(TAG, "initView: h: " + h);

        int imageViewheight = (int) ((float) (h * 1.0 / w) * imageViewWidth);
        ivParams.width = imageViewWidth;
        ivParams.height = imageViewheight;
        iv_banner.setLayoutParams(ivParams);
        clParams.height = imageViewheight;
        cl.setLayoutParams(clParams);
        Log.e(TAG, "setImageViewSize: clheight :" + cl.getHeight());
        Log.e(TAG, "setImageViewSize: imageViewheight :" + iv_banner.getHeight());
    }

    @Override
    public void fetchData() {
        mPresenter.getAdminApp();
    }

    @Override
    public void onConfigurationChanged(@androidx.annotation.NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 3);
            rv_popular.setLayoutManager(gridLayoutManager);
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 2);
            rv_popular.setLayoutManager(gridLayoutManager);
        } else {
            rv_popular.setLayoutManager(new LinearLayoutManager(mContext));
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        registerReceiver();
        mExclusiveAppAdapter.notifyDataSetChanged();
        mPopularAppAdapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (myReceiver != null) {
            try {
                mContext.unregisterReceiver(myReceiver);
            } catch (Exception e) {
                LogUtils.e("onDestroy", e.getMessage());
            }
        }
        mPresenter.detachView();
    }

    @Override
    public void setAdminApp(List<AdminAppInfo> appInfoList) {
        if (appInfoList != null && appInfoList.size() != 0) {
//            if (infos.size() <= 6) {
//                tv_exclusive_app.setVisibility(View.GONE);
//            } else {
//                tv_exclusive_app.setVisibility(View.VISIBLE);
//            }
//            List<AppInfo> filterApp = infos.stream().sorted(Comparator.comparingInt(AppInfo::getWeight).reversed()).limit(6).collect(Collectors.toList());
            rv_exclusive.setVisibility(View.VISIBLE);
            iv_exclusive_nodata.setVisibility(View.GONE);
            mExclusiveAppAdapter.setData(appInfoList);
            cl_exclusive.setVisibility(View.VISIBLE);
        } else {
            cl_exclusive.setVisibility(View.GONE);
            rv_exclusive.setVisibility(View.GONE);
            iv_exclusive_nodata.setImageDrawable(mContext.getDrawable(R.drawable.app_nodata));
            iv_exclusive_nodata.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void getAdminAppError() {
        rv_exclusive.setVisibility(View.GONE);
        iv_exclusive_nodata.setImageDrawable(mContext.getDrawable(R.drawable.app_nonetwork));
        iv_exclusive_nodata.setVisibility(View.VISIBLE);
    }

    @Override
    public void getAdminAppFinish() {
        mPresenter.getAdminAppClass();
    }

    @Override
    public void setAdminAppClass(List<AppClassBean> appClassBeanList) {
        setClass(appClassBeanList);
    }

    private void setClass(List<AppClassBean> appClassList) {
        if (appClassList == null || appClassList.size() == 0) {
            return;
        }
        this.mAppClassList = appClassList.stream().sorted((o1, o2) -> Integer.compare(o1.getId(), o2.getId())).collect(Collectors.toList());
        for (int i = 0; i < mAppClassList.size(); i++) {
            AppClassBean appClassBean = mAppClassList.get(i);
            int imageviewId = mContext.getResources().getIdentifier("iv_" + (i), "id", mContext.getPackageName());
            int textviewId = mContext.getResources().getIdentifier("tv_" + (i), "id", mContext.getPackageName());
            try {
                ImageView imageView = getActivity().findViewById(imageviewId);
                TextView textView = getActivity().findViewById(textviewId);
                Glide.with(mContext).load(appClassBean.getImg()).error(R.drawable.ic_app).into(imageView);
                textView.setText(appClassBean.getName());
            } catch (Exception e) {
                Log.e(TAG, "setClass: " + e.getMessage());
            }
        }
    }

    @Override
    public void getAdminAppClassError() {

    }

    @Override
    public void getAdminAppClassFinish() {
        mRefreshLayout.finishRefresh();
    }


    private void registerReceiver() {
        if (myReceiver == null) {
            myReceiver = new installReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction(Intent.ACTION_PACKAGE_ADDED);
            filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
            filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
            filter.addDataScheme("package");
            filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
            mContext.registerReceiver(myReceiver, filter);
        }
    }

    private installReceiver myReceiver;


    public class installReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //接收安装广播
            if (action.equals(Intent.ACTION_PACKAGE_ADDED)
                    || action.equals(Intent.ACTION_PACKAGE_REPLACED)
                    || action.equals(Intent.ACTION_PACKAGE_REMOVED)) {
                mPopularAppAdapter.notifyDataSetChanged();
                Log.e("InstallReceiver", action);
            }

        }
    }

    private void openAppClass(int index) {
        if (mAppClassList == null || mAppClassList.size() == 0) {
            ToastUtil.show("该分类没有应用");
            return;
        }
        AppClassBean appClassBean = mAppClassList.get(index);
        if (appClassBean == null) {
            ToastUtil.show("该分类没有应用");
            return;
        }
        int classId = appClassBean.getId();
        String className = appClassBean.getName();
        Intent intent = new Intent(getActivity(), ClassAppActivity.class);
        intent.putExtra(CommonConfig.APP_CLASS_ID, classId);
        intent.putExtra(CommonConfig.APP_CLASS_NAME, className);
        startActivity(intent);
    }
}
