package com.taikor.investment.modules.find;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.style.StyleSpan;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.taikor.investment.MainActivity;
import com.taikor.investment.R;
import com.taikor.investment.adapter.ProductAdapter;
import com.taikor.investment.adapter.TextAdapter;
import com.taikor.investment.base.BaseActivity;
import com.taikor.investment.mylibrary.TAnalytics;
import com.taikor.investment.utils.KeyBoardUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 最佳组合
 * Created by Any on 2017/4/5.
 */
public class BestGroupActivity extends BaseActivity {

    @BindView(R.id.et_find)
    EditText etFind;//搜索
    @BindView(R.id.ib_clear)
    ImageButton ibClear;//清除
    @BindView(R.id.dot1)
    ImageView dot1;
    @BindView(R.id.dot2)
    ImageView dot2;
    @BindView(R.id.vp_text)
    ViewPager vpText;//轮播文字
    @BindView(R.id.vp_best_group)
    ViewPager vpBestGroup;//内容存放
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;//导航标签

    private int mCount = 0;  // 记录当前的页数
    public static final int START = -1; // 开始
    public static final int STOP = -2;// 停止
    public static final int UPDATE = -3;// 更新
    public static final int RECORD = -4; // 接受传过来的当前页面数

    private TextAdapter textAdapter;
    private ImageView[] dots = new ImageView[2];
    private List<TextView> mList = new ArrayList<>();
    private ArrayList<Fragment> fragments = new ArrayList<>();
    private String[] titles = {"官方制造", "达人组合", "华山论剑"};
    private String[] contents = {"产品配置  全方位筛选高质量产品，优中选优\n人工智能  基于Black Litterman的高精度模型",
            "平衡调整  定期进行战略平衡，择时再调仓 \n紧密跟踪  提供定期报告，投资动态尽在掌握"};

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case START:
                    handler.sendEmptyMessageDelayed(UPDATE, 2500);
                    break;
                case STOP:
                    handler.removeMessages(UPDATE);
                    break;
                case UPDATE:
                    mCount++;
                    vpText.setCurrentItem(mCount);
                    break;
                case RECORD:
                    mCount = msg.arg1;
                    break;
            }
        }
    };

    @Override
    public int getContentViewId() {
        return R.layout.activity_find_best_group;
    }

    @Override
    public void initView() {
        setListener();
        textAdapter = new TextAdapter();
        //初始化三种不同的fragment
        fragments.add(new OfficialFragment());
        fragments.add(new MasterFragment());
        fragments.add(new CardFragment());

        //设置adapter
        ProductAdapter adapter = new ProductAdapter(getSupportFragmentManager(), fragments, titles);
        vpBestGroup.setAdapter(adapter);
        tabLayout.setupWithViewPager(vpBestGroup);

        //初始化点
        dots[0] = dot1;
        dots[1] = dot2;
        dot1.setSelected(true);

        //文本变化监听
        etFind.addTextChangedListener(myWatcher);
        etFind.setOnKeyListener(onKeyListener);
    }

    @Override
    public void initData() {
        initViewPager();
    }

    @OnClick({R.id.iv_back_best, R.id.ib_clear, R.id.bt_create_group})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.iv_back_best:
                finish();
                break;
            case R.id.ib_clear:
                etFind.setText("");
                ibClear.setVisibility(View.GONE);
                break;
            case R.id.bt_create_group:
                Intent intent = new Intent(BestGroupActivity.this, MainActivity.class);
                intent.putExtra("fragment_position", "2");
                intent.putExtra("default_fragment", true);
                startActivity(intent);
                finish();
                break;
        }
    }

    //   ViewPager页面变化监听
    private void setListener() {

        vpText.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                handler.sendMessage(Message.obtain(handler, RECORD, position, 0));
                //控制点的变化
                int j = position % mList.size();
                for (ImageView view : dots) {
                    view.setSelected(false);
                }
                dots[j].setSelected(true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                switch (state) {
                    // 当滑动时让当前轮播停止
                    case ViewPager.SCROLL_STATE_DRAGGING:
                        handler.sendEmptyMessage(STOP);
                        break;
                    // 滑动停止时继续轮播
                    case ViewPager.SCROLL_STATE_IDLE:
                        handler.sendEmptyMessage(START);
                        break;
                }
            }
        });
    }

    //  轮播图
    public void initViewPager() {
        SpannableString msp;

        TextView textView;
        for (int i = 0; i < 2; i++) {
            textView = new TextView(this);
            msp = new SpannableString(contents[i]);
            msp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //粗体
            msp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 22, 26, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            textView.setText(msp);
            textView.setPadding(10, 20, 10, 10);
            mList.add(textView);
        }

        textAdapter.setData(mList);
        vpText.setAdapter(textAdapter);
        int i = Integer.MAX_VALUE / 2 % mList.size();
        // 默认在中间，让用户看不到边界
        vpText.setCurrentItem(Integer.MAX_VALUE / 2 - i);
        handler.sendEmptyMessage(START);
    }

    // 监听文本的变化
    private TextWatcher myWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            ibClear.setVisibility(View.VISIBLE);
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.sendEmptyMessage(STOP);
    }

    //文字输入之后，点击右下角键盘，开始搜索
    private View.OnKeyListener onKeyListener = new View.OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                KeyBoardUtils.hideSoftKeyboard(v);
                //处理结果
                return true;
            }
            return false;
        }
    };

    //埋点
    @Override
    protected void onResume() {
        super.onResume();
        TAnalytics.onPageStart("bestGroupPage");
    }

    @Override
    protected void onPause() {
        super.onPause();
        TAnalytics.onPageLoad("bestGroupPage", "homePage", "", "");
    }
}
