package com.beanpodtech.allinone.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.beanpodtech.allinone.R;
import com.beanpodtech.allinone.adapter.ClassIntroductionAdapter;
import com.beanpodtech.allinone.adapter.ClassIntroductionSmallTypeAdapter;
import com.beanpodtech.allinone.adapter.TeachersAdapter;
import com.beanpodtech.allinone.bean.SelectSubjectBean;
import com.beanpodtech.allinone.bean.TeacherInfoBean;
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.AutoPollRecyclerView;
import com.beanpodtech.allinone.widget.flowlayout.TagFlowLayout;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.lzy.okgo.model.Response;


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


public class ClassTypeIntroductionActivity extends BaseActivity {
    private final static String CLASSTYPE_DATA = "data";
    private ImageView ivBack;
    private TextView tvTitle;
    private String userId;
    private RecyclerView rcvList;
    private ClassIntroductionAdapter adapter;
    private List<SelectSubjectBean.ListBean> totalList = new ArrayList<>();
    private LinearLayout llData;
    private String className;
    private String classId;
    private TextView tvTextup;
    private TextView tvTextmiddle;
    private TextView tvTextdown;
    private TextView tvClasstitle;
    private RequestOptions requestOptions;
    private ImageView ivBackLeft;
    private PopupWindow popupWindowTeacherDes;
    private TextView tv_teachername;
    private TextView tv_teacherinfo;

    public static void startActivity(Context context, Bundle bundle) {
        Intent intent = new Intent(context, ClassTypeIntroductionActivity.class);
        intent.putExtra(CLASSTYPE_DATA, bundle);
        context.startActivity(intent);
    }


    private void getDataFromNet() {
        OkGoBuilder.getInstance().method(OkGoBuilder.PSOT).url(UrlConfig.GET_SUBJECTS).Builder(this).requestBody(HttpUtils.getRequestJson(initRequestJson())).cls(SelectSubjectBean.class).callback(new OkGoUtil<SelectSubjectBean>(SelectSubjectBean.class) {
            @Override
            public void onSuccess(Response<SelectSubjectBean> response) {
                SelectSubjectBean body = response.body();
                if (body != null) {
                    dealData(body);
                }
            }
        }).build();
    }

    private void getTeacherInfo(String teacherId, String name) {
        OkGoBuilder.getInstance().method(OkGoBuilder.PSOT).url(UrlConfig.GETTEACHERINFO).Builder(this).requestBody(HttpUtils.getRequestJson(initTeacherInfoRequestJson(teacherId))).cls(TeacherInfoBean.class).callback(new OkGoUtil<TeacherInfoBean>(TeacherInfoBean.class) {
            @Override
            public void onSuccess(Response<TeacherInfoBean> response) {
                TeacherInfoBean body = response.body();
                if (body != null) {
                    tv_teachername.setText(name);
                    tv_teacherinfo.setText(body.getInfo());
                    popupWindowTeacherDes.showAsDropDown(tvClasstitle, 0, 200);
                }
            }
        }).build();
    }

    /**
     * @return 返回requestBody  做筛选条件的请求使用
     */
    private HashMap<String, String> initTeacherInfoRequestJson(String teacherId) {
        HashMap<String, String> map = new HashMap<>();
        map.put("teacherId", teacherId);
        map.put("userId", userId);
        return map;
    }

    private void dealData(SelectSubjectBean body) {
        tvTextup.setText(body.getCustomizeString());
        tvTextmiddle.setText(body.getTotalTime());
        tvTextdown.setText(body.getEveryTime());
        Glide.with(this.mContext)
                .load(body.getCoverUrl())
                .apply(requestOptions)
                .into(ivBackLeft);
        List<SelectSubjectBean.ListBean> list = body.getList();

//        list.get(1).setTeacherList(list.get(0).getTeacherList());
//        list.get(2).setTeacherList(list.get(0).getTeacherList());
//        list.remove(2);
//        list.remove(1);
        if (list != null) {
            switch (list.size()) {
                case 1:
                    llData.setWeightSum(1);
                    tvClasstitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, 48);
                    addViewToGroup(list);
                    break;
                case 2:
                    llData.setWeightSum(2);
                    tvClasstitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, 30);
                    addViewToGroup(list);
                    break;
                case 3:
                    llData.setWeightSum(3);
                    tvClasstitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, 30);
                    addViewToGroup(list);
                    break;
                default:
                    while (list.size() > 3) {
                        list.remove(3);
                    }
                    llData.setWeightSum(3);
                    tvClasstitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, 30);
                    addViewToGroup(list);
                    break;
            }
        }
        totalList.clear();
        totalList.addAll(list);
        adapter.notifyDataSetChanged();
    }

    private void addViewToGroup(List<SelectSubjectBean.ListBean> list) {
        LinearLayout view = null;
        for (int i = 0; i < list.size(); i++) {
            if (list.size() == 1) {
                view = (LinearLayout) getLayoutInflater().inflate(R.layout.item_classintroduction, null);
            } else if (list.size() == 2) {
                view = (LinearLayout) getLayoutInflater().inflate(R.layout.item_classintroduction_two, null);
            } else if (list.size() == 3) {
                view = (LinearLayout) getLayoutInflater().inflate(R.layout.item_classintroduction_three, null);
            }
            ((TextView) view.findViewById(R.id.tv_title)).setText(list.get(i).getSubjectTitle());
            ((TagFlowLayout) view.findViewById(R.id.tfl_smalltype)).setAdapter(new ClassIntroductionSmallTypeAdapter(list.get(i).getSubjectList(), getLayoutInflater(), ((TagFlowLayout) view.findViewById(R.id.tfl_smalltype)), list.size()));
            ((TextView) view.findViewById(R.id.tv_des)).setText(list.get(i).getSubjectDes());
            AutoPollRecyclerView rcv_teachers = (AutoPollRecyclerView) view.findViewById(R.id.rcv_teachers);
            rcv_teachers.setLayoutManager(new StaggeredGridLayoutManager(1,
                    StaggeredGridLayoutManager.HORIZONTAL));
            rcv_teachers.setItemAnimator(new DefaultItemAnimator());
            if (list.get(i).getTeacherList() != null) {
                if (list.get(i).getTeacherList().size() == 0) {
                    rcv_teachers.setVisibility(View.GONE);
                } else {
                    rcv_teachers.setVisibility(View.VISIBLE);
                }
                List<SelectSubjectBean.ListBean.TeacherListBean> teacherList = list.get(i).getTeacherList();
                TeachersAdapter teachersAdapter = new TeachersAdapter(teacherList, this.mContext, list.size());
                rcv_teachers.setAdapter(teachersAdapter);
                rcv_teachers.start();
                teachersAdapter.setOnTeacherItemClickListener(new TeachersAdapter.OnTeacherItemClickListener() {
                    @Override
                    public void onTeacherItemClick(String teacherId, String name) {
                        getTeacherInfo(teacherId, name);
//                        popupWindowTeacherDes.showAtLocation(tvClasstitle, Gravity.TOP, 0, 0);

//                        Toast.makeText(mContext, teacherId, 1).show();
                    }
                });
                //=============================
                RecyclerView.ViewHolder holder = teachersAdapter.createViewHolder(rcv_teachers, teachersAdapter
                        .getItemViewType(0));
                teachersAdapter.onBindViewHolder(holder, 0);
                holder.itemView.measure(
                        View.MeasureSpec.makeMeasureSpec(rcv_teachers.getWidth(), View.MeasureSpec.EXACTLY),
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                holder.itemView.layout(0, 0, holder.itemView.getMeasuredWidth(),
                        holder.itemView.getMeasuredHeight());
                holder.itemView.setDrawingCacheEnabled(true);
                holder.itemView.buildDrawingCache();
                int measuredHeight = holder.itemView.getMeasuredHeight();
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        measuredHeight);
                if (list.size() == 1) {
                    layoutParams.topMargin = 80;
                } else if (list.size() == 2) {
                    layoutParams.topMargin = 40;
                } else if (list.size() == 3) {
                    layoutParams.topMargin = 20;
                }
                rcv_teachers.setLayoutParams(layoutParams);
            } else {
                rcv_teachers.setVisibility(View.GONE);
            }
            llData.addView(view);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0);
            params.weight = 1;
            view.setLayoutParams(params);

        }
    }

    /**
     * @return 返回requestBody  做筛选条件的请求使用
     */
    private HashMap<String, String> initRequestJson() {
        HashMap<String, String> map = new HashMap<>();
        map.put("classId", classId);
        map.put("userId", userId);
        return map;
    }


    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
        }
    }

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

    @Override
    public void initView(View view) {
        requestOptions = new RequestOptions()
                .error(R.drawable.temp_classintro_left);
        userId = SpUtil.getInstace().getString(Contants.USER_ID, null);
        ivBack = findViewById(R.id.iv_back);
        ivBack.setVisibility(View.GONE);
        tvTitle = findViewById(R.id.tv_title);
        rcvList = findViewById(R.id.rcv_list);
        rcvList.setLayoutManager(new StaggeredGridLayoutManager(1,
                StaggeredGridLayoutManager.VERTICAL));
        rcvList.setItemAnimator(new DefaultItemAnimator());
        adapter = new ClassIntroductionAdapter(totalList, this);
        rcvList.setAdapter(adapter);
        llData = findViewById(R.id.ll_data);
        tvTextup = findViewById(R.id.tv_textup);
        tvTextmiddle = findViewById(R.id.tv_textmiddle);
        tvTextdown = findViewById(R.id.tv_textdown);
        tvClasstitle = findViewById(R.id.tv_classtitle);
        ivBackLeft = findViewById(R.id.iv_back_left);
    }

    @Override
    public void initListener() {
        ivBack.setOnClickListener(this);
    }


    @Override
    public void initData(Context mContext) {
        Bundle bundle = getIntent().getBundleExtra(CLASSTYPE_DATA);
        className = bundle.getString(Contants.CLASS_NAME);
        classId = bundle.getString(Contants.CLASS_ID);
        tvClasstitle.setText(className);
        tvTitle.setText(getResources().getString(R.string.classintro_title));
        tvTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        getDataFromNet();
        initTeacherDesPopupWindow();
    }

    private void initTeacherDesPopupWindow() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.popupwindow_teacherdes, null);
        popupWindowTeacherDes = new PopupWindow(this);
        popupWindowTeacherDes.setContentView(contentView);
        popupWindowTeacherDes.setWidth(400);
        popupWindowTeacherDes.setFocusable(true);
        popupWindowTeacherDes.setBackgroundDrawable(new ColorDrawable(0x00000000));
        tv_teachername = contentView.findViewById(R.id.tv_teachername);
        tv_teacherinfo = contentView.findViewById(R.id.tv_teacherinfo);

    }

}
