package com.jimind.sportdemo;

import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.gcssloop.widget.PagerGridLayoutManager;
import com.gcssloop.widget.PagerGridSnapHelper;
import com.jimind.sportdemo.adapter.CourseAdapter;
import com.jimind.sportdemo.adapter.PopupAdapter;
import com.jimind.sportdemo.api.ApiManager;
import com.jimind.sportdemo.base.BaseActivity;
import com.jimind.sportdemo.base.BaseObserver;
import com.jimind.sportdemo.base.ResponseResult;
import com.jimind.sportdemo.bean.Course;
import com.jimind.sportdemo.listener.MyClickListener;
import com.jimind.sportdemo.listener.PopupListener;
import com.jimind.sportdemo.utils.CommonUtils;
import com.jimind.sportdemo.utils.Constant;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.security.KeyFactory;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 主页
 *
 * @author Any
 */
public class MainActivity extends BaseActivity
        implements PagerGridLayoutManager.PageListener,
        PopupListener, MyClickListener,
        OnRefreshListener {


    @BindView(R.id.bt_subject)
    Button btSubject;
    @BindView(R.id.bt_grade)
    Button btGrade;
    @BindView(R.id.bt_classes)
    Button btClasses;
    @BindView(R.id.bt_difficulty)
    Button btDifficulty;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.bt_search)
    Button btSearch;
    @BindView(R.id.bt_head_photo)
    Button btHeadPhoto;
    @BindView(R.id.cl_main)
    ConstraintLayout clMain;
    @BindView(R.id.ib_arrow_left)
    ImageButton ibArrowLeft;
    @BindView(R.id.sf_course)
    SmartRefreshLayout sfCourse;
    @BindView(R.id.rlv_course)
    RecyclerView rlvCourse;

    private int mLocation;
    private boolean mIsInit = true;
    private String mClassName, mSelectCourse;
    private static Connection mConnection;
    private PopupAdapter mPopupAdapter;
    private CourseAdapter mListAdapter;
    private PopupWindow mPopupWindow, mExitWindow;
    private PagerGridLayoutManager mLayoutManager;
    private List<Course> mCourseList = new ArrayList<>();
    private List<String> mOptionList = new ArrayList<>();

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        CommonUtils.initTitleBar(this, clMain);
        MyApplication.getInstance().setTeacherName(btHeadPhoto.getText().toString());

        mLayoutManager = new PagerGridLayoutManager(
                2, 4, PagerGridLayoutManager.HORIZONTAL);
        mLayoutManager.setAllowContinuousScroll(false);
        rlvCourse.setLayoutManager(mLayoutManager);
        PagerGridSnapHelper pageSnapHelper = new PagerGridSnapHelper();
        pageSnapHelper.attachToRecyclerView(rlvCourse);
        mListAdapter = new CourseAdapter(this);
        rlvCourse.setAdapter(mListAdapter);
        mLayoutManager.setPageListener(this);
        sfCourse.setEnableLoadMore(false);
        sfCourse.setOnRefreshListener(this);

        initPopupWindow();
    }

    /**
     * 初始化弹出框
     */
    private void initPopupWindow() {
        View recyclerPop = getLayoutInflater().inflate(R.layout.ppw_recycler, null);
        View exitPop = getLayoutInflater().inflate(R.layout.item_popup, null);
        mPopupWindow = new PopupWindow(recyclerPop, 130, 220, true);
        mExitWindow = new PopupWindow(exitPop, 80, 60, true);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setOutsideTouchable(true);
        RecyclerView rlvPop = recyclerPop.findViewById(R.id.rlv_ppw);
        TextView tvExit = exitPop.findViewById(R.id.tv_content);
        tvExit.setBackgroundResource(R.drawable.pop_);
        rlvPop.setLayoutManager(new LinearLayoutManager(this));
        mPopupAdapter = new PopupAdapter(this);
        rlvPop.setAdapter(mPopupAdapter);

        tvExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mExitWindow.dismiss();
                onBackPressed();
            }
        });
    }

    /**
     * 下拉刷新
     *
     * @param refreshLayout
     */
    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        getCourseList();
    }

    /**
     * 当总页数确定时的回调
     *
     * @param pageSize
     */
    @Override
    public void onPageSizeChanged(int pageSize) {
    }

    /**
     * 当页面被选中时的回调（从 0 开始）
     *
     * @param pageIndex
     */
    @Override
    public void onPageSelect(int pageIndex) {
        if (pageIndex == 0) {
            ibArrowLeft.setVisibility(View.INVISIBLE);
        } else {
            ibArrowLeft.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 查询数据库数据
     */
    public void getCourseList() {
        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                if (mIsInit||mConnection==null) {
                    Class.forName("com.mysql.jdbc.Driver");
                    mConnection = DriverManager.getConnection("jdbc:mysql://"
                            + MyApplication.getInstance().getHost() + ":3306/gisports", "root", "root");
                }
                Statement statement = mConnection.createStatement();
                ResultSet resultSet = statement.executeQuery(mSelectCourse);
                mCourseList.clear();
                while (resultSet.next()) {
                    Course course = new Course();
                    course.setCourseId(resultSet.getInt(1));
                    course.setCourseName(resultSet.getString(3));
                    course.setCourseDescUrl(resultSet.getString(4));
                    course.setCourseListUrl(resultSet.getString(5));
                    course.setCourseDescribe(resultSet.getString(6));
                    course.setGradeName(resultSet.getString(8));
                    course.setDifficultyLevel(resultSet.getInt(9));
                    mCourseList.add(course);
                }
                resultSet.close();
                statement.close();
                emitter.onNext(1);
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<Object>() {
                    @Override
                    protected void onSuccess(Object o) {
                        sfCourse.finishRefresh();
                        mListAdapter.setDataList(mCourseList);
                        mIsInit = false;
                    }

                    @Override
                    protected void onFailure(int code, String message) {

                    }
                });
    }

    @OnClick({R.id.bt_subject, R.id.bt_grade, R.id.bt_classes, R.id.bt_difficulty, R.id.bt_search,
            R.id.bt_head_photo, R.id.bt_system_setting, R.id.bt_data_statistics,
            R.id.ib_arrow_left, R.id.ib_arrow_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_subject:
                //科目
                mLocation = 0;
                String selectCategory = "select Type_Code from sys_dict_type where  P_Type_Code='Category'";
                selectOption(selectCategory,false);
                break;
            case R.id.bt_grade:
                //年级
                mLocation = 1;
                String selectGrade = "select GradeName from course";
                selectOption(selectGrade, false);
                break;
            case R.id.bt_classes:
                //班级
                String gradeName = btGrade.getText().toString();
                if (gradeName.equals(Constant.GRADE)) {
                    Toast.makeText(this, "请先选择年级！", Toast.LENGTH_SHORT).show();
                    return;
                }
                mLocation = 2;
                String selectionClass = "select ClassName from class where GradeName='" + gradeName + "'";
                selectOption(selectionClass, false);
                break;
            case R.id.bt_difficulty:
                //难度
                mLocation = 3;
                String selectDifficulty = "select DifficultyLevel from course";
                selectOption(selectDifficulty, false);
                break;
            case R.id.bt_search:
                CommonUtils.hideSoftKeyboard(this, etSearch);
                String searchContent = etSearch.getText().toString();
                if (!TextUtils.isEmpty(searchContent)) {
                    Toast.makeText(this, searchContent, Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.bt_head_photo:
                //头像，点击退出app
                mExitWindow.showAsDropDown(btHeadPhoto);
                break;
            case R.id.bt_system_setting:
                //系统设置
                Intent setIntent = new Intent(this, SettingActivity.class);
                startActivityForResult(setIntent, 101);
                break;
            case R.id.bt_data_statistics:
                //数据统计
                Intent dataIntent = new Intent(this, StatisticsActivity.class);
                startActivity(dataIntent);
                break;
            case R.id.ib_arrow_left:
                //左边-->前一页
                mLayoutManager.smoothPrePage();
                break;
            case R.id.ib_arrow_right:
                //右边-->下一页
                mLayoutManager.smoothNextPage();
                break;
            default:
        }
    }

    /**
     * 搜索指定的列:科目，年级，班级，难度
     */
    private void selectOption(final String selectSql,final boolean isClick) {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                Statement statement = mConnection.createStatement();
                ResultSet resultSet = statement.executeQuery(selectSql);
                mOptionList.clear();
                while (resultSet.next()) {
                    mOptionList.add(resultSet.getString(1));
                }
                resultSet.close();
                statement.close();
                if (isClick) {
                    return;
                }
                emitter.onNext("1");
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    protected void onSuccess(String s) {
                        mPopupAdapter.setDataList(mOptionList);
                        switch (mLocation) {
                            case 0:
                                mPopupWindow.showAsDropDown(btSubject, 0, 20, Gravity.START);
                                break;
                            case 1:
                                mPopupWindow.showAsDropDown(btGrade, 0, 20, Gravity.START);
                                break;
                            case 2:
                                mPopupWindow.showAsDropDown(btClasses, 0, 20, Gravity.START);
                                break;
                            case 3:
                                mPopupWindow.showAsDropDown(btDifficulty, 0, 20, Gravity.START);
                                break;
                            default:
                        }
                    }

                    @Override
                    protected void onFailure(int code, String message) {

                    }
                });
    }

    /**
     * 弹出框内容点击事件
     *
     * @param content
     */
    @Override
    public void click(String content) {
        switch (mLocation) {
            case 0:
                btSubject.setText(content);
                String category = btSubject.getText().toString();
                mSelectCourse = "select * from course where Category='" + category + "'";
                sfCourse.autoRefresh();
                break;
            case 1:
                btGrade.setText(content);
                mSelectCourse = "select * from course where GradeName='" + btGrade.getText().toString().trim()+ "'";
                sfCourse.autoRefresh();
                break;
            case 2:
                btClasses.setText(content);
                break;
            case 3:
                btDifficulty.setText(content);
                mSelectCourse = "select * from course where DifficultyLevel='" + btDifficulty.getText().toString() + "'";
                sfCourse.autoRefresh();
                break;
            default:
        }
        mPopupWindow.dismiss();
    }

    /**
     * 点击课程,显示选择班级对话框
     *
     * @param position
     */
    @Override
    public void click(int position) {
        Course course = mCourseList.get(position);
        mClassName = btClasses.getText().toString();
        if (mClassName.equals(Constant.CLASS)) {
            //没有选择班级
            String selectionClass = "select ClassName from class where GradeName='" + course.getGradeName() + "'";
            selectOption(selectionClass,true);
            showMyDialog(course);
        } else {
            //直接跳转
            sendToService(course);
            toCourseDesc(course);
        }
    }

    /**
     * 显示选择班级对话框
     */
    private void showMyDialog(final Course course) {
        int textColor = ContextCompat.getColor(this, R.color.textColor);
        View inflate = getLayoutInflater().inflate(R.layout.dialog_class, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(inflate);

        final AlertDialog dialog = builder.create();
        TextView tvGrade = inflate.findViewById(R.id.tv_class_grade);
        tvGrade.setText(course.getGradeName());
        Button btPositive = inflate.findViewById(R.id.bt_positive);
        Button btNegative = inflate.findViewById(R.id.bt_negative);
        RadioGroup rgClass = inflate.findViewById(R.id.rg_class);
        RadioGroup.LayoutParams lp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
        lp.setMargins(20, 10, 0, 0);

        for (int i = 0; i < mOptionList.size(); i++) {
            RadioButton radioButton = new RadioButton(this);
            radioButton.setId(i);
            radioButton.setWidth(100);
            radioButton.setHeight(100);
            radioButton.setButtonDrawable(R.drawable.selector_class);
            radioButton.setPadding(20, 0, 0, 0);
            radioButton.setText(mOptionList.get(i));
            radioButton.setTextColor(textColor);
            radioButton.setTextSize(22);
            rgClass.addView(radioButton, i, lp);
        }

        rgClass.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                mClassName = mOptionList.get(i);
            }
        });

        btPositive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                sendToService(course);
                toCourseDesc(course);
            }
        });

        btNegative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        dialog.show();
        //修改对话框的宽高
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = CommonUtils.dip2px(this, 460);
        params.height = CommonUtils.dip2px(this, 360);
        dialog.getWindow().setAttributes(params);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
    }

    /**
     * 跳转到到课程详情
     * @param course 课程
     */
    private void toCourseDesc(Course course){
        Intent intent = new Intent(MainActivity.this, CourseDescActivity.class);
        intent.putExtra(Constant.CLASS_NAME,mClassName);
        intent.putExtra(Constant.COURSE,course);
        startActivity(intent);
    }

    /**
     * 传给服务器
     */
    private void sendToService(Course course) {
        ApiManager.getInstance().requestService
                .sendCommand(Constant.CHECK_COURSE, String.valueOf(course.getCourseId()), "")
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe(new BaseObserver<ResponseResult>() {
                    @Override
                    protected void onSuccess(ResponseResult responseResult) {
                    }

                    @Override
                    protected void onFailure(int code, String message) {

                    }
                });
    }

    /**
     * 刷新页面
     *
     * @param requestCode 请求码
     * @param resultCode 结果码
     * @param data 数据
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == 200) {
            if (data!=null){
                String ip = data.getStringExtra("ip");
                if(!TextUtils.isEmpty(ip)){
                    mSelectCourse = "select * from course";
                    sfCourse.autoRefresh();
                }
            }
        }
    }

    /**
     * 获取连接对象
     *
     * @return 连接对象
     */
    public static Connection getConnection() {
        return mConnection;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            if (mConnection!=null){
                mConnection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
