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 com.alibaba.android.arouter.launcher.ARouter;
import com.frame.base.url.Constance;
import com.frame.rv.InviteCodeUtil;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.presenter.CommonPresenter;
import com.ruiwenliu.wrapper.bean.BeanUserInfo;
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.umeng.socialize.bean.SHARE_MEDIA;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created :Auser
 * Date: 2019/5/21.
 * Desc:确认密码
 */
public class ConfirmPwdActivity extends BaseLoginActivity<CommonPresenter> {

    @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 String mOpenid;
    private String mHeadImg;
    private String mName;
    private int mIsQQ;
    private String mPhone;
    private String mCode;
    private String mUnionid;

    private boolean pwdShow;//密码
    private boolean confirmShow;//确认密码

    public static Intent getIntent(Context context, String openid, String headImg, int isQQ, String name, String phone, String code, String uid) {
        return new Intent(context, ConfirmPwdActivity.class)
                .putExtra("openid", openid)
                .putExtra("headImg", headImg)
                .putExtra("isQQ", isQQ)
                .putExtra("name", name)
                .putExtra("phone", phone)
                .putExtra("code", code)
                .putExtra("uid", uid);
    }


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

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        super.initView(savedInstanceState, titleView, intent);
        titleView.setTitle(mActivity.getString(R.string.rv_edit_pwd));
        editListener(etPwd);
        mOpenid = intent.getStringExtra("openid");
        mHeadImg = intent.getStringExtra("headImg");
        mName = intent.getStringExtra("name");
        mIsQQ = intent.getIntExtra("isQQ", 1);
        mCode = intent.getStringExtra("code");
        mPhone = intent.getStringExtra("phone");
        mUnionid = intent.getStringExtra("uid");

        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);
        }
        initData();
    }

    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));
    }


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

    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        if (requestType == 2) {
            processLoginData((RegisteredBean) result);
        } else if (requestType == 10) {
            setDataUser((BeanUserInfo) result);
        }
    }

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

    }


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


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

    @OnClick({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_pwd) {
            pwdShow = !pwdShow;
            ivClearPwd.setSelected(pwdShow);
            etPwd.setTransformationMethod(pwdShow ? HideReturnsTransformationMethod.getInstance() : PasswordTransformationMethod.getInstance());
        } else if (view.getId() == R.id.tv_agreement) {

        } else if (view.getId() == R.id.tv_registered) {
            if (getPwd().length() < 8) {
                showToast(mActivity.getString(R.string.rv_pwd_length));
                return;
            }

            if (cbAnnotations.isChecked() == false) {
                showToast(mActivity.getString(R.string.rv_confirm_agreement));
                return;
            }
            loginBind(mPhone, mCode, getPwd(), mName, mHeadImg, mOpenid, 2, mIsQQ, mUnionid);
        }
    }


    /**
     * 第三方登录
     *
     * @param username
     * @param mobilecode
     * @param password
     * @param nickname
     * @param headimgurl
     * @param openid
     * @param type
     */
    private void loginBind(String username, String mobilecode, String password, String nickname, String headimgurl, String openid, int type, int isQQ, String uid) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("username", username);
        map.put("mobilecode", mobilecode);
        map.put("password", password);
        map.put("nickname", nickname);
        map.put("headimgurl", headimgurl);
        map.put("openid", openid);
        map.put("type", type);
        map.put("isQQ", isQQ);
        if (isQQ == 0) {
            map.put("unionid", uid);
        }
        String inviteCode = AppCookie.getStringValue("code");
        if (!TextUtils.isEmpty(inviteCode)) {
            map.put("code", inviteCode);
        } else {
            map.put("code", InviteCodeUtil.getInviteCode(etInviteCode));
        }
        mPresenter.postData(2, ApiConfig.HTTP_URL_OTHER_LOGIN_BIND, RegisteredBean.class, map, true);
    }

    /**
     * 文本输入监听
     *
     * @param editText
     */
    private void editListener(final EditText editText) {
        editText.addTextChangedListener(new TextChangedListener() {
            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
//                switch (editText.getId()) {
//
//                    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 (etPwd.length() > 0) {
                    tvRegistered.setEnabled(true);
                    tvRegistered.setSelected(true);
                } else {
                    tvRegistered.setEnabled(false);
                    tvRegistered.setSelected(false);
                }
            }
        });
    }

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