package com.efounder.chat.fragment;

import android.graphics.Bitmap;
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.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.chat.adapter.SelectContactAdapter;
import com.efounder.chat.adapter.SelectContactAdapter.ViewHolder;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.model.Group;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.frame.baseui.BaseFragment;
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 SelectGroupContactsFragment extends BaseFragment implements
        AdapterView.OnItemClickListener,
        StickyListHeadersListView.OnHeaderClickListener,
        StickyListHeadersListView.OnStickyHeaderOffsetChangedListener,
        StickyListHeadersListView.OnStickyHeaderChangedListener {
    private StickyListHeadersListView stickyList;
    private SideBar sideBar;
    private TextView dialog;
    private SelectContactAdapter adapter;
    private ClearEditText mClearEditText;
    private LinearLayout menuLinerLayout;//显示联系人头像可滑动
    private LinearLayout llSearch;

    private boolean fadeHeader = true;
    private User user;
//    private ImageLoader imageLoader;
//    private DisplayImageOptions options;
    // 添加的列表
    private List<String> addList = new ArrayList<String>();
    /**
     * group中一开始就有的成员
     */
    private List<User> existList = new ArrayList<User>();
    /**
     * 汉字转换成拼音的类
     */
    private List<User> sourceDataList;

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

    //是否是单选模式
    private  boolean isSingleMode = false;
    //是否可一取消默认选中
    private  boolean isCancleSelected = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_select_groupcontacts, container,
                false);
        if (getActivity().getIntent().hasExtra("chatgroup")) {
            //取group中的 群成员
            existList = ((Group) getActivity().getIntent().getSerializableExtra("chatgroup")).getUsers();
        }
        if (getActivity().getIntent().hasExtra("selectuser")) {
            //从chatsingglesetting 跳过来的
            user = (User) getActivity().getIntent().getSerializableExtra("selectuser");
            existList.add(user);
        }

        //是否是单选
        if (getActivity().getIntent().hasExtra("isSingleMode")){
            if (getActivity().getIntent().getBooleanExtra("isSingleMode",false) ==true){
                isSingleMode = true;
            }
        }
        //是否可以取消选中的人
        if(getActivity().getIntent().hasExtra("isCancleSelected")){
            isCancleSelected=getActivity().getIntent().getBooleanExtra("isCancleSelected",false);
        }

        initViews(view);
        initData();
        return view;
    }

    private void initData() {
        //XXX 模拟数据

        sourceDataList = filledData(WeChatDBManager.getInstance().getallFriends());

        // 根据a-z进行排序源数据
        Collections.sort(sourceDataList, pinyinComparator);
        if (getActivity().getIntent().hasExtra("existList")) {
            //从数据库中查询 组中存在的成员
        }
        adapter = new SelectContactAdapter(getActivity(), sourceDataList, existList);
        if (isSingleMode){
            adapter.setSingleMode(true);
            llSearch.setVisibility(View.GONE);
        }
        if(isCancleSelected){
            adapter.setCancleSelected( true );
        }
        stickyList.setAdapter(adapter);

    }

    private void initViews(View view) {
        // 实例化汉字转拼音类

        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);
                }

            }
        });
        llSearch = (LinearLayout) view.findViewById(R.id.ll_search);
        menuLinerLayout = (LinearLayout) view
                .findViewById(R.id.linearLayoutMenu);
        stickyList = (StickyListHeadersListView) view
                .findViewById(R.id.country_lvcountry);
        stickyList.setOnItemClickListener(this);
        stickyList.setOnHeaderClickListener(this);
        stickyList.setOnStickyHeaderChangedListener(this);
        stickyList.setOnStickyHeaderOffsetChangedListener(this);

        stickyList.setDrawingListUnderStickyHeader(true);
        stickyList.setAreHeadersSticky(true);
        stickyList.setStickyHeaderTopOffset(-10);
//        stickyList.setFastScrollEnabled(true);
//        stickyList.setFastScrollAlwaysVisible(true);


        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填充数据
     *
     * @return
     */
    private List<User> filledData(List<User> list) {
        List<User> usersList = new ArrayList<User>();

        // String[] idData = getResources().getStringArray(R.array.id);
        for (User user : list) {
            // 汉字转换成拼音
            String userName = user.getReMark();
            String pinyin = new HanyuParser().getStringPinYin(userName);
            String sortString = pinyin.substring(0, 1).toUpperCase(
                    Locale.getDefault());

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

    }

    /**
     * 根据输入框中的值来过滤数据并更新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.getReMark();
                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) {

        String userId = String.valueOf(sourceDataList.get(position).getId());
        if (adapter.mexistId.contains(userId.toString())) {
            return;
        }
        ViewHolder viewHolder = (ViewHolder) view.getTag();
        viewHolder.checked.performClick();

        adapter.toggleChecked(position);

        if (viewHolder.checked.isChecked()) {
            // 选中用户显示在滑动栏显示
            //XXX 用户头像暂未设置，为空
            showCheckImage(null,
                    adapter.getItem(position));

        } else {
            // 用户显示在滑动栏删除
            deleteImage(adapter.getItem(position));

        }
        //判断从单聊设置界面选人发起群聊，需要将该用户加上
        if (getActivity().getIntent().hasExtra("selectuser")) {
            ArrayList<User> selects = new ArrayList<User>();
            selects = adapter.getSelectedList();
            if (selects == null) {
                return;
            }
            selects.add(user);
            if (selectedCallBack!=null){
                selectedCallBack.getSelectUsers(selects);
            }

        } else {
            //去掉已存在的成员后
           // selectedCallBack.getSelectUsers(adapter.getSelectedList());
            if (selectedCallBack!=null){
                selectedCallBack.getSelectUsers(adapter.getSelectedList());
            }
        }
    }

    @Override
    public void onHeaderClick(StickyListHeadersListView l, View header,
                              int itemPosition, long headerId, boolean currentlySticky) {
    }

    // 即时显示被选中用户的头像和昵称。

    private void showCheckImage(Bitmap bitmap, User user) {
        if (addList.contains(user.getNickName())) {
            return;
        }

        // 包含TextView的LinearLayout
        // 参数设置
        android.widget.LinearLayout.LayoutParams menuLinerLayoutParames = new LinearLayout.LayoutParams(
                108, 108, 1);
        View view = LayoutInflater.from(getActivity()).inflate(
                R.layout.item_chatroom_header_item, null);
        ImageView imageView = (ImageView) view.findViewById(R.id.iv_avatar);
        menuLinerLayoutParames.setMargins(6, 6, 6, 6);

        // 设置id，方便后面删除
        view.setTag(user);

        LXGlideImageLoader.getInstance().showRoundUserAvatar(getActivity(),imageView, user.getAvatar()
                , LXGlideImageLoader.DEFATLT_AVATAR_RADIUS_10);


        menuLinerLayout.addView(view, menuLinerLayoutParames);

        addList.add(user.getNickName());
    }

    private void deleteImage(User user) {
        View view = (View) menuLinerLayout.findViewWithTag(user);

        menuLinerLayout.removeView(view);
        addList.remove(user.getNickName());
    }

    public void setSelectedCallBack(SelectedCallBack selectedCallBack) {
        this.selectedCallBack = selectedCallBack;
    }

    public interface SelectedCallBack {
        public void getSelectUsers(ArrayList<User> selectList);

    }
}
