package com.taikor.investment.modules;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.taikor.investment.R;
import com.taikor.investment.base.BaseFragment;
import com.taikor.investment.event.BooleanEvent;
import com.taikor.investment.modules.user.AboutActivity;
import com.taikor.investment.modules.user.FeedBackActivity;
import com.taikor.investment.modules.user.InfoActivity;
import com.taikor.investment.modules.user.PhoneBindingActivity;
import com.taikor.investment.modules.user.PhoneRegisterActivity;
import com.taikor.investment.modules.user.SettingActivity;
import com.taikor.investment.mylibrary.TAnalytics;
import com.taikor.investment.utils.KeyBoardUtils;
import com.taikor.investment.utils.SharedPreferenceUtils;
import com.taikor.investment.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

/**
 * 用户页面：初次使用显示登录页面，登录后显示用户页面，退出后显示登录页面
 * Created by Any on 2017/3/29.
 */

public class UserFragment extends BaseFragment {

    //登录页面
    @BindView(R.id.ll_login)
    LinearLayout llLogin;
    @BindView(R.id.et_login_phone)
    EditText etLoginPhone;//账号
    @BindView(R.id.et_login_password)
    EditText etLoginPassword;//密码
    @BindView(R.id.ib_eye)
    ImageButton ibEye;//是否显示密码
    @BindView(R.id.bt_login)
    Button btLogin;//登录
    @BindView(R.id.tv_phone_register)
    TextView tvPhoneRegister;//手机快速注册
    @BindView(R.id.tv_find_password)
    TextView tvFindPassword;//找回密码
    @BindView(R.id.ib_wei_xin)
    ImageButton ibWeixin;
    @BindView(R.id.ib_qq)
    ImageButton ibQq;
    @BindView(R.id.ib_wei_bo)
    ImageButton ibWeibo;

    //用户页面
    @BindView(R.id.ll_user)
    LinearLayout llUser;
    @BindView(R.id.iv_head_photo)
    ImageView ivHeadPhoto;//头像
    @BindView(R.id.tv_info_phone)
    TextView tvInfoPhone;//手机号码
    @BindView(R.id.tv_job)
    TextView tvJob;//职位
    @BindView(R.id.ll_phone)
    LinearLayout llPhone;//手机认证
    @BindView(R.id.ll_feedback)
    LinearLayout llFeedback;//意见反馈
    @BindView(R.id.ll_about)
    LinearLayout llAbout;//关于我们
    @BindView(R.id.ll_setting)
    LinearLayout llSetting;//设置
    @BindView(R.id.tv_bind_phone)
    TextView tvBindPhone;//手机号码

    private String phone, password;
    private boolean eyeOpen = false;//密码默认是密文

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_user;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        //判断用户是否登录
        boolean flag = SharedPreferenceUtils.getBoolean(getActivity(), "login", false);
        if (flag) {
            llLogin.setVisibility(View.GONE);
            llUser.setVisibility(View.VISIBLE);
        } else {
            llLogin.setVisibility(View.VISIBLE);
            llUser.setVisibility(View.GONE);
        }
    }

    @Override
    public void initData() {
        String phoneNumber = SharedPreferenceUtils.getString(getActivity(), "phone", "");
        //已经绑定过手机，推出后重新登陆
        if (!TextUtils.isEmpty(phoneNumber)) {
            tvInfoPhone.setText(phoneNumber);
            tvBindPhone.setText(phoneNumber);
        }
        etLoginPhone.addTextChangedListener(new LoginWatcher("phone"));
        etLoginPassword.addTextChangedListener(new LoginWatcher("password"));
    }
    
    @OnClick({R.id.ib_eye, R.id.bt_login, R.id.tv_phone_register, R.id.tv_find_password,
            R.id.iv_head_photo,R.id.ll_phone, R.id.ll_feedback, R.id.ll_about, R.id.ll_setting,
            R.id.ib_wei_xin, R.id.ib_qq, R.id.ib_wei_bo})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ib_eye://是否显示密码
                isShowPwd();
                break;
            case R.id.bt_login://登录
                KeyBoardUtils.hideSoftKeyboard(btLogin);
                confirmLogin();
                break;
            case R.id.tv_phone_register://手机快速注册
                Intent phoneIntent = new Intent(getActivity(), PhoneRegisterActivity.class);
                phoneIntent.putExtra("type", "register");
                startActivity(phoneIntent);
                break;
            case R.id.tv_find_password://找回密码
                Intent passwordIntent = new Intent(getActivity(), PhoneRegisterActivity.class);
                passwordIntent.putExtra("type", "password");
                startActivity(passwordIntent);
                break;
            case R.id.ib_wei_xin://微信登录
                break;
            case R.id.ib_qq:
                break;
            case R.id.ib_wei_bo:
                break;
            case R.id.iv_head_photo:
                Intent infoIntent=new Intent(getActivity(), InfoActivity.class);
                startActivity(infoIntent);
                break;
            case R.id.ll_phone: //手机绑定
                bindPhone();
                break;
            case R.id.ll_feedback:
                Intent feedbackIntent = new Intent(getActivity(), FeedBackActivity.class);
                startActivity(feedbackIntent);
                break;
            case R.id.ll_about:
                Intent aboutIntent = new Intent(getActivity(), AboutActivity.class);
                startActivity(aboutIntent);
                break;
            case R.id.ll_setting:
                Intent settingIntent = new Intent(getActivity(), SettingActivity.class);
                startActivity(settingIntent);
                break;
        }
    }

    //绑定手机
    private void bindPhone() {
        Intent confirmIntent = new Intent(getActivity(), PhoneBindingActivity.class);
        //判断手机绑定条目是否有手机号
        String bindPhone = tvBindPhone.getText().toString();
        if (TextUtils.isEmpty(bindPhone)) {
            //绑定手机
            confirmIntent.putExtra("bind", true);
        } else {
            //重新绑定
            confirmIntent.putExtra("bind", false);
            confirmIntent.putExtra("phone", bindPhone);
        }
        startActivityForResult(confirmIntent, 100);
    }

    //登录验证
    private void confirmLogin() {
        if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(password)) {
            btLogin.setClickable(false);
            ToastUtils.showShort(getActivity(), "手机号码或者密码不能为空");
            return;
        }
        //获取注册的手机号和密码，进行比较
        String regPhone = SharedPreferenceUtils.getString(getActivity(), "phone", "");
        String regPassword = SharedPreferenceUtils.getString(getActivity(), "password", "");
        if (phone.equals(regPhone) && regPassword.equals(password)) {
            //设置登录为true,表示登录成功，再次打开APP后显示用户页面
            SharedPreferenceUtils.saveBoolean(getActivity(), "login", true);
            //显示用户页面，隐藏登录页面
            llUser.setVisibility(View.VISIBLE);
            llLogin.setVisibility(View.GONE);
            //手机号码登陆
            tvInfoPhone.setText(phone);
            tvBindPhone.setText(phone);
        }
    }

   //是否显示密码
    private void isShowPwd() {
        if (eyeOpen) {
            //密文
            etLoginPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
            ibEye.setImageResource(R.drawable.eye_normal3);
            eyeOpen = false;
        } else {
            //明文
            etLoginPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            ibEye.setImageResource(R.drawable.eye_selected3);
            eyeOpen = true;
        }
    }

   //监听手机号码和密码输入
    private class LoginWatcher implements TextWatcher {

        private String type;

        LoginWatcher(String type) {
            this.type = type;
        }

        @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) {
            if (type.equals("phone")) {
                phone = s.toString();
            } else if (type.equals("password")) {
                password = s.toString();
                btLogin.setClickable(true);//可点击
                btLogin.setBackgroundColor(Color.parseColor("#EB423E"));//修改背景色
            }
        }
    }

    //处理显示的界面
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void process(BooleanEvent event) {
        if (event.isFlag() && event.getType().equals("user")) {
            //接收发送来的事件，显示登录页面
            llLogin.setVisibility(View.VISIBLE);
            llUser.setVisibility(View.GONE);
        }
    }

    //注册事件总线
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    //解除事件总线
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //绑定手机，数据回显
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            String phone_number = data.getStringExtra("phone");
            tvInfoPhone.setText(phone_number);
            tvBindPhone.setText(phone_number);
        }
    }

    //埋点
    @Override
    public void onHiddenChanged(boolean hidden) {
        if(!hidden){
            TAnalytics.onPageStart("minePage");
        }else{
            TAnalytics.onPageLoad("minePage","","","");
        }
    }
}