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.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
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.SinglePeopleAdapter;
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.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 SinglePeopleTestActivity extends BaseActivity {
    @BindView(R.id.begin_test)
    TextView mBeginTest;
    @BindView(R.id.selete_area_tv)
    TextView mSeleteAreaTv;
    @BindView(R.id.selete_area_lay)
    LinearLayout mSeleteAreaLay;

    @BindView(R.id.recycle_view)
    RecyclerView mRecycleView;
    @BindView(R.id.progress)
    RelativeLayout mProgress;
    @BindView(R.id.key_test)
    EditText mKeyTest;
    private List<StudentBean> mStudentBeans;
    private SinglePeopleAdapter mPeopleAdapter;
    private SearchParamBean mSearchParamBean = new SearchParamBean();
    private SchoolBean mSchoolBean;
    private PopuAdapter mPopuAdapter;

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


    @Override
    protected void init() {
        mSearchParamBean.setSchoolId(EyeConfig.TEST_SCHOOL_ID);
        mRecycleView.setLayoutManager(new LinearLayoutManager(this));
        mStudentBeans = new ArrayList<>();
        mPeopleAdapter = new SinglePeopleAdapter(mStudentBeans, this);
        mRecycleView.setAdapter(mPeopleAdapter);
        search();//
    }

    @OnClick({R.id.back_iv, R.id.selete_area_lay, R.id.do_search, R.id.begin_test})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back_iv:
                finish();
                break;
            case R.id.selete_area_lay:
                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.do_search:
                mSearchParamBean.setStudentId(mKeyTest.getText().toString());
                search();
                break;
            case R.id.begin_test:
                StudentBean bean = mPeopleAdapter.getLastSelectBean();
                if (!CheckUtil.isNull(bean)) {
                    ArrayList<StudentBean> list = new ArrayList<>();
                    list.add(bean);
                    EyeConfig.getInstance().setStudents(list);
                    startActivity(BeforeEyeTestActivity.class);
                }
                break;
        }
    }

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

    private void showPopWindow(final List<PopuBean> popuBeans) {
        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];
            mSeleteAreaLay.getLocationOnScreen(location);
//            popupWindow.setAnimationStyle(R.style.style_pop_animation);// 动画效果必须放在showAsDropDown()方法上边，否则无效
            conview.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            int xoff = -(conview.getMeasuredWidth() / 2 - mSeleteAreaLay.getWidth() / 2);
            popupWindow.showAsDropDown(mSeleteAreaLay, xoff, 0);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    for (PopuBean popuBean : popuBeans) {
                        popuBean.setChick(false);
                    }
                    PopuBean popuBean = popuBeans.get(position);
                    popuBean.setChick(true);
                    mPopuAdapter.notifyDataSetChanged();
                    mSearchParamBean.setGrade(popuBean.getName());
                    mSearchParamBean.setStudentId("");
                    search();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 搜索
     */
    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);
                            mPeopleAdapter.appendToListAndNotify(listOldResponse.getData());
                        } else {
                            ToastUtil.showMessage("暂无数据");
                        }
                    }

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

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