package com.navinfo.outdoor.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.lzy.okgo.model.HttpParams;
import com.navinfo.outdoor.R;
import com.navinfo.outdoor.activity.LoginActivity;
import com.navinfo.outdoor.api.Constant;
import com.navinfo.outdoor.base.BaseFragment;
import com.navinfo.outdoor.bean.MessageCodeBean;
import com.navinfo.outdoor.bean.UserBean;
import com.navinfo.outdoor.http.Callback;
import com.navinfo.outdoor.http.HttpInterface;
import com.navinfo.outdoor.http.OkGoBuilder;
import com.navinfo.outdoor.util.Base64;
import com.navinfo.outdoor.util.Md5Util;
import com.navinfo.outdoor.util.RegexUtil;

import org.greenrobot.eventbus.EventBus;


/**
 * 注册页面
 */
public class RegisterFragment extends BaseFragment implements View.OnClickListener {
    private EditText etRegisterPhone, etRegisterNote, etRegisterReferrer, etRegisterPaw, etRegisterConfirmPaw;
    private ImageView  ivFinish;
    private TextView haveGoLogin, registerGetNote;
    private Button btnRegister;
    private String sessionId;
    private CountDownTimer timer;
    private CheckBox ivRegisterCheck;

    public static RegisterFragment newInstance(Bundle bundle) {
        RegisterFragment fragment = new RegisterFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_register;
    }

    @Override
    protected void initView() {
        super.initView();
        ivFinish = findViewById(R.id.iv_register_finish);
        ivFinish.setOnClickListener(this::onClick);
        etRegisterPhone = findViewById(R.id.et_register_phone);
        etRegisterNote = findViewById(R.id.et_register_note);
        registerGetNote = findViewById(R.id.register_get_note);
        registerGetNote.setOnClickListener(this::onClick);
        etRegisterReferrer = findViewById(R.id.et_register_referrer);
        etRegisterPaw = findViewById(R.id.et_register_paw);
        etRegisterConfirmPaw = findViewById(R.id.et_register_confirm_paw);
        ivRegisterCheck = findViewById(R.id.iv_register_check);
        haveGoLogin = findViewById(R.id.have_go_login);
        haveGoLogin.setOnClickListener(this::onClick);
        btnRegister = findViewById(R.id.btn_register);
        btnRegister.setOnClickListener(this::onClick);

    }


    @Override
    protected void initData() {
        super.initData();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_register_finish:
                getActivity().finish();
                break;
            case R.id.have_go_login:
                Intent registerLogin = new Intent(getActivity(), LoginActivity.class);
                startActivity(registerLogin);
                break;
            case R.id.btn_register:
                initRegister();
                break;
            case R.id.register_get_note:
                if (!RegexUtil.isPhone(etRegisterPhone.getText().toString())){
                    Toast.makeText(getActivity(), "手机号错误，请重新输入", Toast.LENGTH_SHORT).show();
                    return;
                }else {
                    registerNote();
                    initGetNote();
            }
                break;
        }
    }

    private void initGetNote() {
        HttpParams httpParams = new HttpParams();
        String mobile = etRegisterPhone.getText().toString().trim();
        if (!RegexUtil.isPhone(mobile)) {
            Toast.makeText(getActivity(), "请输入手机号", Toast.LENGTH_SHORT).show();
            return;
        } else {
            httpParams.put("mobile", mobile);
        }
        httpParams.put("type", 1);
        showLoadingDialog();
        OkGoBuilder.getInstance()
                .Builder(getActivity())
                .url(HttpInterface.USER_MESSAGE)
                .cls(MessageCodeBean.class)
                .params(httpParams)
                .getRequest(new Callback<MessageCodeBean>() {
                    @Override
                    public void onSuccess(MessageCodeBean response, int id) {
                        dismissLoadingDialog();
                        if (response.getCode() == 200) {
                            sessionId = response.getBody();
                            Toast.makeText(getActivity(), "验证码已发送", Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(getActivity(), response.getMessage()+"", Toast.LENGTH_SHORT).show();
                        }

                    }

                    @Override
                    public void onError(Throwable e, int id) {
                        dismissLoadingDialog();
                        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void initRegister() {
        HttpParams httpParams = new HttpParams();
        String mobile = etRegisterPhone.getText().toString().trim();
        if (!RegexUtil.isPhone(mobile)) {
            Toast.makeText(getActivity(), "手机号错误", Toast.LENGTH_SHORT).show();
            return;
        } else {
            httpParams.put("mobile", mobile);
        }
        String code = etRegisterNote.getText().toString().trim();
        if (code == null || code.equals("")) {
            Toast.makeText(getActivity(), "请获取短信验证码", Toast.LENGTH_SHORT).show();
            return;
        } else {
            httpParams.put("code", code);
        }
        String password = etRegisterPaw.getText().toString().trim();
        if (password == null || password.equals("")) {
            Toast.makeText(getActivity(), "请输入密码", Toast.LENGTH_SHORT).show();
            return;
        } else {
            try {
                httpParams.put("password",  Base64.desEncrypt(password));
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        String conFirmPaw = etRegisterConfirmPaw.getText().toString().trim();
        if (conFirmPaw == null || conFirmPaw.equals("")) {
            Toast.makeText(getActivity(), "请输入确认密码", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!conFirmPaw.equals(password)) {
            Toast.makeText(getActivity(), "密码和确认密码请保持一致", Toast.LENGTH_SHORT).show();
        return;
        }
        if (sessionId == null || sessionId.equals("")) {
            Toast.makeText(getActivity(), "请短信获取验证码", Toast.LENGTH_SHORT).show();
            return;
        } else {
            httpParams.put("sessionId", sessionId);
        }
        long time = System.currentTimeMillis();
        httpParams.put("datetime", time);
        showLoadingDialog();
        OkGoBuilder.getInstance()
                .Builder(getActivity())
                .url(HttpInterface.USER_REGISTER)
                .token(null)
                .params(httpParams)
                .cls(UserBean.class)
                .postRequest(new Callback<UserBean>() {
                    @Override
                    public void onSuccess(UserBean response, int id) {
                        dismissLoadingDialog();
                        if (response.getCode() == 200) {
                            Constant.USER_NAME = mobile;
                            Constant.PASS_WORD = password;
                            Message obtain = Message.obtain();
                            obtain.what = Constant.REGISTER_WORD;
                            obtain.obj = true;
                            EventBus.getDefault().post(obtain);
                            getActivity().finish();
                        }else {
                            Toast.makeText(getActivity(), response.getMessage() + "", Toast.LENGTH_SHORT).show();
                        }
                    }
                    @Override
                    public void onError(Throwable e, int id) {
                        dismissLoadingDialog();
                        Toast.makeText(getActivity(), e.getMessage() + "", Toast.LENGTH_SHORT).show();
                    }
                });


    }

    private void registerNote() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        registerGetNote.setEnabled(false);
        timer = new CountDownTimer(60 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                registerGetNote.setText(millisUntilFinished / 1000 + "秒后重新获取验证码");
            }

            @Override
            public void onFinish() {
                registerGetNote.setEnabled(true);
                registerGetNote.setText("重新发送");
            }
        };
        timer.start();
    }
}