package com.beanpodtech.allinone.adapter;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

//import com.aliyun.solution.longvideo.activity.AlivcPlayerActivity;
import com.aliyun.svideo.common.utils.ToastUtils;
import com.beanpodtech.allinone.R;
import com.beanpodtech.allinone.bean.BaseRequestBean;
import com.beanpodtech.allinone.bean.VideoBean;
import com.beanpodtech.allinone.http.UrlConfig;
import com.beanpodtech.allinone.utils.Contants;
import com.beanpodtech.allinone.utils.DateUtils;
import com.beanpodtech.allinone.utils.HttpUtils;
import com.beanpodtech.allinone.utils.OkGoBuilder;
import com.beanpodtech.allinone.utils.OkGoUtil;
import com.beanpodtech.allinone.utils.PlayVideoUtils;
import com.beanpodtech.allinone.utils.SpUtil;
import com.beanpodtech.allinone.widget.LoadingView;
import com.beanpodtech.allinone.widget.RoundImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.lzy.okgo.model.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

public class VideoAdapter extends RecyclerView.Adapter {
    private static final String TAG = "VideoAdapter";
    private List<VideoBean.ListBean> list;
    private Context mContext;
    private LayoutInflater inflate;
    private LoadingView loadingView;
    private RequestOptions requestOptions;
    private DatePickerDialog datePickerDialog;
    private String videoId;
    private int clickIndex;
    private DatePickerDialog.OnDateSetListener mdateListener = new DatePickerDialog.OnDateSetListener() {
        //重写onDateSet方法
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            try {
                JSONObject jsonObject = new JSONObject();
                JSONArray array = new JSONArray();
                JSONObject object = new JSONObject();
                object.put("videoId", videoId);
                array.put(object);
                jsonObject.put("list", array);
                addStudyplan((DateUtils.parseDate(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth, DateUtils.DEFAULT_FORMATS).getTime() / 1000) + "", jsonObject.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            //dothings
            //year，monthOfYear,dayOfMonth分别为当前选择的年，月，日，这样便获取到了你想要的日期
        }
    };

    public VideoAdapter(List<VideoBean.ListBean> list, Context mContext) {
        this.list = list;
        this.mContext = mContext;
        inflate = LayoutInflater.from(mContext);
        loadingView = new LoadingView(mContext, R.style.CustomDialog);
        loadingView.setTitle(R.string.pleasewait);
        requestOptions = new RequestOptions()
                .error(R.drawable.temp_video_bg)
                .diskCacheStrategy(DiskCacheStrategy.ALL);
        datePickerDialog = new DatePickerDialog(mContext, mdateListener, Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().get(Calendar.DATE));

    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        View view = inflate.inflate(R.layout.course, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
        ((ViewHolder) holder).className.setText(list.get(position).getSubjectName());
        ((ViewHolder) holder).tvTitleCount.setText(list.get(position).getCoursesCount());
        ((ViewHolder) holder).tvTitle1.setText(list.get(position).getCoursesTitleUp());
        ((ViewHolder) holder).tvTitle2.setText(list.get(position).getCoursesTitleDown());
        ((ViewHolder) holder).tvTotaltime.setText(list.get(position).getVideoDuration());
        ((ViewHolder) holder).ivPlan.setVisibility(list.get(position).isAddingStatus() ? View.GONE : View.VISIBLE);
        Glide.with(this.mContext)
                .load(list.get(position).getCoverUrl())
                .apply(requestOptions)
                .into(((ViewHolder) holder).rivBg);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (isFastClick()) return;

                PlayVideoUtils.getInstance().setVideoId(list.get(position).getVideoId()).setContext(mContext).setCourseId(list.get(position).getCourseId()).setType(PlayVideoUtils.NORMAL_VIDEO).setIsNeedRecord(true).build();
//                PlayVideoUtils utils = new PlayVideoUtils(mContext, list.get(position).getVideoId(), list.get(position).getCourseId(), PlayVideoUtils.NORMAL_VIDEO);
//                utils.getPlayAuthToPlay();
//                loadingView.show();
//                getPlayAuth(list.get(position));
            }
        });
        ((ViewHolder) holder).ivPlan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickIndex = position;
                videoId = list.get(position).getVideoId();
                datePickerDialog.show();
            }
        });
    }

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

    //内部类，绑定控件
    class ViewHolder extends RecyclerView.ViewHolder {
        TextView className;
        TextView tvTotaltime, tvTitleCount, tvTitle1, tvTitle2;
        RoundImageView rivBg;
        ImageView ivPlan;

        public ViewHolder(View itemView) {
            super(itemView);
            className = (TextView) itemView.findViewById(R.id.class_name);
            tvTotaltime = (TextView) itemView.findViewById(R.id.tv_totaltime);
            tvTitleCount = (TextView) itemView.findViewById(R.id.tv_title_count);
            tvTitle1 = (TextView) itemView.findViewById(R.id.tv_title1);
            tvTitle2 = (TextView) itemView.findViewById(R.id.tv_title2);
            rivBg = (RoundImageView) itemView.findViewById(R.id.riv_bg);
            ivPlan = itemView.findViewById(R.id.iv_plan);
        }
    }

    private void addStudyplan(String timeStamp, String idList) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", SpUtil.getInstace().getString(Contants.USER_ID, null));
        map.put("date", timeStamp);
        map.put("videoIdList", idList);

        OkGoBuilder.getInstance().url(UrlConfig.ADDSTUDYPLAN).Builder((Activity) mContext).requestBody(HttpUtils.getRequestJson(map)).method(OkGoBuilder.PSOT).cls(BaseRequestBean.class).callback(new OkGoUtil<BaseRequestBean>(BaseRequestBean.class) {
            @Override
            public void onSuccess(Response<BaseRequestBean> response) {
                if (response.body() != null) {
                    if (response.body().getStatus() == 1) {
                        ToastUtils.show(mContext, R.string.add_success);
                        list.get(clickIndex).setAddingStatus(true);
                        notifyDataSetChanged();
                    } else {
                        ToastUtils.show(mContext, R.string.add_fail);
                    }
                }
            }
        }).build();


    }

    private long lastClickTime;
    int MIN_CLICK_DELAY_TIME = 2000;

    // 使用 if (isFastClick()) return;
    private boolean isFastClick() {

        long curClickTime = System.currentTimeMillis();

        if ((curClickTime - lastClickTime) < MIN_CLICK_DELAY_TIME) {
            return true;
        }
        lastClickTime = curClickTime;

        return false;

    }
}