package com.lj.template.ui;

import android.content.Context;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;


import com.lj.template.R;
import com.lj.template.commonadapter.CommonAdapter;
import com.lj.template.commonadapter.ViewHolder;
import com.lj.template.letter.LetterView;
import com.lj.template.letter.Person;
import com.lj.template.letter.SortUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


/**
 * 自定义通讯录列表.
 * 将耗时的操作放在主线程，导致视图加载等待中发生丢帧情况
 */
public class NoteBookActivity extends AppCompatActivity {

    private Context context;

    /**
     * 进度框
     */
    private ProgressBar progressBar;
    /**
     * 列表
     */
    private ListView listview;
    /**
     * 字母提示
     */
    private TextView textview;

    /**
     * 中心区域的展示字母
     */
    private TextView letterDialog;

    private PopupWindow popupWindow;

    private CommonAdapter<Person> commonAdapter;

    private List<Person> data = new ArrayList<Person>();

    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notebook);
        context = this;
        // 搜索框
        EditText etSearch = (EditText) findViewById(R.id.searchEdit);
        progressBar = (ProgressBar) findViewById(R.id.progress);
        progressBar.setVisibility(View.VISIBLE);
        listview = (ListView) findViewById(R.id.listview);
        listview.setVisibility(View.GONE);
        textview = (TextView) findViewById(R.id.textview);
        // 字母索引表
        LetterView letters = (LetterView) findViewById(R.id.letter);
        // TextView比PopupWindow性能好些
        letters.setOnTouchLettersListener(touchLettersListener1);
        letterDialog = (TextView) LayoutInflater.from(this).inflate(R.layout.pop_textview_dialog, (ViewGroup) null);

        commonAdapter = new CommonAdapter<Person>(context, data, R.layout.letter_item) {

            @Override
            public void convert(ViewHolder holder, Person t) {
                if (holder.getPosition() == 0) {    // 第一个记录总是显示字母条与姓名
                    holder.setVisible(R.id.letter, true);
                    holder.setText(R.id.letter, t.getLetter());
                } else {        // 判断是否显示字母条
                    // 将搜索结果也区分，则用下面
                    // 获取上一条记录的姓名首字母
                    String lastLetter = commonAdapter.getmDatas().get(holder.getPosition() - 1).getLetter();
                    if (t.getLetter().equals(lastLetter)) {     // 与上一条记录相同，不显示字母条
                        holder.setVisible(R.id.letter, false);
                    } else {        // 与上一条记录不同，显示字母条
                        holder.setVisible(R.id.letter, true);
                        holder.setText(R.id.letter, t.getLetter());
                    }
                }
                holder.setText(R.id.name, t.getName());
            }
        };
        listview.setAdapter(commonAdapter);

        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                progressBar.setVisibility(View.GONE);
                listview.setVisibility(View.VISIBLE);
                String[] contact = getResources().getStringArray(R.array.contact);
                /**
                 * 此段获取汉字拼音首字符并进行排序的操作比较耗时，对视图的绘制展示会有一定的影响。通过post的方式在主线程执行时，
                 * 会提示Skipped xxx frames! The application may be doing too much work on its main thread.
                 * 对于这种问题，可以将这些耗时代码放入到子线程，通过Message的方式来处理结果。
                 */
                for (int i = 0; i < contact.length; i++) {
                    Person person = new Person();
                    String name = contact[i];
                    // 处理空值或特殊字符的情况
                    char firstLetter = TextUtils.isEmpty(name) ? '#' : name.charAt(0);
                    String type = SortUtil.getFirstCharType(firstLetter);
                    person.setName(name);
                    person.setLetter(type);
                    data.add(person);
                }
                Collections.sort(data, new PersonComparator());
                System.out.println(com.alibaba.fastjson.JSON.toJSONString(data));
                commonAdapter.notifyDataSetChanged();
            }

        }, 1000);
        etSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                List<Person> list = new ArrayList<Person>();
                if (!TextUtils.isEmpty(s)) {
                    for (int i = 0; i < data.size(); i++) {
                        boolean bool = false;
                        Person person = data.get(i);
                        if(s.length()==1){  // 单字符时
                            /**
                             * 考虑到输入的可能可能会是小写、大写，所以要分别判断
                             * 不能用||，因为这||前面为true，后面就不会判断了。表达式必须都判断，才能得出精准结果。
                             *
                             */
                            int c = s.charAt(0);
                            if(c >= 97 && c <= 122){    // 小写字母
                                String UpText = s.toString().toUpperCase();
                                bool = person.getName().contains(s) | person.getName().contains(UpText);
                            }else if(c >= 65 && c <= 90){   // 大写字母
                                String lowText = s.toString().toLowerCase();
                                bool = person.getName().contains(s) | person.getName().contains(lowText);
                            }else{      // 非字母
                                bool = person.getName().contains(s);
                            }
                        }else{  //多字符，全字符匹配
                            bool = person.getName().contains(s);
                        }
                        if (bool) {
                            list.add(person);
                        }
                    }
                    commonAdapter.setmDatas(list);
                } else {
                    commonAdapter.setmDatas(data);
                }
                commonAdapter.notifyDataSetChanged();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 通过位原视图中心的TextView来展示手指碰触到的字母
     */
    private LetterView.OnTouchLettersListener touchLettersListener1 = new LetterView.OnTouchLettersListener() {

        @Override
        public void onTouchLettersUp() {
            textview.setVisibility(View.GONE);
        }

        @Override
        public void onTouchLettersDown(String letter) {
            int m = -1;
            m = getSelectedIndex(letter, m);
            listview.setSelection(m);
            textview.setVisibility(View.VISIBLE);
            textview.setText(letter);
        }
    };

    /**
     * 通过PopupWindow弹窗来展示手指碰触到的字母
     */
    private LetterView.OnTouchLettersListener touchLettersListener2 = new LetterView.OnTouchLettersListener() {

        @Override
        public void onTouchLettersUp() {
            if (popupWindow != null) {
                popupWindow.dismiss();
            }
        }

        @Override
        public void onTouchLettersDown(String letter) {
            int m = -1;
            m = getSelectedIndex(letter, m);
            listview.setSelection(m);
            if (popupWindow == null) {
                popupWindow = new PopupWindow(letterDialog, 150, 150, false);
            }
            // 显示在Activity的根视图中心
            popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
            letterDialog.setText(letter);
        }
    };

    /**
     * 获取手指碰触的字母对应列表应该定位的位置
     * @param letter
     * @param m
     * @return
     */
    private int getSelectedIndex(String letter, int m) {
        if (letter.equals("↑")) {   // 如果是箭头，直接回到顶端
            m = 0;
        } else {
            for (int i = 0; i < data.size(); i++) {
                if (data.get(i).getLetter().equals(letter)) {
                    m = i;
                    break;
                }
            }
        }
        return m;
    }

    /**
     * 排序算法（如果首字符相同，则按Unicode码排序；首字符不同的，按首字符排）
     */
    class PersonComparator implements Comparator<Person> {

        @Override
        public int compare(Person lhs, Person rhs) {
            String lhsLetter = lhs.getLetter();
            String rhsLetter = rhs.getLetter();
            if (lhsLetter.equals(rhsLetter)) { // 首字符相同
                return lhs.getName().compareTo(rhs.getName());
            } else { // 首字符不同
                if (lhsLetter.equals("#")) {
                    return 1; // 前者为#，前者比后者大，前者后移
                } else if (rhsLetter.equals("#")) {
                    return -1; // 后者为#，前者比后者少，前者前移
                } else {
                    return lhsLetter.compareTo(rhsLetter);
                }
            }
        }
    }
}
