package com.hjx.miaohongentry.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hjx.miaohongentry.R;
import com.hjx.miaohongentry.adapter.RowWordListAdapter;
import com.hjx.miaohongentry.bean.BookInfo;
import com.hjx.miaohongentry.bean.RowWord;
import com.hjx.miaohongentry.bean.TitleWord;
import com.hjx.miaohongentry.db.MHDataManager;
import com.hjx.miaohongentry.util.DeviceUtils;
import com.hjx.miaohongentry.util.SpanTextViewUtils;
import com.hjx.miaohongentry.util.StatisUtils;

import java.util.List;

public class WordActivity extends Activity {

    private RelativeLayout rl_two_type;
    private Button btn_one_type;
    private BookInfo bookInfo;
    private List<String> tableTypes;
    private RadioGroup radioGroup;
    private RadioButton rb_left;
    private RadioButton rb_right;
    private LinearLayout ll_word_group;
    private ImageButton backBtn;
    private EditText et_search;
    private ImageButton btn_search;

    private List<TitleWord> titleWords_left;
    private List<TitleWord> titleWords_right;
    private final static int GET_TITLE_WORD_FINISH = 1;
    protected ProgressDialog progressDialog = null;
    public static final int REQUEST_CODE_MIAO_HONG = 0x01;

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_TITLE_WORD_FINISH:
                    updateTableTypeView();
                    showWordGroup(titleWords_left);
                    dismissProgressDialog();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_word);
        initData();
        initView();
        showProgressDialog("正在加载...");
    }

    private void initData(){

        String infoStr = getIntent().getStringExtra("bookInfo");
        String info[] = infoStr.split("#");
        bookInfo = new BookInfo("0",info[0],info[1],info[2]);
        new Thread() {
            public void run() {

                tableTypes = MHDataManager.getTableTypes(bookInfo.getPress(),bookInfo.getGrade(),bookInfo.getReactOS());
                titleWords_left = MHDataManager.getTitleWords(bookInfo.getPress(),bookInfo.getGrade(),bookInfo.getReactOS(),tableTypes.get(0));
                for(TitleWord titleWord : titleWords_left){
                    List<RowWord> rowWords = MHDataManager.getRowWords(bookInfo,tableTypes.get(0),titleWord);
                    titleWord.setRowWordList(rowWords);
                }
                if(tableTypes.size() > 1){
                    titleWords_right = MHDataManager.getTitleWords(bookInfo.getPress(),bookInfo.getGrade(),bookInfo.getReactOS(),tableTypes.get(1));
                    for(TitleWord titleWord : titleWords_right){
                        List<RowWord> rowWords = MHDataManager.getRowWords(bookInfo,tableTypes.get(1),titleWord);
                        titleWord.setRowWordList(rowWords);
                    }
                }
                Message msg = new Message();
                msg.what = GET_TITLE_WORD_FINISH;
                handler.sendMessage(msg);
            }
        }.start();

    }


    private void initView(){
        backBtn = findViewById(R.id.btn_back);
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        et_search = findViewById(R.id.et_search);
        btn_search = findViewById(R.id.btn_search);
        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String searchStr = et_search.getText().toString();
                if(!searchStr.isEmpty()){
                    SpanTextViewUtils.gotoMiaohong(WordActivity.this, searchStr);
                }
            }
        });
        initTableTypeView();

    }

    private void initTableTypeView(){
        btn_one_type = findViewById(R.id.btn_one_type);
        rl_two_type = findViewById(R.id.rl_two_type);
        rb_left = findViewById(R.id.rb_left);
        rb_right = findViewById(R.id.rb_right);
        radioGroup = findViewById(R.id.rg_type);
    }

    private void updateTableTypeView(){
        if(tableTypes.size() > 1){
            btn_one_type.setVisibility(View.GONE);
            rl_two_type.setVisibility(View.VISIBLE);
            rb_left.setText(tableTypes.get(0).replace("（一）","1").replace("（二）","2"));
            rb_right.setText(tableTypes.get(1).replace("（一）","1").replace("（二）","2"));
            radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
                    ll_word_group.removeAllViews();
                    if(i == R.id.rb_left){
                        showWordGroup(titleWords_left);
                    }else{
                        showWordGroup(titleWords_right);
                    }
                }
            });

        }else{
            btn_one_type.setVisibility(View.VISIBLE);
            rl_two_type.setVisibility(View.GONE);
            btn_one_type.setText(tableTypes.get(0));
        }
    }
    private void showWordGroup(List<TitleWord> titleWords ){
        ll_word_group = findViewById(R.id.ll_word_group);
        for (TitleWord titleWord : titleWords){
            ll_word_group.addView(getTitleWordView(titleWord));
        }
    }

    public View getTitleWordView(TitleWord titleWord ) {
        View view = LayoutInflater.from(this).inflate(
                R.layout.view_title_word, null);
        TextView tvTitle = view.findViewById(R.id.tv_title);
        tvTitle.setText(titleWord.getTitle());
        ListView listView = view.findViewById(R.id.row_list);
        listView.setEnabled(false);
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        RowWordListAdapter adapter = new RowWordListAdapter(this,titleWord.getRowWordList());
        listView.setAdapter(adapter);
        setListViewHeightBasedOnChildren(listView);
        return view;
    }

    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int px = DeviceUtils.dip2px(this,1.0f);

        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount();  i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            int w = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
            int h = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);

            listItem.measure(w, h);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();

            if(totalHeight + (listView.getDividerHeight() * (i - 1)) >1000){
                break;
            }
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));


        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }


    public void showProgressDialog( final String message){

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (progressDialog == null) {
                    progressDialog = new ProgressDialog(WordActivity.this);
                }
                if(progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }

                progressDialog.setMessage(message);
                progressDialog.setCanceledOnTouchOutside(false);
                progressDialog.show();
            }
        });
    }


    /**隐藏加载进度
     */
    public void dismissProgressDialog() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //把判断写在runOnUiThread外面导致有时dismiss无效，可能不同线程判断progressDialog.isShowing()结果不一致
                if(progressDialog == null || progressDialog.isShowing() == false){
                    return;
                }
                progressDialog.dismiss();
            }
        });
    }

    @Override
    protected  void onResume(){
        super.onResume();
        long enter_mills = StatisUtils.getEnterMiaohongTime(this);
        if(enter_mills != 0){
            long now_mills = System.currentTimeMillis();
            long diff_mills = now_mills - enter_mills;
            if(diff_mills > 0){
                long save_mills = StatisUtils.getTodayTime(WordActivity.this) + diff_mills;
                StatisUtils.setTodayTime(WordActivity.this,save_mills);
            }
            StatisUtils.setEnterMiaohongTime(this, 0);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case REQUEST_CODE_MIAO_HONG:
                if(resultCode == 0){

                    long now_mills = System.currentTimeMillis();
                    long enter_mills = StatisUtils.getEnterMiaohongTime(WordActivity.this);
                    long diff_mills = now_mills - enter_mills;
                    if(diff_mills > 0){
                        long save_mills = StatisUtils.getTodayTime(WordActivity.this) + diff_mills;
                        StatisUtils.setTodayTime(WordActivity.this,save_mills);
                    }
                }
                break;
            default:
                break;
        }
    }

}
