package com.beanpodtech.allinone.activity;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.aliyun.svideo.common.utils.ToastUtils;
import com.beanpodtech.allinone.R;
import com.beanpodtech.allinone.bean.AliVideoBean;
import com.beanpodtech.allinone.bean.BusinessPromotion;
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.beanpodtech.allinone.widget.LoadingView;
import com.bumptech.glide.Glide;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.lzy.okgo.model.Response;

import java.util.HashMap;
import java.util.List;

import okhttp3.RequestBody;

/**
 * 企业宣传页面
 **/
public class BusinessPromotionAvtivity extends BaseActivity {
    private XRecyclerView mRecyclerView;
    private HomeAdapter mAdapter;
    private Context mContext = this;
    int page = 1;
    int number = 20;
    int totalPages;
    String userId = SpUtil.getInstace().getString(Contants.USER_ID, null);
    HashMap<String, String> map = new HashMap<>();
    List<BusinessPromotion.ListBean> list;
    private LoadingView loadingView;

    @Override
    public void widgetClick(View v) {

    }


    @Override
    public int bindLayout() {
        return R.layout.activity_business_promotion;
    }

    @Override
    public void initView(View view) {
        loadingView = new LoadingView(mContext, R.style.CustomDialog);
        loadingView.setTitle(mContext.getResources().getString(R.string.pleasewait));
        mRecyclerView = findViewById(R.id.id_recyclerview);
        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(5,
                StaggeredGridLayoutManager.VERTICAL));
        ImageView imageView = findViewById(R.id.back);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    public void initListener() {
        mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                resetRecycleViewState();
            }

            @Override
            public void onLoadMore() {
                if (page == totalPages) {
                    Toast.makeText(BusinessPromotionAvtivity.this, "到底了", Toast.LENGTH_SHORT).show();
                    resetRecycleViewState();

                } else {
                    page++;
                    map.put("page", page + "");
                    final RequestBody body = HttpUtils.getRequestJson(map);
                    OkGoBuilder.getInstance().url(UrlConfig.BUSINESS).method(OkGoBuilder.PSOT).cls(BusinessPromotion.class).Builder(BusinessPromotionAvtivity.this).requestBody(body).callback(new OkGoUtil<BusinessPromotion>(BusinessPromotion.class) {
                        @Override
                        public void onSuccess(Response<BusinessPromotion> response) {
                            BusinessPromotion body = response.body();
                            //list = body.getList();
                            list.addAll(body.getList());
                            Log.d(TAG, "list size is " + list.size());
                            //mRecyclerView.setAdapter(new HomeAdapter());
                            //mRecyclerView.setItemAnimator(new DefaultItemAnimator());
                            mAdapter.notifyDataSetChanged();
                            resetRecycleViewState();
                        }
                    }).build();
                }
            }
        });
    }

    @Override
    public void initData(Context mContext) {

        map.put("userId", userId);
        map.put("page", page + "");
        map.put("number", number + "");
        final RequestBody body = HttpUtils.getRequestJson(map);
        OkGoBuilder.getInstance().url(UrlConfig.BUSINESS).method(OkGoBuilder.PSOT).cls(BusinessPromotion.class).Builder(BusinessPromotionAvtivity.this).requestBody(body).callback(new OkGoUtil<BusinessPromotion>(BusinessPromotion.class) {

            @Override
            public void onSuccess(Response<BusinessPromotion> response) {
                BusinessPromotion body = response.body();
                totalPages = body.getTotalPages();
                list = body.getList();

                mRecyclerView.setAdapter(mAdapter = new HomeAdapter());
                mRecyclerView.setItemAnimator(new DefaultItemAnimator());
            }

        }).build();
    }

    /**
     * 重置RecycleView 刷新状态
     */
    private void resetRecycleViewState() {
        mRecyclerView.refreshComplete();
        mRecyclerView.loadMoreComplete();
    }

    class HomeAdapter extends RecyclerView.Adapter {

        @RequiresApi(api = Build.VERSION_CODES.M)
        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.businesspromotion_item, viewGroup, false);
            ViewHolder holder = new ViewHolder(view);
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder viewHolder, final int i) {

            ((ViewHolder) viewHolder).time.setText(list.get(i).getTime());
            ((ViewHolder) viewHolder).sloage.setText(list.get(i).getSloage());
            ((ViewHolder) viewHolder).title.setText(list.get(i).getTitle());
            ((ViewHolder) viewHolder).videoDuration.setText(list.get(i).getVideoDuration());
            Glide.with(BusinessPromotionAvtivity.this).load(list.get(i).getPicturePath()).into(((ViewHolder) viewHolder).imageView);
//            ((ViewHolder) viewHolder).Name.setText(mDatas.get(i));
            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    loadingView.show();
                    getPlayAuthToPlay(list.get(i).getVideoId());
                }
            });
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {

            TextView time;
            TextView sloage;
            TextView title;
            TextView videoDuration;
            ImageView imageView;

            public ViewHolder(@NonNull View itemView) {
                super(itemView);

                time = itemView.findViewById(R.id.time);
                sloage = itemView.findViewById(R.id.sloage);
                title = itemView.findViewById(R.id.title);
                videoDuration = itemView.findViewById(R.id.videoDuration);
                imageView = itemView.findViewById(R.id.image);
            }
        }
    }

    public void getPlayAuthToPlay(final String videoId) {
        OkGoBuilder.getInstance().url(UrlConfig.GETPLAYAUTHBUSINES).Builder((Activity) mContext).method(OkGoBuilder.PSOT).cls(AliVideoBean.class).requestBody(HttpUtils.getRequestJson(getRequestBody(videoId))).callback(new OkGoUtil<AliVideoBean>(AliVideoBean.class) {
            @Override
            public void onSuccess(Response<AliVideoBean> response) {
                loadingView.dismiss();
                AliVideoBean body = response.body();
                if (body != null) {
//                    if (!body.isBelongCurrent()) {
//                        ToastUtils.show(mContext, mContext.getString(R.string.currentvideo_notbelong));
//                        return;
//                    }
//                    if (!body.isAllowPlay()) {
//                        ToastUtils.show(mContext, mContext.getString(R.string.not_have_role_watch));
//                        return;
//                    }
                    AlivcPlayerActivity.startAlivcPlayerActivity(mContext, body, "-1", videoId);
                } else {
                    ToastUtils.show(mContext, R.string.neterror);
                }
            }

            @Override
            public void onError(Response<AliVideoBean> response) {
                loadingView.dismiss();
                super.onError(response);
            }
        }).build();
    }

    private HashMap<String, String> getRequestBody(String videoId) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", SpUtil.getInstace().getString(Contants.USER_ID, null));
        map.put("videoId", videoId);
        return map;
    }
}
