package com.efounder.chat.fragment;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.chat.R;
import com.efounder.chat.activity.PublicNumerInfoActivity;
import com.efounder.chat.adapter.ContactsSortAdapter;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.presenter.publicnumberlist.PublicNumberListContract;
import com.efounder.chat.presenter.publicnumberlist.PublicNumberListPresenter;
import com.efounder.frame.baseui.BasePresenterFragment;
import com.efounder.mobilecomps.contacts.ClearEditText;
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;


/**
 * 公众号列表
 *
 * @author yqs
 */
public class PublicNumberListFragment extends BasePresenterFragment<PublicNumberListContract.Presenter> implements
        AdapterView.OnItemClickListener,
        StickyListHeadersListView.OnHeaderClickListener,
        StickyListHeadersListView.OnStickyHeaderOffsetChangedListener,
        StickyListHeadersListView.OnStickyHeaderChangedListener,
        PublicNumberListContract.View {

    private static final String TAG = "PublicNumberListFragment";

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

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

    private String title;

    public PublicNumberListFragment() {
    }

    /**
     * 初始化 该fragment的Presenter
     *
     * @return
     */
    @Override
    protected PublicNumberListPresenter initPresenter() {
        return new PublicNumberListPresenter(this);
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_publicnumberlist;
    }

    /**
     * 控件初始化
     *
     * @param root
     */
    @Override
    protected void initView(View root) {
        sideBar = (SideBar) root.findViewById(R.id.sidrbar);
        dialog = (TextView) root.findViewById(R.id.dialog);
        sideBar.setTextView(dialog);
        stickyList = (StickyListHeadersListView) root
                .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);
        mClearEditText = (ClearEditText) root.findViewById(R.id.filter_edit);
        relativeLayout = root.findViewById(R.id.rl_title);
        titleView = root.findViewById(R.id.tv_title);
        backView = root.findViewById(R.id.iv_back);
    }

    /**
     * 数据初始化
     */
    @Override
    protected void initData() {
        super.initData();
        if (title == null) {
            try {
                if (stubObject != null) {
                    title = stubObject.getCaption();
                    String id = (String) stubObject.getObject("id", "");
                    if ("应用号".equals(title) || "yyh".equals(id)) {
                        sourceDataList = WeChatDBManager.getInstance().getallOfficialNumber();
                        sourceDataList = mPresenter.filledData(sourceDataList);
                    } else {
                        sourceDataList = mPresenter.filledData(mActivity, getResources().getStringArray(
                                R.array.publicarray2));
                    }
                } else {
                    sourceDataList = WeChatDBManager.getInstance().getallOfficialNumber();
                    sourceDataList = mPresenter.filledData(sourceDataList);
                }
            } catch (Exception e) {
                e.printStackTrace();
                sourceDataList = WeChatDBManager.getInstance().getallOfficialNumber();
                sourceDataList = mPresenter.filledData(sourceDataList);
            }
        } else {
            if ("应用号".equals(title)) {
                //sourceDataList = filledData(getResources().getStringArray(
                //R.array.publicarray));
                sourceDataList = WeChatDBManager.getInstance().getallOfficialNumber();
                sourceDataList = mPresenter.filledData(sourceDataList);
            } else {
                sourceDataList = mPresenter.filledData(mActivity, getResources().getStringArray(
                        R.array.publicarray2));
            }
        }
        // 根据a-z进行排序源数据
        Collections.sort(sourceDataList, pinyinComparator);
        initAdapter();
        initListener();
        setTitle();
    }

    /**
     * 控件监听初始化
     */
    @Override
    protected void initListener() {
        super.initListener();
        // 设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    stickyList.setSelection(position);
                }

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

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

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

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        //EditText获取焦点后隐藏掉提示文字
        mClearEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                ClearEditText editText = (ClearEditText) v;
                String hint = null;
                int i = v.getId();
                if (i == R.id.filter_edit) {
                    if (hasFocus) {
                        hint = editText.getHint().toString();
                        editText.setTag(hint);
                        editText.setHint("");
                    } else {
                        hint = editText.getTag().toString();
                        editText.setHint(hint);
                    }
                }
            }
        });

    }

    /**
     * 接收传过来的参数
     *
     * @param bundle
     */
    @Override
    protected void initArgs(Bundle bundle) {
        super.initArgs(bundle);
        // 实例化汉字转拼音类
        pinyinComparator = new PinyinComparator();
        if (bundle != null) {
            title = bundle.getString("title");
        }
        if (bundle != null) {
            stubObject = (StubObject) bundle.getSerializable("stubObject");

        }

    }


    @Override
    protected void initAdapter() {
        super.initAdapter();
        adapter = new ContactsSortAdapter(getActivity(), sourceDataList);
        stickyList.setAdapter(adapter);
    }

    /**
     * 根据title参数设置标题
     */
    private void setTitle() {
        if (isAlone()) {
            relativeLayout.setVisibility(View.VISIBLE);
            titleView.setText(title);
            backView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getActivity().finish();
                }
            });
        }

    }

    @Override
    public void filterDataSuccess(List<User> userList) {
        adapter.updateListView(userList);
    }

    @Override
    public void onResume() {
        super.onResume();
        reloadData();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        reloadData();
    }

    private void reloadData() {
        if ("应用号".equals(title)) {
            sourceDataList.clear();
            List<User> myList = new ArrayList<User>();
            myList.addAll(WeChatDBManager.getInstance().getallOfficialNumber());
            sourceDataList.addAll(mPresenter.filledData(myList));
            // 根据a-z进行排序源数据
            Collections.sort(sourceDataList, pinyinComparator);
            adapter.notifyDataSetChanged();
        }


    }

    @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) {

        User user = (User) adapter.getItem(position);
        Intent intent = new Intent(getActivity(), PublicNumerInfoActivity.class);
        intent.putExtra("id", user.getId());
        if (user.getType() != -1) {
            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();
    }


}
