package com.rv.home.rv.module.ui.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.LinkMovementMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.frame.base.url.Constance;
import com.frame.rv.InviteCodeUtil;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.presenter.CommonPresenter;
import com.ruiwenliu.wrapper.bean.BeanUserInfo;
import com.ruiwenliu.wrapper.util.RxJavaManager;
import com.ruiwenliu.wrapper.util.listener.TextChangedListener;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.component.utils.AppCookie;
import com.rv.home.R;
import com.rv.home.R2;
import com.rv.home.rv.module.ApiConfig;
import com.rv.home.rv.module.basic.BaseLoginActivity;
import com.rv.home.rv.module.ui.login.bean.RegisteredBean;
import com.rv.home.rv.module.ui.login.bean.SendCodeBean;
import com.rv.home.rv.module.ui.login.bean.VerifyDataBean;
import com.rv.home.rv.module.ui.login.bean.VerifyResultBean;
import com.umeng.socialize.bean.SHARE_MEDIA;


import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class RegisteredActivity extends BaseLoginActivity<CommonPresenter> {
    @BindView(R2.id.et_phone)
    EditText etPhone;
    @BindView(R2.id.iv_clear_phone)
    ImageView ivClearPhone;
    @BindView(R2.id.et_phone_code)
    EditText etPhoneCode;
    @BindView(R2.id.iv_clear_code)
    ImageView ivClearCode;
    @BindView(R2.id.tv_get_code)
    TextView tvGetCode;
    @BindView(R2.id.et_pwd)
    EditText etPwd;
    @BindView(R2.id.iv_clear_pwd)
    ImageView ivClearPwd;
    @BindView(R2.id.et_invite_code)
    EditText etInviteCode;
    @BindView(R2.id.cb_annotations)
    CheckBox cbAnnotations;
    @BindView(R2.id.tv_registered)
    TextView tvRegistered;
    @BindView(R2.id.tv_agreement)
    TextView tvAgreement;

    private Disposable mDisposable;
    private boolean pwdShow;//密码
    private boolean confirmShow;//确认密码
    private int mType;
    private int jumptype;

    public static Intent getIntent(Context context, int type, int jumptype) {
        return new Intent(context, RegisteredActivity.class)
                .putExtra("type", type)
                .putExtra("jumptype", jumptype);
    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {

    }

    @Override
    protected int setLayout() {
        return R.layout.rv_act_registered;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        mType = intent.getIntExtra("type", 0);
        jumptype = intent.getIntExtra("jumptype", 0);
        titleView.setTitle(mActivity.getString(mType == 0 ? R.string.rv_phone_registered : R.string.rv_forget_pwd));
        tvRegistered.setText(mActivity.getString(mType == 0 ? R.string.rv_registered : R.string.rv_reset_pwd));
        cbAnnotations.setVisibility(mType == 0 ? View.VISIBLE : View.GONE);
        tvAgreement.setVisibility(mType == 0 ? View.VISIBLE : View.GONE);

        ((View) etInviteCode.getParent()).setVisibility(mType == 0 ? View.VISIBLE : View.GONE);
        if (mType == 0) {
            String inviteCode = AppCookie.getStringValue("code");
            if (!TextUtils.isEmpty(inviteCode)) {
                if (inviteCode.contains("_")) {
                    String[] split = inviteCode.split("_");
                    if (split != null && split.length > 0) {
                        etInviteCode.setText(split[0]);
                    }
                } else {
                    etInviteCode.setText(inviteCode);

                }
                etInviteCode.setEnabled(false);
            }
        }
        editListener(etPhone);
        editListener(etPhoneCode);
        editListener(etPwd);
        editListener(etInviteCode);
        initData();
        if (mType == 0)
            privacyAgree();
    }


    private void privacyAgree() {
        new PrivacyTipsDialog.Builder(this, new PrivacyTipsDialog.PrivacyListener() {
            @Override
            public void agree() {
                cbAnnotations.setChecked(true);
            }

            @Override
            public void disAgree() {
                finish();
            }
        }).show();

    }

    private void initData() {
        String str = "注册即表示同意滴房车《用户协议》和《隐私政策》";

        SpannableStringBuilder ssb = new SpannableStringBuilder();
        ssb.append(str);

        final int start = str.indexOf("《");//第一个出现的位置
        ssb.setSpan(new ClickableSpan() {

            @Override
            public void onClick(View widget) {
                avoidHintColor(widget);
                ARouter.getInstance().build(Constance.ACTIVITY_URL_WEBVIEW)
                        .withString("title", "用户协议")
                        .withString("url", ApiConfig.HTTP_URL_CAR_TYPE_NOTICE)
                        .withInt("type", 15)
                        .navigation();
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(getResources().getColor(R.color.gray_FFB74B));       //设置文件颜色
                // 去掉下划线
                ds.setUnderlineText(false);
            }

        }, start, start + 6, 0);

        final int end = str.lastIndexOf("《");//最后一个出现的位置
        ssb.setSpan(new ClickableSpan() {

            @Override
            public void onClick(View widget) {
                avoidHintColor(widget);
                ARouter.getInstance().build(Constance.ACTIVITY_URL_WEBVIEW)
                        .withString("title", "隐私政策")
                        .withString("url", ApiConfig.HTTP_URL_CAR_TYPE_NOTICE)
                        .withInt("type", 19)
                        .navigation();

            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(getResources().getColor(R.color.gray_FFB74B));       //设置文件颜色
                // 去掉下划线
                ds.setUnderlineText(false);
            }

        }, end, end + 6, 0);

        tvAgreement.setMovementMethod(LinkMovementMethod.getInstance());
        tvAgreement.setText(ssb, TextView.BufferType.SPANNABLE);
    }


    private void avoidHintColor(View view) {
        if (view instanceof TextView)
            ((TextView) view).setHighlightColor(getResources().getColor(android.R.color.transparent));
    }

    private VerifyDialog.Builder builder;

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                showToast(mActivity.getString(R.string.rv_phone_code_toast));
                sendCode(60);
                break;
            case 1:
                processLoginData((RegisteredBean) result);
                if (jumptype == 1) {
                    mPresenter.saveOnclick("4", "");
                }
                break;
            case 10:
                setDataUser((BeanUserInfo) result);
                break;
            case 11:
                VerifyDataBean bean = (VerifyDataBean) result;
                if (bean != null && bean.isRel() && bean.getData() != null) {
                    if (builder == null && !isVerifyCancel) {
                        builder = new VerifyDialog.Builder(this, bean.getData());
                        builder.setListener(verifyListener);
                        builder.create().show();
                    } else {
                        builder.change(bean.getData());
                    }
                }
                break;
            case 12:
                VerifyResultBean resultBean = (VerifyResultBean) result;
                if (resultBean != null && resultBean.isData()) {
                    if (builder != null) {
                        builder.dismiss();
                        builder = null;
                    }
                    showToast("验证成功");
                    sendCode();
                } else {
                    showToast("点击错误，将为您重新生成图片");
                    sendVerifyCode();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onShowError(String errorMsg, int errorType) {
        super.onShowError(errorMsg, errorType);
        Toast.makeText(this, errorMsg, Toast.LENGTH_LONG).show();
    }

    @OnClick({R2.id.iv_clear_phone, R2.id.iv_clear_code, R2.id.tv_get_code, R2.id.iv_clear_pwd, R2.id.tv_agreement, R2.id.tv_registered})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.iv_clear_phone) {
            clearEditData(etPhone);
        } else if (view.getId() == R.id.iv_clear_code) {
            clearEditData(etPhoneCode);
        } else if (view.getId() == R.id.tv_get_code) {
            if (TextUtils.isEmpty(getPhone())) {
                showToast(mActivity.getString(R.string.rv_phone_hint));
                return;
            }

            if (getPhone().length() != 11) {
                showToast("请输入正确手机号");
                return;
            }
            isVerifyCancel = false;
            if (mType == 0) {
                sendVerifyCode();
            } else {
                sendCode();
            }
        } else if (view.getId() == R.id.iv_clear_code) {
            pwdShow = !pwdShow;
            ivClearPwd.setSelected(pwdShow);
            etPwd.setTransformationMethod(pwdShow ? HideReturnsTransformationMethod.getInstance() : PasswordTransformationMethod.getInstance());
        } else if (view.getId() == R.id.iv_clear_pwd) {
            confirmShow = !confirmShow;
            ivClearPwd.setSelected(confirmShow);
            etPwd.setTransformationMethod(confirmShow ? HideReturnsTransformationMethod.getInstance() : PasswordTransformationMethod.getInstance());

        }
//        else if (view.getId() == R.id.iv_clear_again_pwd) {
//            confirmShow = !confirmShow;
//            ivClearAgainPwd.setSelected(confirmShow);
//            etAgainPwd.setTransformationMethod(confirmShow ? HideReturnsTransformationMethod.getInstance() : PasswordTransformationMethod.getInstance());
//        }
//        else if (view.getId() == R.id.tv_agreement) {
//            ARouter.getInstance().build(Constance.ACTIVITY_URL_WEBVIEW)
//                    .withString("title", "用户协议")
//                    .withString("url", ApiConfig.HTTP_URL_CAR_TYPE_NOTICE)
//                    .withInt("type", 15)
//                    .navigation();
//        }
        else if (view.getId() == R.id.tv_registered) {
            if (getPwd().length() < 8) {
                showToast(mActivity.getString(R.string.rv_pwd_length));
                return;
            }
//            if (!getPwd().equals(getAgainPwd())) {
//                showToast(mActivity.getString(R.string.rv_pwd_same));
//                return;
//            }

            if (mType == 1) {
                resetPwd();
                return;
            }
            if (cbAnnotations.isChecked() == false) {
                showToast(mActivity.getString(R.string.rv_confirm_agreement));
                return;
            }
            userRegister();
        }
    }

    private void sendVerifyCode() {
        mPresenter.getData(11, String.format(ApiConfig.HTTP_URL_PIC_VERIFY, new String[]{getPhone()}), VerifyDataBean.class, true);
    }

    private void verifyCode(int x, int y) {

//
//        Point point = new Point(x, y);
//        List<Point> pointList = new ArrayList<>();
//        pointList.add(point);
////        String pointListString = null;
////        try {
////            pointListString = URLEncoder.encode(new Gson().toJson(pointList),"UTF-8") ;
////        } catch (UnsupportedEncodingException e) {
////            e.printStackTrace();
////        }
//
////        JsonArray array = new JsonArray();
////        array.addAll(pointList);
//        String pointListString = JSONArray.toJSONString(pointList);
//        Map<String, String> params = new HashMap<>();
//        params.put("phone", getPhone());
//        params.put("pointList", dealString(x,y));
        dealString(x, y);
        mPresenter.getData(12, String.format(ApiConfig.HTTP_URL_CLICK_VERIFY, new String[]{getPhone(), pointList}), VerifyResultBean.class, true);
    }

    private String pointList;

    private void dealString(int x, int y) {
        pointList = "%5B%7B%22x%22:" + x + ",%22y%22:" + y + "%7D%5D";
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopCarousel();
    }

    /**
     * 发送验证码
     */
    private void sendCode() {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("username", getPhone());
        if (mType == 0) {
            map.put("type", 0);
            map.put("pointList", pointList);
        } else {
            map.put("type", 4);
        }
        mPresenter.postData(0, ApiConfig.HTTP_URL_SEND_CODE, SendCodeBean.class, map, true);
    }

    /**
     * 注册
     */
    private void userRegister() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        headMap.put("dataType", "json");
        headMap.put("contentType", "application/json;charset-UTF-8");
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("username", getPhone());
        map.put("mobilecode", getCode());
        map.put("password", getPwd());

        String inviteCode = AppCookie.getStringValue("code");
        if (!TextUtils.isEmpty(inviteCode)) {
            map.put("code", inviteCode);
        } else {
            map.put("code", InviteCodeUtil.getInviteCode(etInviteCode));
        }
        mPresenter.postData(RvFrameConfig.AUTH_POST, 1, ApiConfig.HTTP_URL_USER_REGISTER, RegisteredBean.class, map, headMap, true);
    }

    /**
     * 重置密码
     */
    private void resetPwd() {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("username", getPhone());
        map.put("mobilecode", getCode());
        map.put("password", getPwd());
        mPresenter.postData(1, ApiConfig.HTTP_URL_PWD_RESET, RegisteredBean.class, map, true);
    }


    /**
     * 获得手机号
     *
     * @return
     */
    private String getPhone() {
        return etPhone.getText().toString().trim();
    }

    /**
     * 获得验证码
     *
     * @return
     */
    private String getCode() {
        return etPhoneCode.getText().toString().trim();
    }

    /**
     * 获得输入密码
     *
     * @return
     */
    private String getPwd() {
        return etPwd.getText().toString().trim();
    }


    /**
     * 清除编辑数据
     */
    private void clearEditData(EditText text) {
        text.setText("");
    }

    /**
     * 文本输入监听
     *
     * @param editText
     */
    private void editListener(final EditText editText) {
        editText.addTextChangedListener(new TextChangedListener() {
            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
                if (editText.getId() == R.id.et_phone) {
                    ivClearPhone.setVisibility(getPhone().length() > 0 ? View.VISIBLE : View.GONE);
                } else if (editText.getId() == R.id.et_phone_code) {
                    ivClearCode.setVisibility(getCode().length() > 0 ? View.VISIBLE : View.GONE);
                } else if (editText.getId() == R.id.et_pwd) {
//                    ivClearPwd.setVisibility(getPwd().length() > 0 ? View.VISIBLE : View.GONE);
                } else if (editText.getId() == R.id.et_invite_code) {
//                    ivClearAgainPwd.setVisibility(getAgainPwd().length() > 0 ? View.VISIBLE : View.GONE);
                }
//                switch (editText.getId()) {
//                    case R.id.et_phone:
//                        ivClearPhone.setVisibility(getPhone().length() > 0 ? View.VISIBLE : View.GONE);
//                        break;
//                    case R.id.et_phone_code:
//                        ivClearCode.setVisibility(getCode().length() > 0 ? View.VISIBLE : View.GONE);
//                        break;
//                    case R.id.et_pwd:
//                        ivClearPwd.setVisibility(getPwd().length() > 0 ? View.VISIBLE : View.GONE);
//                        break;
//                    case R.id.et_again_pwd:
//                        ivClearAgainPwd.setVisibility(getAgainPwd().length() > 0 ? View.VISIBLE : View.GONE);
//                        break;
//                }
                if (etPhone.length() > 0 && etPhoneCode.length() > 0 && etPwd.length() > 0) {
                    tvRegistered.setEnabled(true);
                    tvRegistered.setSelected(true);
                } else {
                    tvRegistered.setEnabled(false);
                    tvRegistered.setSelected(false);
                }


            }
        });
    }

    /**
     * 发送验证码
     *
     * @param timeLong 验证码时长
     */
    private void sendCode(final int timeLong) {
        RxJavaManager.getInstance().sendCode(timeLong, new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                tvGetCode.setEnabled(false);

            }
        }, new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {
                mDisposable = d;
            }

            @Override
            public void onNext(Long aLong) {
                tvGetCode.setText("" + aLong + "s");
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

                tvGetCode.setEnabled(true);
                tvGetCode.setText(mActivity.getString(R.string.rv_login_rest));

            }
        });

    }

    /**
     * 停止计时
     */
    public void stopCarousel() {
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }


    @Override
    public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    private boolean isVerifyCancel = false;
    private boolean isVerifySucess = false;
    private VerifyDialog.VerifyListener verifyListener = new VerifyDialog.VerifyListener() {
        @Override
        public void cancel() {
            isVerifyCancel = true;
            builder = null;
        }

        @Override
        public void verify(int x, int y) {
            verifyCode(x, y);
        }

        @Override
        public void freshen() {
            if (!isVerifyCancel)
                sendVerifyCode();
        }
    };
}
