package com.wanyue.main.view.proxy.home;

import androidx.lifecycle.Observer;
import android.content.Intent;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.wanyue.common.CommonAppConfig;
import com.wanyue.common.custom.DrawableTextView;
import com.wanyue.common.custom.refresh.RxRefreshView;
import com.wanyue.common.proxy.RxViewProxy;
import com.wanyue.common.server.entity.Data;
import com.wanyue.common.utils.DpUtil;
import com.wanyue.common.utils.ListUtil;
import com.wanyue.common.utils.ResourceUtil;
import com.wanyue.common.utils.StringUtil;
import com.wanyue.detail.business.IntentInsHelper;
import com.wanyue.inside.bean.LecturerBean;
import com.wanyue.inside.bean.ProjectBean;
import com.wanyue.inside.busniess.data.ProjectDataHelper;
import com.wanyue.inside.busniess.ui.UIFactory;
import com.wanyue.inside.event.InsideEvent;
import com.wanyue.main.R;
import com.wanyue.main.R2;
import com.wanyue.main.adapter.FamousTeacherSimpleAdapter;
import com.wanyue.main.adapter.HomePageAdapter;
import com.wanyue.main.adapter.HomeSubjectAdapter;
import com.wanyue.main.api.MainAPI;
import com.wanyue.main.api.project.HomeMoreProjectDataProvider;
import com.wanyue.main.api.project.SubjectProjectDataProvider;
import com.wanyue.main.bean.SubjectBean;
import com.wanyue.main.bean.SectionProjectBean;
import com.wanyue.main.bean.banner.HomBannerBean;
import com.wanyue.main.view.proxy.BannerViewProxy;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

/*首页布局*/
public class HomePageViewProxy extends RxViewProxy {

    @BindView(R2.id.refreshView)
    RxRefreshView<SectionProjectBean> mRxRefreshView;
    @BindView(R2.id.btn_search)
    View mBtnSearch;
    @BindView(R2.id.tv_interest)
    TextView mTvInterest;

    @BindView(R2.id.tv_red_point)
    TextView mTvRedPoint;

    private HomePageAdapter mHomePageAdapter;
    private HomeSubjectAdapter mHeadSubjectAdapter;
    private FamousTeacherSimpleAdapter mTeacherSimpleAdapter;

    @Override
    public int getLayoutId() {
        return R.layout.view_home_page;
    }

    @Override
    protected void initView(ViewGroup contentView) {
        super.initView(contentView);
        setDefaultStatusBarPadding();


        RecyclerView recyclerView=mRxRefreshView.getRecyclerView();
        recyclerView.setHasFixedSize(true);
        recyclerView.setItemViewCacheSize(20);
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);/*{
            @Override
            protected int getExtraLayoutSpace(RecyclerView.State state) {
                return 10;
            }
        };*/
        recyclerView.setLayoutManager(linearLayoutManager);

        mHomePageAdapter = new HomePageAdapter(null);
        mHomePageAdapter.setEnableLoadMore(false);
        mHomePageAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                SectionProjectBean sectionProjectBean=mHomePageAdapter.getData().get(position);
                ProjectBean projectBean=sectionProjectBean.t;
                if(projectBean==null){
                   itemClickHead(sectionProjectBean);
                }else{
                   itemClickProject(projectBean);
                }
            }
        });

        mHomePageAdapter.setHasStableIds(true);
        mHomePageAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                int viewId=view.getId();
                SectionProjectBean sectionProjectBean=mHomePageAdapter.getData().get(position);
                ProjectBean projectBean=sectionProjectBean.t;
                if(projectBean!=null){
                    String uid=projectBean.getLecturerUid();
                    if(viewId==R.id.tv_name||viewId==R.id.img_avator){
                      // TeacherHomeActivity.forward(getActivity(),uid);
                    }
                }
            }
        });

        mRxRefreshView.setLoadMoreEnable(false);
        //mRxRefreshView.setReclyViewSetting(RxRefreshView.ReclyViewSetting.createLinearSetting(getActivity(),0));
        mRxRefreshView.setAdapter(mHomePageAdapter);
        mRxRefreshView.setDataListner(new RxRefreshView.DataListner<SectionProjectBean>() {
            @Override
            public Observable<List<SectionProjectBean>> loadData(int p) {
                return requestData();
            }
            @Override
            public void compelete(List<SectionProjectBean> data) {
            }
            @Override
            public void error(Throwable e) {
                e.printStackTrace();
            }
        });
       initHeadBannerView(); //banner轮播图
       initHeadClassView(); //课程分类
       initHeadTeacher(); //讲师列表
       initGrade(); //初始化学级

       LiveEventBus.get(InsideEvent.GRADE).observe(getActivity(), new Observer<Object>() {
            @Override
            public void onChanged(@Nullable Object o) {
                initGradeData();
            }
        });
    }
    private void initGradeData() {
        mTvInterest.setText(CommonAppConfig.getGradeName());
        if(mRxRefreshView!=null){
           mRxRefreshView.initData();
        }
    }


    private void initGrade() {
       String gradeId= CommonAppConfig.getGradeId();
        if(StringUtil.equals(gradeId,"0")){ //没有学级的时候默认设置学级
           toStudyStage();
        }else{
           initGradeData();
        }
    }


    /*获取首页数据*/
    private Observable<List<SectionProjectBean>> getIndexData() {
    return MainAPI.getIndex().compose(this.<Data<JSONObject>>bindUntilOnDestoryEvent()).doOnNext(new Consumer<Data<JSONObject>>() {
            @Override
            public void accept(Data<JSONObject> jsonObjectData) throws Exception {
                JSONObject jsonObject=jsonObjectData.getInfo_0();
                String silideJson=jsonObject.getJSONArray("silide").toJSONString();
                String courseclassJson=jsonObject.getJSONArray("courseclass").toJSONString();
                String teacherJson=jsonObject.getJSONArray("teacher").toJSONString();
                int num=jsonObject.getIntValue("cartnums");
                UIFactory.setTextCount(mTvRedPoint,num);

                List<HomBannerBean>bannerBeanList=JSON.parseArray(silideJson,HomBannerBean.class);
                List<SubjectBean>subjectList=JSON.parseArray(courseclassJson,SubjectBean.class);
                List<LecturerBean>lecturerBeanList=JSON.parseArray(teacherJson,LecturerBean.class);
                if(mBannerViewProxy!=null){
                    mBannerViewProxy.setData(bannerBeanList);
                }
                if(mHeadSubjectAdapter!=null){
                    mHeadSubjectAdapter.setData(subjectList);
                }

                if(mTeacherSimpleAdapter!=null){
                    mTeacherSimpleAdapter.setData(lecturerBeanList);
                }
            }
        }).map(new Function<Data<JSONObject>, List<SectionProjectBean>>() {
            @Override
            public List<SectionProjectBean> apply(Data<JSONObject> jsonObjectData) throws Exception {
                ListUtil.TransFormByIndexListner transFormListner= new ListUtil.TransFormByIndexListner<ProjectBean, SectionProjectBean>() {
                    @Override
                    public SectionProjectBean transform(int index, int totalSize, ProjectBean projectBean) {
                        SectionProjectBean section=new SectionProjectBean(projectBean);
                        if(totalSize==1){
                            section.backgroudDrawableId=R.drawable.press_raidius_5_color_white;
                        }else if(totalSize>1){
                            if(index==0){
                                section.backgroudDrawableId=R.drawable.press_bg_top_border_press;
                            }else if(index==totalSize-1){
                                section.backgroudDrawableId=R.drawable.press_bg_bottom_border_press;
                            }else{
                                section.backgroudDrawableId=R.drawable.press_left_right_border_press;
                            }
                        }
                        return section;
                    }
                };
                JSONObject jsonObject=jsonObjectData.getInfo_0();
                JSONArray courseArray=jsonObject.getJSONArray("course");
                JSONArray liveArray=jsonObject.getJSONArray("live");
                JSONArray contentArray=jsonObject.getJSONArray("list");
                JSONArray packsArray=jsonObject.getJSONArray("packs");

                List<ProjectBean>packgeBeanList= ProjectDataHelper.formatProject(packsArray);
                List<ProjectBean>courseList= ProjectDataHelper.formatProject(courseArray);
                List<ProjectBean>liveList=ProjectDataHelper.formatProject(liveArray);
                List<ProjectBean>contentList=ProjectDataHelper.formatProject(contentArray);

                List<SectionProjectBean> list = new ArrayList<>();
                List<SectionProjectBean>tranData=null;

                SectionProjectBean sectionProjectBean = new SectionProjectBean(true, "精选套餐",SectionProjectBean.HEAD_ID_PACKGE);
                list.add(sectionProjectBean);
                if(courseList!=null){
                    tranData=ListUtil.transFormByIndex(packgeBeanList, SectionProjectBean.class,transFormListner);
                    list.addAll(tranData);
                }

                sectionProjectBean = new SectionProjectBean(true, "好课推荐",SectionProjectBean.HEAD_ID_COURSE);
                list.add(sectionProjectBean);
                if(courseList!=null){
                    tranData=ListUtil.transFormByIndex(courseList, SectionProjectBean.class,transFormListner);
                    list.addAll(tranData);
                }


                sectionProjectBean = new SectionProjectBean(true, "直播课堂",SectionProjectBean.HEAD_ID_LIVE);
                list.add(sectionProjectBean);
                if(liveList!=null){
                    tranData=ListUtil.transFormByIndex(liveList, SectionProjectBean.class,transFormListner);
                    list.addAll(tranData);
                }

                sectionProjectBean = new SectionProjectBean(true, "精选内容",SectionProjectBean.HEAD_ID_CONTENT);
                list.add(sectionProjectBean);
                if(contentList!=null){
                    tranData=ListUtil.transFormByIndex(contentList, SectionProjectBean.class,transFormListner);
                    list.addAll(tranData);
                }

                return list;
            }
        });
    }



    private void itemClickProject(ProjectBean projectBean) {
        IntentInsHelper.forward(getActivity(),new Intent(),projectBean);
    }


    private void itemClickHead(SectionProjectBean sectionProjectBean) {
        HomeMoreProjectDataProvider projectDataProvider=new HomeMoreProjectDataProvider();
        projectDataProvider.setType(sectionProjectBean.headerId);
        //ProjectListActivity.forward(getActivity(),sectionProjectBean.header,projectDataProvider);
    }

    private Observable<List<SectionProjectBean>> requestData() {
       return getIndexData();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            mRxRefreshView.initData();
        }
    }

    private BannerViewProxy<HomBannerBean>mBannerViewProxy;
    private void initHeadBannerView() {
        mBannerViewProxy = new BannerViewProxy<HomBannerBean>();
        FrameLayout frameLayout = new FrameLayout(getActivity());
        int padding=DpUtil.dp2px(10);
        frameLayout.setPadding(padding,padding,padding,padding);
        mHomePageAdapter.addHeaderView(frameLayout);
        getViewProxyChildMannger().addViewProxy(frameLayout, mBannerViewProxy, mBannerViewProxy.getDefaultTag());
    }


    private void initHeadClassView() {

        RecyclerView recyclerView = new RecyclerView(getActivity());
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.topMargin = DpUtil.dp2px(20);
        recyclerView.setLayoutParams(params);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
        recyclerView.setLayoutManager(linearLayoutManager);
        mHeadSubjectAdapter = new HomeSubjectAdapter(null);
        recyclerView.setAdapter(mHeadSubjectAdapter);
        mHeadSubjectAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                SubjectBean subjectBean= mHeadSubjectAdapter.getData().get(position);
                SubjectProjectDataProvider projectDataProvider=new SubjectProjectDataProvider();
                projectDataProvider.setClassId(subjectBean.getId());
                //ProjectListActivity.forward(getActivity(),subjectBean.getName(),projectDataProvider);
            }
        });
        mHomePageAdapter.addHeaderView(recyclerView);
    }
    private void initHeadTeacher() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_recly_head_home_page, null);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toFamousTeacher();
            }
        });
        TextView tvTitle = view.findViewById(R.id.tv_head_title);
        tvTitle.setText(R.string.famous_teacher_lecture);

        DrawableTextView tvMore=view.findViewById(R.id.tv_more);
        tvMore.setRightDrawable(ResourceUtil.getDrawable(R.mipmap.icon_arrow_right,true));
        mHomePageAdapter.addHeaderView(view);

        mTeacherSimpleAdapter = new FamousTeacherSimpleAdapter(null);
        RecyclerView teacherReclyView = new RecyclerView(getActivity());
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
        teacherReclyView.setLayoutManager(linearLayoutManager);
        teacherReclyView.setAdapter(mTeacherSimpleAdapter);
        mHomePageAdapter.addHeaderView(teacherReclyView);
    }

    private void toFamousTeacher() {

    }

    @OnClick(R2.id.btn_search)
    public void toSearch() {

    }
    @OnClick(R2.id.tv_interest)
    public void toStudyStage(){

    }
    @OnClick(R2.id.btn_shop_cart)
    public void toShopCart(){
        //startActivity(ShopCartActivity.class);
    }
}
