package com.yidianling.user.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.ydl.webview.H5Params;
import com.ydl.webview.NewH5Activity;
import com.ydl.ydlcommon.base.BaseActivity;
import com.ydl.ydlcommon.base.config.YDLConstants;
import com.ydl.ydlcommon.bean.StatusBarOptions;
import com.ydl.ydlcommon.data.http.RxUtils;
import com.ydl.ydlcommon.data.http.ThrowableConsumer;
import com.ydl.ydlcommon.router.YdlCommonOut;
import com.ydl.ydlcommon.utils.log.LogHelper;
import com.ydl.ydlcommon.utils.remind.ToastHelper;
import com.ydl.ydlcommon.view.DeleteEditTextView;
import com.ydl.ydlcommon.view.JumpTextView;
import com.ydl.ydlcommon.view.RoundCornerButton;
import com.ydl.ydlcommon.view.dialog.CommonDialog;
import com.yidianling.common.tools.ToastUtil;
import com.yidianling.user.R;
import com.yidianling.user.UserConstants;
import com.yidianling.user.http.UserHttp;
import com.yidianling.user.http.UserHttpImpl;
import com.yidianling.user.http.request.CodeParam;
import com.yidianling.user.http.request.ExistParam;
import com.yidianling.user.http.response.ExistResponse;
import com.yidianling.user.ui.login.RegisterAndLoginActivity;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import org.jetbrains.annotations.NotNull;

import java.util.concurrent.TimeUnit;


/**
 * 注册手机号或绑定手机号
 * Created by softrice on 15/11/23.
 */
public class InputPhoneActivity extends BaseActivity implements View.OnClickListener {

    JumpTextView jtv_country;
    DeleteEditTextView detv_phone;
    TextView tv_protocol;
    LinearLayout ll_protocol;
    RoundCornerButton rcb_next;

    TextView tvFreePacketHint;

    private String country_code = "0086";
    private String country_name = "中国";
    private String FORMAT = "%s   +%s";

    String phoneNum;

    String smsAction = UserConstants.REGISTER_ACTION;//验证码类型,注册：register找回密码：forget 绑定手机 wxbind
    private boolean isFromSplash;

    private boolean isRegisterFromRedPacket;

    private static final String SMS_ACTION = "smsAction";
    private static final String PHONE = "phone";
    private static final String ISFROMSPLASH = "isFromSplash";

    public static Intent newIntent(Activity activity, String smsAction) {
        Intent intent = new Intent(activity, InputPhoneActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(SMS_ACTION, smsAction);
        intent.putExtra(YDLConstants.BUNDLE, bundle);
        return intent;
    }

    public static void start(Activity activity, String smsAction, String phone, boolean isFromSplash) {
        Intent intent = new Intent(activity, InputPhoneActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(SMS_ACTION, smsAction);
        bundle.putString(PHONE, phone);
        bundle.putBoolean(ISFROMSPLASH, isFromSplash);
        intent.putExtra(YDLConstants.BUNDLE, bundle);
        activity.startActivity(intent);
    }

    public static void start(Activity activity, String smsAction, boolean isRegisterFromRedPacket) {
        Intent intent = new Intent(activity, InputPhoneActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(SMS_ACTION, smsAction);
        bundle.putBoolean(UserConstants.IS_REGISTER_FROM_PACKET, isRegisterFromRedPacket);
        intent.putExtra(YDLConstants.BUNDLE, bundle);
        activity.startActivity(intent);
    }

    @NotNull
    @Override
    public StatusBarOptions getStatusViewOptions() {
        return new StatusBarOptions(true,true);
    }

    @Override
    protected int layoutResId() {
        return R.layout.user_activity_input_phone;
    }

    @Override
    protected void initDataAndEvent() {
        jtv_country = findViewById(R.id.jtv_country);
        detv_phone = findViewById(R.id.detv_phone);
        tv_protocol = findViewById(R.id.tv_protocol);
        ll_protocol = findViewById(R.id.ll_protocol);
        tvFreePacketHint = findViewById(R.id.tv_free_packet_hint);
        rcb_next = findViewById(R.id.rcb_next);
        jtv_country.setOnClickListener(this);
        tv_protocol.setOnClickListener(this);
        rcb_next.setOnClickListener(this);

        String action = null;
        Bundle bundle = getIntent().getBundleExtra(YDLConstants.BUNDLE);
        if (bundle != null) {
            action = bundle.getString(SMS_ACTION);
            LogHelper.Companion.getInstance().writeLogSync(String.format("%s页面创建", action));
            phoneNum = bundle.getString(PHONE);
            isFromSplash = bundle.getBoolean(ISFROMSPLASH, false);
            isRegisterFromRedPacket = bundle.getBoolean(UserConstants.IS_REGISTER_FROM_PACKET, false);
        } else {
            ToastUtil.toastShort("请稍后重试");
            finish();
        }
        if (action == null) {
            smsAction = UserConstants.REGISTER_ACTION;
        } else {
            smsAction = action;
        }
        detv_phone.requestFocus();
        InputMethodManager manager = (InputMethodManager) detv_phone.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (manager != null) {
            manager.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
        }
        init();

        Observable.timer(300, TimeUnit.MILLISECONDS)
                .subscribe(aLong -> {
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.showSoftInput(detv_phone, 0);
                }, t -> {
                });

    }


    void init() {
        if (isRegisterFromRedPacket) {
            tvFreePacketHint.setVisibility(View.VISIBLE);
        }
        jtv_country.setLeftText(String.format(FORMAT, country_name, country_code));
        if (smsAction.equals(UserConstants.REGISTER_ACTION)) {
            ll_protocol.setVisibility(View.VISIBLE);
        } else {
            ll_protocol.setVisibility(View.INVISIBLE);
        }
        if (!TextUtils.isEmpty(phoneNum)) {
            detv_phone.setText(phoneNum);
        }
    }


    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.jtv_country) {
            startActivityForResult(new Intent(this, CountryListActivity.class), 44);

        } else if (i == R.id.tv_protocol) {
            NewH5Activity.start(this, new H5Params("http://www.yidianling.com/agreement/reg", "用户协议"));

        } else if (i == R.id.rcb_next) {
            if ("0086".equals(country_code)) {
                if (detv_phone.getText().toString().length() != 11) {
                    ToastHelper.Companion.show("请输入11位手机号");
                    return;
                }
            } else {
                if (TextUtils.isEmpty(detv_phone.getText())) {
                    YdlCommonOut.Companion.showToast("请输入正确的手机号");
                    return;
                }
            }
            if (TextUtils.isEmpty(detv_phone.getText().toString())) {
                ToastHelper.Companion.show("请输入手机号!");
                return;
            }
            switch (smsAction) {
                case UserConstants.BIND_PHONE_ACTION://绑定手机
                    judge(UserConstants.BIND_PHONE_ACTION);
                    break;
                case UserConstants.REGISTER_ACTION://注册
                    judge(UserConstants.REGISTER_ACTION);
                    break;

                case UserConstants.FORGET_ACTION://忘记密码
                    judge(UserConstants.FORGET_ACTION);
                    break;

                case UserConstants.SIGNIN_ACTION:// 短信快捷登录
                    judge(UserConstants.SIGNIN_ACTION);
                    break;
            }

        }
    }


    private void judge(final String action) {

        UserHttp userHttp = UserHttpImpl.Companion.getInstance();
        userHttp.phoneExist(new ExistParam(country_code, detv_phone.getText().toString()))
                .compose(RxUtils.resultData())
                .map(ExistResponse::isExist)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> showProgressDialog(""))
                .doAfterTerminate(this::dismissProgressDialog)
                .subscribe(isExist -> {
                    LogHelper.Companion.getInstance().writeLogSync(String.format("%s成功", action));
                    switch (action) {
                        case UserConstants.BIND_PHONE_ACTION:
                            if (isExist == 1) {
                                getCode(action, true);
                            } else {
                                getCode(action, false);
                            }
                            break;
                        case UserConstants.REGISTER_ACTION:
                            if (isExist == 1) {
                                new CommonDialog(InputPhoneActivity.this)
                                        .setMessage("该手机号已注册")
                                        .setRightClick("登录", v -> {
                                            startActivity(new Intent(InputPhoneActivity.this, RegisterAndLoginActivity.class));
                                            finish();
                                        })
                                        .setLeftOnclick("取消", null)
                                        .show();
                            } else {
                                getCode(action, false);
                            }
                            break;
                        case UserConstants.FORGET_ACTION:
                            if (isExist == 0) {
                                ToastHelper.Companion.show("该手机还未注册");
                            } else {
                                getCode(action, true);
                            }
                            break;
                        case UserConstants.SIGNIN_ACTION:
                            if (isExist == 0) {
                                getCode(UserConstants.REGISTER_ACTION, false);
                            } else {
                                SmsLoginActivity.Companion.start(this, country_code, detv_phone.getText().toString(), isFromSplash);
                                finish();
                            }
                            break;
                    }
                }, new ThrowableConsumer() {
                    @Override
                    public void accept(@NotNull String msg) {
                        ToastHelper.Companion.show(msg);
                    }
                });

    }

    private void getCode(final String action, final boolean phoneIsExits) {

        UserHttp userHttp = UserHttpImpl.Companion.getInstance();
        userHttp.code(new CodeParam(country_code, detv_phone.getText().toString(), action))
                .compose(RxUtils.resultData())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> showProgressDialog(""))
                .doAfterTerminate(this::dismissProgressDialog)
                .subscribe(o -> {
                    LogHelper.Companion.getInstance().writeLogSync("获取验证码成功");
                    Intent intent = new Intent(InputPhoneActivity.this, GetIdentifyingCodeActivity.class);
                    intent.putExtra("action", action);
                    intent.putExtra("code", country_code);
                    intent.putExtra("isRegisted", phoneIsExits);
                    intent.putExtra("isFromSplash", isFromSplash);
                    intent.putExtra("lastGetCodeTime", (int) (System.currentTimeMillis() / 1000));
                    intent.putExtra("phoneNum", detv_phone.getText().toString());
                    intent.putExtra(UserConstants.IS_REGISTER_FROM_PACKET, isRegisterFromRedPacket);
                    startActivity(intent);
                    finish();
                }, new ThrowableConsumer() {
                    @Override
                    public void accept(@NotNull String msg) {
                        ToastHelper.Companion.show(msg);
                        LogHelper.Companion.getInstance().writeLogSync(String.format("获取验证码失败：%s", msg));
                    }
                });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 44 && resultCode == 45) {
            country_code = data.getStringExtra("code");
            country_name = data.getStringExtra("name");
            jtv_country.setLeftText(String.format("%s   +%s", country_name, country_code));
        }
    }

}
