package com.taikor.investment.modules.user;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.taikor.investment.R;
import com.taikor.investment.base.BaseActivity;
import com.taikor.investment.bean.OutputResult;
import com.taikor.investment.bean.User;
import com.taikor.investment.utils.CountDownTimerUtils;
import com.taikor.investment.utils.SharedPreferenceUtils;
import com.taikor.investment.utils.Constant_URL;
import com.taikor.investment.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Response;

/**
 * 手机注册，找回密码
 * Created by Any on 2017/4/12.
 */
public class PhoneRegisterActivity extends BaseActivity {

    @BindView(R.id.iv_delete)
    ImageView ivDelete;
    @BindView(R.id.tv_bar_title)
    TextView tvBarTitle;
    @BindView(R.id.et_reg_phone)
    EditText etRegPhone;//手机号
    @BindView(R.id.et_reg_code)
    EditText etRegCode;//验证码
    @BindView(R.id.tv_get_code)
    TextView tvGetCode;//获取验证码
    @BindView(R.id.et_reg_password)
    EditText etRegPassword;//密码
    @BindView(R.id.iv_eye)
    ImageView ivEye;
    @BindView(R.id.bt_register)
    Button btRegister;
    @BindView(R.id.cb_agreed)
    CheckBox cbAgreed;
    @BindView(R.id.tv_info)
    TextView tvInfo;
    @BindView(R.id.ll_agree)
    LinearLayout llAgree;

    private String phone, code, password;
    private boolean eyeOpen = false;//密码默认是密文
    private static final String TAG = "PhoneRegisterActivity";

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

    @Override
    public void initView() {

        btRegister.getBackground().setAlpha(100);
        etRegPhone.addTextChangedListener(new RegisterWatcher("phone"));
        etRegCode.addTextChangedListener(new RegisterWatcher("code"));
        etRegPassword.addTextChangedListener(new RegisterWatcher("password"));

        Intent intent = getIntent();
        String type = intent.getStringExtra("type");
        if (type.equals("register")) {
            tvBarTitle.setText(getString(R.string.phone_register));
        } else if (type.equals("password")) {
            tvBarTitle.setText(getString(R.string.password_find));
            llAgree.setVisibility(View.GONE);
        }
    }

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

        private String type;

        RegisterWatcher(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();
                ivDelete.setVisibility(View.VISIBLE);
            } else if (type.equals("code")) {
                code = s.toString();
            } else if (type.equals("password")) {
                password = s.toString();
                btRegister.getBackground().setAlpha(255);
            }
        }
    }

    @OnClick({R.id.tv_bar_back, R.id.tv_get_code, R.id.iv_eye, R.id.bt_register, R.id.iv_delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_bar_back:
                finish();
                break;
            case R.id.iv_delete:
                etRegPhone.setText("");
                break;
            case R.id.tv_get_code://获取验证码
                if (!TextUtils.isEmpty(phone)) {
                    //获取验证码
//                    getConfirmCode(phone);
                    CountDownTimerUtils mCountDownTimerUtils = new CountDownTimerUtils(tvGetCode, 30000, 1000);
                    mCountDownTimerUtils.start();
                    tvInfo.setText("已向手机 " + phone + " 发送验证码");
                    tvInfo.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.iv_eye://是否显示密码
                if (eyeOpen) {
                    //密文
                    etRegPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    ivEye.setImageResource(R.drawable.eye_normal3);
                    eyeOpen = false;
                } else {
                    //明文
                    etRegPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    ivEye.setImageResource(R.drawable.eye_selected3);
                    eyeOpen = true;
                }
                break;
            case R.id.bt_register://注册
                if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(code) || TextUtils.isEmpty(password)) {
                    ToastUtils.showShort(PhoneRegisterActivity.this, "没有填写完整");
                    return;
                }
                //注册用户
//                registerUser(phone, password);
                SharedPreferenceUtils.saveString(PhoneRegisterActivity.this, "phone", phone);
                SharedPreferenceUtils.saveString(PhoneRegisterActivity.this, "password", password);
                finish();
                break;
        }
    }

    //注册用户
    private void registerUser(String userPhone, String userPassword) {
        User user = new User(userPhone, userPassword);
        Gson gson = new Gson();
        OkHttpUtils.postString().url(Constant_URL.REGISTER).content(gson.toJson(user))
                .mediaType(MediaType.parse("application/json;charset=utf-8"))
                .build().execute(new Callback<OutputResult>() {
            @Override
            public OutputResult parseNetworkResponse(Response response, int id) throws Exception {
                Gson gson = new Gson();
                return gson.fromJson(response.body().toString(), OutputResult.class);
            }

            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(OutputResult response, int id) {
                if (response == null) {
                    return;
                }
                if ( response.isSuccess()) {
//                    SharedPreferenceUtils.saveString(PhoneRegisterActivity.this, "phone", phone);
//                    SharedPreferenceUtils.saveString(PhoneRegisterActivity.this, "password", password);
                }
                Log.d(TAG, "success:" + response.isSuccess());
                Log.d(TAG, "message:" + response.getMessage());
            }
        });
    }

    //获取验证码
    private void getConfirmCode(String phoneNum) {
        OkHttpUtils.get().url(Constant_URL.CODE_CONFIRM)
                .addParams("phoneNum", phoneNum)
                .build().execute(new Callback<OutputResult>() {
            @Override
            public OutputResult parseNetworkResponse(Response response, int id) throws Exception {
                Gson gson = new Gson();
                return gson.fromJson(response.body().toString(), OutputResult.class);
            }

            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(OutputResult response, int id) {
                if (response == null) {
                    return;
                }
                if (response.isSuccess()) {//发送成功
//                    CountDownTimerUtils mCountDownTimerUtils = new CountDownTimerUtils(tvGetCode, 30000, 1000);
//                    mCountDownTimerUtils.start();
//                    tvInfo.setText("已向手机 " + phone + " 发送验证码");
//                    tvInfo.setVisibility(View.VISIBLE);
                }
                Log.d(TAG, "success:" + response.isSuccess());
                Log.d(TAG, "message:" + response.getMessage());
            }
        });
    }
}
