package com.oo.eye.activity;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.app.baselibrary.base.common.BaseActivity;
import com.app.baselibrary.commonUtil.CheckUtil;
import com.app.baselibrary.commonUtil.ToastUtil;
import com.oo.eye.EyeConfig;
import com.oo.eye.R;
import com.oo.eye.adapter.PopuAdapter;
import com.oo.eye.adapter.TestResultListAdapter;
import com.oo.eye.bean.ClassBean;
import com.oo.eye.bean.GradeBean;
import com.oo.eye.bean.PopuBean;
import com.oo.eye.bean.SchoolBean;
import com.oo.eye.bean.SearchParamBean;
import com.oo.eye.bean.StudentBean;
import com.oo.eye.db.DbManager;
import com.oo.eye.net.EyeDataManager;
import com.oo.seex.netlibrary.net.response.OldResponseImpl;
import com.oo.seex.netlibrary.net.response.RxCallback;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;

/**
 * Date : 2018/8/28.
 * Author:  cxh
 */

public class TestResurtListActivity extends BaseActivity {
    @BindView(R.id.ddd)
    LinearLayout mDdd;
    @BindView(R.id.recycle_view)
    RecyclerView mRecycleView;
    @BindView(R.id.selete_area_tv)
    TextView mSeleteAreaTv;
    @BindView(R.id.selete_area_iv)
    ImageView mSeleteAreaIv;
    @BindView(R.id.selete_area_lay)
    LinearLayout mSeleteAreaLay;
    @BindView(R.id.selete_tv)
    TextView mSeleteTv;
    @BindView(R.id.selete_iv)
    ImageView mSeleteIv;
    @BindView(R.id.selete_lay)
    LinearLayout mSeleteLay;
    // @BindView(R.id.selete1_tv)
    // TextView mSelete1Tv;
    @BindView(R.id.selete2_iv)
    ImageView mSelete2Iv;
    @BindView(R.id.selete2_tv)
    TextView mSelete2Tv;
    @BindView(R.id.selete2_lay)
    LinearLayout mSelete2Lay;
    @BindView(R.id.key_test)
    EditText mKeyTest;
    @BindView(R.id.do_search)
    TextView mDoSearch;
    @BindView(R.id.title_1)
    TextView mTitle1;
    @BindView(R.id.title_2)
    TextView mTitle2;
    @BindView(R.id.textView)
    TextView mTextView;
    @BindView(R.id.progress)
    RelativeLayout mProgress;
    @BindView(R.id.back_iv)
    ImageView mBackIv;
    @BindView(R.id.selete1_iv)
    ImageView mSelete1Iv;
    @BindView(R.id.search_lay)
    LinearLayout mSearchLay;
    @BindView(R.id.selete1_lay)
    LinearLayout mSelete1Lay;
    @BindView(R.id.text_empty)
    RelativeLayout mTextEmpty;
    private List<ClassBean> mClassBeans;//选择学校的所有小组
    private boolean isAll = true;//是否是全部学校
    private List<PopuBean> mAreaList = new ArrayList<>();
    private List<PopuBean> mClassList = new ArrayList<>();
    private SearchParamBean mSearchParamBean = new SearchParamBean();
    private TestResultListAdapter mResultListAdapter;
    private PopuAdapter mPopuAdapter;
    private int popuPosition;//1学校,2小组
    private SchoolBean mSchoolBean;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_testresult;
    }

    @Override
    protected void init() {
        mTitle1.setSelected(true);
        mTitle2.setSelected(false);
        mRecycleView.setLayoutManager(new LinearLayoutManager(this));
        List<StudentBean> list = new ArrayList<>();
        mResultListAdapter = new TestResultListAdapter(list, this);
        mRecycleView.setAdapter(mResultListAdapter);
        mSearchParamBean.setSchoolId(EyeConfig.TEST_SCHOOL_ID);
        search();
    }

    private boolean isA;
    private boolean isTemporary;//是否是临时报表

    @OnClick({R.id.title_1, R.id.title_2, R.id.back_iv, R.id.selete_area_lay, R.id.selete_lay, R.id.selete1_lay, R.id.selete2_lay, R.id.do_search})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_1:
                isTemporary = false;
                mTitle1.setSelected(true);
                mTitle2.setSelected(false);
                mSeleteAreaLay.setVisibility(View.VISIBLE);
                mSearchLay.setVisibility(View.VISIBLE);
                if (isA) {
                    mSelete2Iv.setImageResource(R.drawable.select3_sel);
                } else {
                    mSelete2Iv.setImageResource(R.drawable.select3_nor);
                }
                mResultListAdapter.clearAndNotify();
                search();
                break;
            case R.id.title_2:
                isTemporary = true;
                mTitle1.setSelected(false);
                mTitle2.setSelected(true);
                mSeleteAreaLay.setVisibility(View.GONE);
                mSearchLay.setVisibility(View.GONE);
                if (isTemporaryA) {
                    mSelete2Iv.setImageResource(R.drawable.select3_sel);
                } else {
                    mSelete2Iv.setImageResource(R.drawable.select3_nor);
                }
                if (CheckUtil.isEmpty(mTemporaryClassList)) {
                    getTemporaryClass();
                }
                mResultListAdapter.clearAndNotify();
                searchTemporary();
                break;
            case R.id.back_iv:
                finish();
                break;
            case R.id.selete_area_lay:
                popuPosition = 1;
                if (!CheckUtil.isEmpty(mAreaList)) {
                    showPopWindow(mAreaList);
                } else if (!CheckUtil.isNull(mSchoolBean)) {
                    setAreaData();
                } else {
                    EyeDataManager.getInstance().getSchoolInfo(EyeConfig.TEST_SCHOOL_ID)
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new RxCallback<OldResponseImpl<SchoolBean>>() {
                                @Override
                                protected void onSuccess(OldResponseImpl<SchoolBean> schoolBeanOldResponse) {
                                    if (schoolBeanOldResponse.getResultData() != null) {
                                        mSchoolBean = schoolBeanOldResponse.getResultData();
                                        if (!CheckUtil.isNull(mSchoolBean)) {
                                            setAreaData();
                                        } else {
                                            ToastUtil.showMessage("暂无数据");
                                        }
                                    }
                                }

                                @Override
                                protected void onError(int errorCode, String errorMessage) {
                                    ToastUtil.showLongMessage(errorMessage);
                                }
                            });
                }
                break;

            case R.id.selete_lay:
                popuPosition = 2;
                if (isTemporary) {
                    showPopWindow(mTemporaryClassList);
                } else {
                    if (!CheckUtil.isEmpty(mClassList)) {
                        showPopWindow(mClassList);
                    } else if (!CheckUtil.isNull(mClassBeans)) {
                        setClassData();
                    } else {
                        EyeDataManager.getInstance().getSchoolInfo(EyeConfig.TEST_SCHOOL_ID)
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new RxCallback<OldResponseImpl<SchoolBean>>() {
                                    @Override
                                    protected void onSuccess(OldResponseImpl<SchoolBean> schoolBeanOldResponse) {
                                        if (schoolBeanOldResponse.getResultData() != null) {
                                            mSchoolBean = schoolBeanOldResponse.getResultData();
                                            if (!CheckUtil.isNull(mSchoolBean)) {
                                                setClassData();
                                            } else {
                                                ToastUtil.showMessage("暂无数据");
                                            }
                                        }
                                    }

                                    @Override
                                    protected void onError(int errorCode, String errorMessage) {
                                        ToastUtil.showLongMessage(errorMessage);
                                    }
                                });
                    }
                }
                break;
            case R.id.selete1_lay://双眼1.0以上
                // showPopWindow(3);
                break;
            case R.id.selete2_lay://仅看A类
                if (isTemporary) {
                    isTemporaryA = !isTemporaryA;
                    if (isTemporaryA) {
                        mSelete2Iv.setImageResource(R.drawable.select3_sel);
                    } else {
                        mSelete2Iv.setImageResource(R.drawable.select3_nor);
                    }
                    searchTemporary();
                } else {
                    isA = !isA;
                    if (isA) {
                        mSelete2Iv.setImageResource(R.drawable.select3_sel);
                        mSearchParamBean.setVisionStatus("typeA");
                    } else {
                        mSelete2Iv.setImageResource(R.drawable.select3_nor);
                        mSearchParamBean.setVisionStatus("");
                    }
                    search();
                }
                break;
            case R.id.do_search:
                mSearchParamBean.setStudentId(mKeyTest.getText().toString());
                search();
                break;
        }
    }

    private void setAreaData() {
        List<GradeBean> gradeBeans = mSchoolBean.getGradeList();
        if (!CheckUtil.isEmpty(gradeBeans)) {
            List<PopuBean> popuBeans = new ArrayList<>();
            PopuBean all = new PopuBean();
            all.setName("全部学校");
            all.setChick(true);
            popuBeans.add(all);
            for (GradeBean gradeBean : gradeBeans) {
                PopuBean popuBean = new PopuBean();
                popuBean.setName(gradeBean.getName());
                popuBean.setClassBeans(gradeBean.getClassList());
                popuBeans.add(popuBean);
            }
            mAreaList = popuBeans;
            showPopWindow(popuBeans);
        } else {
            ToastUtil.showMessage("暂无数据");
        }
    }

    private void setClassData() {
        if (!CheckUtil.isEmpty(mClassBeans)) {
            List<PopuBean> popuBeans = new ArrayList<>();
            PopuBean all = new PopuBean();
            all.setName("全部小组");
            all.setClassId("");
            all.setChick(true);
            popuBeans.add(all);
            for (ClassBean gradeBean : mClassBeans) {
                PopuBean popuBean = new PopuBean();
                popuBean.setName(gradeBean.getClasses());
                popuBean.setClassId(gradeBean.getId());
                popuBeans.add(popuBean);
            }
            mClassList = popuBeans;
            showPopWindow(popuBeans);
            mTextEmpty.setVisibility(View.GONE);
        } else {
            if (!isAll) {
                ToastUtil.showMessage("暂无数据");
                mTextEmpty.setVisibility(View.VISIBLE);
            }
        }
    }

    private void showPopWindow(List<PopuBean> popuBeans) {
        LinearLayout view = mSeleteLay;
        switch (popuPosition) {
            case 1:
                view = mSeleteAreaLay;
                break;
            case 2:
                view = mSeleteLay;
                break;
        }
        try {
            View conview = View.inflate(this, R.layout.popu_list, null);
            PopupWindow popupWindow = new PopupWindow(conview, RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);
            popupWindow.setFocusable(true);
            popupWindow.setOutsideTouchable(true);
            ColorDrawable cd = new ColorDrawable(0x00ffffff);// 背景颜色全透明
            popupWindow.setBackgroundDrawable(cd);
            ListView listView = (ListView) conview.findViewById(R.id.list_view);
            mPopuAdapter = new PopuAdapter(this, popuBeans);
            listView.setAdapter(mPopuAdapter);
            int[] location = new int[2];
            view.getLocationOnScreen(location);
//            popupWindow.setAnimationStyle(R.style.style_pop_animation);// 动画效果必须放在showAsDropDown()方法上边，否则无效
            conview.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            int xoff = -(conview.getMeasuredWidth() / 2 - view.getWidth() / 2);
            popupWindow.showAsDropDown(view, xoff, 0);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    itemClick(position);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void itemClick(int position) {
        List<PopuBean> popuBeans = mPopuAdapter.getBeanList();
        for (PopuBean popuBean : popuBeans) {
            popuBean.setChick(false);
        }
        PopuBean popuBean = popuBeans.get(position);
        popuBean.setChick(true);
        mPopuAdapter.notifyDataSetChanged();
        switch (popuPosition) {
            case 1://学校
                isAll = position == 0 ? true : false;
                mClassBeans = popuBean.getClassBeans();
                mSeleteAreaTv.setText(popuBean.getName());
                if (popuBean.getName().equals("全部学校")) {
                    mSearchParamBean.setGrade("");
                } else {
                    mSearchParamBean.setGrade(popuBean.getName());
                }
                mSearchParamBean.setClassId("");
                mSeleteTv.setText("全部小组");
                break;
            case 2://小组
                if (isTemporary) {
                    className = popuBean.getName();
                } else {
                    mSearchParamBean.setClassId(popuBean.getClassId());
                    mSeleteTv.setText(popuBean.getName());
                }
                break;
        }
        if (isTemporary) {
            searchTemporary();
        } else {
            mSearchParamBean.setStudentId("");
            search();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    /**
     * 搜索
     */
    private void search() {
        mProgress.setVisibility(View.VISIBLE);
        EyeDataManager.getInstance().getStudents(mSearchParamBean.getParams())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxCallback<OldResponseImpl<List<StudentBean>>>() {
                    @Override
                    protected void onSuccess(OldResponseImpl<List<StudentBean>> listOldResponse) {
                        if (listOldResponse != null && listOldResponse.getData() != null) {
                            mProgress.setVisibility(View.GONE);
                            mResultListAdapter.clear();
                            mResultListAdapter.appendToListAndNotify(listOldResponse.getData());
                            mTextEmpty.setVisibility(View.GONE);
                        } else {
                            ToastUtil.showMessage("暂无数据");
                            mTextEmpty.setVisibility(View.VISIBLE);
                        }
                    }

                    @Override
                    protected void onError(int errorCode, String errorMessage) {
                        mProgress.setVisibility(View.GONE);
                        ToastUtil.showMessage(errorMessage);
                    }
                });
    }

    private List<PopuBean> mTemporaryClassList = new ArrayList<>();//临时报表的组

    //获取临时报表的组
    public void getTemporaryClass() {
        List<String> strings = DbManager.getInstance(this).getClasses(this);
        PopuBean all = new PopuBean();
        all.setName("全部小组");
        all.setChick(true);
        mTemporaryClassList.add(all);
        if (!CheckUtil.isEmpty(strings)) {
            for (String string : strings) {
                PopuBean popuBean = new PopuBean();
                popuBean.setName(string);
                mTemporaryClassList.add(popuBean);
            }
        }
    }

    private String className;
    private boolean isTemporaryA;//搜索的时候是否A

    //获取临时报表的组
    public void searchTemporary() {
        mResultListAdapter.clearAndNotify();
        List<StudentBean> list = DbManager.getInstance(this).getStudents(this, className, isTemporaryA);
        if (!CheckUtil.isEmpty(list)) {
            mTextEmpty.setVisibility(View.GONE);
            mResultListAdapter.appendToListAndNotify(list);
        } else {
            ToastUtil.showMessage("暂无数据");
            mTextEmpty.setVisibility(View.VISIBLE);
        }
    }
}
