package com.yidianling.user.mine;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.ydl.ydlcommon.base.BaseActivity;
import com.ydl.ydlcommon.bean.StatusBarOptions;
import com.ydl.ydlcommon.data.http.RxUtils;
import com.ydl.ydlcommon.data.http.ThrowableConsumer;
import com.ydl.ydlcommon.utils.ActivityManager;
import com.ydl.ydlcommon.utils.remind.ToastHelper;
import com.ydl.ydlcommon.view.JumpTextView;
import com.ydl.ydlcommon.view.RoundCornerButton;
import com.yidianling.common.tools.ToastUtil;
import com.yidianling.user.R;
import com.yidianling.user.UserHelper;
import com.yidianling.user.event.UpdateBindStatusEvent;
import com.yidianling.user.http.UserHttp;
import com.yidianling.user.http.UserHttpImpl;
import com.yidianling.user.http.request.ChangePhone;
import com.yidianling.user.http.request.CodeParam;
import com.yidianling.user.ui.CountryListActivity;

import org.jetbrains.annotations.NotNull;

import de.greenrobot.event.EventBus;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * 更换手机
 */
public class PhoneChangeActivity extends BaseActivity implements View.OnClickListener {

    JumpTextView jtv_country;
    EditText new_phone;
    TextView change_get_code;
    EditText change_code;

    RoundCornerButton change_submit;
    private String defauleName = "中国";
    private String defauleCode = "0086";

    private int lastGetCodeTime;

    private UserHttp userHttp;

    //按钮是否可点击
    boolean isDisable = true;

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

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

    @Override
    protected void initDataAndEvent() {
        jtv_country = findViewById(R.id.jtv_country);
        new_phone = findViewById(R.id.new_phone);
        change_get_code = findViewById(R.id.change_get_code);
        change_code = findViewById(R.id.change_code);
        change_submit = findViewById(R.id.change_submit);
        userHttp = UserHttpImpl.Companion.getInstance();

        change_submit.setOnClickListener(this);
        jtv_country.setOnClickListener(this);
        change_get_code.setOnClickListener(this);
    }

    @SuppressLint("CheckResult")
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.change_submit) {
            if (checkVcode()) {
                showProgressDialog("");

                userHttp.changePhone(new ChangePhone(defauleCode,
                        change_code.getText().toString().trim(),
                        new_phone.getText().toString().trim()))
                        .compose(RxUtils.resultData())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(o -> {
                            dismissProgressDialog();
                            ActivityManager.Companion.finishActivity(PwdCheckActivity.class);
                            UserHelper.INSTANCE.getUserInfo().getUserInfo().setPhone(new_phone.getText().toString().trim());
                            EventBus.getDefault().post(new UpdateBindStatusEvent());
                            ToastUtil.toastShort("更换成功");
                            finish();
                        }, new ThrowableConsumer() {
                            @Override
                            public void accept(@NotNull String msg) {
                                dismissProgressDialog();
                                ToastHelper.Companion.show(msg);
                            }
                        });

            }
        } else if (id == R.id.jtv_country) {
            startActivityForResult(new Intent(this, CountryListActivity.class), 44);
        } else if (id == R.id.change_get_code) {
            if (checkPhone()) {

                userHttp.code(new CodeParam(defauleCode, new_phone.getText().toString().trim(), "forget"))
                        .compose(RxUtils.resultData())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(o -> {
                            ToastHelper.Companion.show("验证码发送成功");
                            lastGetCodeTime = (int) (System.currentTimeMillis() / 1000);
                            isDisable = false;
                            handler.sendEmptyMessage(1);
                        }, new ThrowableConsumer() {
                            @Override
                            public void accept(@NotNull String msg) {
                                ToastHelper.Companion.show(msg);
                            }
                        });

            }
        }
    }


    public Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (change_get_code != null) {
                //获取当前时间和验证码的时间差
                int currentTimeInSecond = (int) (System.currentTimeMillis() / 1000);
                int leftTime = currentTimeInSecond - lastGetCodeTime;

                //时间差大于60.则可以重新获取
                if (leftTime > 60) {
                    if (isDisable) {
                        change_get_code.setTextColor(0xFF49D281);
                        change_get_code.setText("重新获取");
                        isDisable = false;
                    }
                } else {//否则不让重新获取
                    change_get_code.setTextColor(0xFFADADAD);
                    isDisable = true;
                    change_get_code.setText(
                            String.format("重发(%d)", 60 - leftTime)
                    );
                    handler.sendEmptyMessageDelayed(1, 1000);
                }
            }

            return true;
        }
    });


    private boolean checkVcode() {
        String vcode = change_code.getText().toString().trim();
        if (TextUtils.isEmpty(vcode)) {
            ToastUtil.toastShort("请输入验证码");
            return false;
        }
        return true;
    }

    private boolean checkPhone() {
        String newPhone = new_phone.getText().toString().trim();
        if (TextUtils.isEmpty(newPhone)) {
            ToastUtil.toastShort("手机号不能为空");
            return false;
        }
        if (newPhone.length() != 11) {
            ToastUtil.toastShort("请输入11位手机号");
            return false;
        }
        return true;
    }

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

}
