package com.efounder.chat.fragment;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;

import com.efounder.frame.baseui.BaseFragment;
import com.efounder.chat.R;
import com.efounder.chat.activity.PublicNumerInfoActivity;
import com.efounder.chat.adapter.ContactsSortAdapter;
import com.efounder.chat.struct.StructFactory;
import com.efounder.mobilecomps.contacts.ClearEditText;
import com.efounder.mobilecomps.contacts.HanyuParser;
import com.efounder.mobilecomps.contacts.PinyinComparator;
import com.efounder.mobilecomps.contacts.SideBar;
import com.efounder.mobilecomps.contacts.SideBar.OnTouchingLetterChangedListener;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.thirdpartycomps.stickylistheaders.StickyListHeadersListView;

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

/**
 * 公众号列表
 * 
 * @author yqs
 * 
 */
public class ServiceNumberListFragment extends BaseFragment implements
		AdapterView.OnItemClickListener,
		StickyListHeadersListView.OnHeaderClickListener,
		StickyListHeadersListView.OnStickyHeaderOffsetChangedListener,
		StickyListHeadersListView.OnStickyHeaderChangedListener {

	private static final String TAG = "ServiceNumberListFragment";

	private StickyListHeadersListView stickyList;
	private SideBar sideBar;
	private TextView dialog;
	private ContactsSortAdapter adapter;
	private ClearEditText mClearEditText;
	private boolean fadeHeader = true;
	/**
	 * 汉字转换成拼音的类
	 */
	private List<User> sourceDataList;

	/**
	 * 根据拼音来排列ListView里面的数据类
	 */
	private PinyinComparator pinyinComparator;

	private View view;

	// @Override
	// protected void onCreate(Bundle savedInstanceState) {
	// super.onCreate(savedInstanceState);
	// setContentView(R.layout.activity_publicnumberlist);
	// initView();
	// }
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.activity_publicnumberlist, container,
				false);
		initView();
		return view;
	}

	private void initView() {
		// 实例化汉字转拼音类

		pinyinComparator = new PinyinComparator();

		sideBar = (SideBar) view.findViewById(R.id.sidrbar);
		dialog = (TextView) view.findViewById(R.id.dialog);
		sideBar.setTextView(dialog);

		// 设置右侧触摸监听
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {
				// 该字母首次出现的位置
				int position = adapter.getPositionForSection(s.charAt(0));
				if (position != -1) {
					stickyList.setSelection(position);
				}

			}
		});

		stickyList = (StickyListHeadersListView) view
				.findViewById(R.id.country_lvcountry);
		stickyList.setOnItemClickListener(this);
		stickyList.setOnHeaderClickListener(this);
		stickyList.setOnStickyHeaderChangedListener(this);
		stickyList.setOnStickyHeaderOffsetChangedListener(this);
		// stickyList.addHeaderView(getLayoutInflater().inflate(R.layout.list_header,
		// null));
		// stickyList.addFooterView(getLayoutInflater().inflate(R.layout.list_footer,
		// null));
		// stickyList.setEmptyView(view.findViewById(R.id.empty));
		stickyList.setDrawingListUnderStickyHeader(true);
		stickyList.setAreHeadersSticky(true);
		stickyList.setStickyHeaderTopOffset(-10);
		stickyList.setFastScrollEnabled(true);
		stickyList.setFastScrollAlwaysVisible(true);
		sourceDataList = filledData(getResources().getStringArray(
				R.array.publicarray2));

		// 根据a-z进行排序源数据
		Collections.sort(sourceDataList, pinyinComparator);
		adapter = new ContactsSortAdapter(getActivity(), sourceDataList);
		stickyList.setAdapter(adapter);

		mClearEditText = (ClearEditText) view.findViewById(R.id.filter_edit);

		// 根据输入框输入值的改变来过滤搜索
		mClearEditText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
				filterData(s.toString());
			}

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

			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

	}

	/**
	 * 为ListView填充数据
	 * 
	 * @param
	 * @return
	 */
	private List<User> filledData(String[] data) {
		List<User> mSortList = new ArrayList<User>();

		String[] idData = getResources().getStringArray(R.array.publicid);
		for (int i = 0; i < data.length; i++) {
			User user = new User();
			user.setNickName(data[i]);
			user.setId(Integer.valueOf(idData[i]));
			// 汉字转换成拼音
			String pinyin = new HanyuParser().getStringPinYin(data[i]);
			String sortString = pinyin.substring(0, 1).toUpperCase(
					Locale.getDefault());

			if (data[i].equals("群聊") || data[i].equals("公众号")
					|| data[i].equals("组织机构")) {
				user.setSortLetters("↑");
			} else if (data[i].equals("")) {
				user.setSortLetters("☆");
			} else if (sortString.matches("[A-Z]")) {// 正则表达式，判断首字母是否是英文字母
				user.setSortLetters(sortString.toUpperCase(Locale
						.getDefault()));
			} else {
				user.setSortLetters("#");
			}
			mSortList.add(user);
		}
		return mSortList;

	}

	/**
	 * 根据输入框中的值来过滤数据并更新ListView
	 * 
	 * @param filterStr
	 */
	private void filterData(String filterStr) {
		List<User> filterDateList = new ArrayList<User>();

		if (TextUtils.isEmpty(filterStr)) {
			filterDateList = sourceDataList;
		} else {
			filterDateList.clear();
			for (User user : sourceDataList) {
				String name = user.getNickName();
				// if (name.indexOf(filterStr.toString()) != -1 ||
				// characterParser.getSelling(name).startsWith(filterStr.toString()))
				// {
				// if (name.contains(filterStr.toString()) ||
				// characterParser.getSelling(name).contains(filterStr.toString()))
				// {
				// filterDateList.add(user);
				// }
				if (containString(name, filterStr)) {
					filterDateList.add(user);
				}
			}
		}

		// 根据a-z进行排序
		Collections.sort(filterDateList, pinyinComparator);
		adapter.updateListView(filterDateList);
	}

	private boolean containString(String name, String filterStr) {
		String namePinyin = new HanyuParser().getStringPinYin(name);
		for (int i = 0; i < filterStr.length(); i++) {
			String singleStr = filterStr.substring(i, i + 1);
			// 汉字
			if (name.contains(singleStr)) {
				if (i == filterStr.length() - 1) {
					return true;
				}
				continue;
			}
			// 英文
			if (namePinyin.contains(singleStr)) {
				int currentIndex = namePinyin.indexOf(singleStr);
				namePinyin = namePinyin.substring(currentIndex + 1,
						namePinyin.length());
			} else {// 不包含
				break;
			}
			if (i == filterStr.length() - 1) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void onStickyHeaderOffsetChanged(StickyListHeadersListView l,
			View header, int offset) {
		if (fadeHeader
				&& Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			header.setAlpha(1 - (offset / (float) header.getMeasuredHeight()));
		}
	}

	@Override
	public void onStickyHeaderChanged(StickyListHeadersListView l, View header,
			int itemPosition, long headerId) {
		header.setAlpha(1);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {

		// XXX
		User model = sourceDataList.get(position);

		Intent intent = new Intent(getActivity(), PublicNumerInfoActivity.class);
		 
		    User user = new User();
		  
		  user.setId(Integer.valueOf(model.getId()));
		user.setNickName(model.getNickName());
		   

		intent.putExtra("user", user);
		intent.putExtra("chattype", StructFactory.TO_USER_TYPE_OFFICIAL_ACCOUNT);

		startActivity(intent);
	}

	@Override
	public void onHeaderClick(StickyListHeadersListView l, View header,
			int itemPosition, long headerId, boolean currentlySticky) {
		Toast.makeText(getActivity(),
				"Header " + headerId + " currentlySticky ? " + currentlySticky,
				Toast.LENGTH_SHORT).show();
	}

}
