package com.yyrh.ui.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.yyrh.constant.SDKSettings;
import com.yyrh.constant.URLConstants;
import com.yyrh.networking.NetRequestApi;
import com.yyrh.sdk.SDKEntry;
import com.yyrh.sdk.YyrhSdkManager;
import com.yyrh.ui.dialog.WvPageListDialog;
import com.yyrh.utils.ResourceUtil;
import com.yyrh.utils.SignUtils;
import com.yyrh.utils.TosUtil;
import com.yyrh.utils.Utils;
import com.yyrh.utils.YYLog;

import static com.yyrh.constant.Constants.CLICK_INTERVAL;
import static com.yyrh.constant.URLConstants.RSAKEY;


public class UserPhoneLoginFragment extends BaseFragment {


    private EditText et_user_phone,et_user_code;
    private CheckBox cb_register;
    private TextView tv_tip,tv_private_policy;
    private Button btn_get_code,btn_account_login,btn_guest_login,btn_reg_compete;
    private CodeVerifyTimeCount codeVerifyTimeCount;
    private long clickLoginTime = 0L;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(ResourceUtil.getLayoutId(getActivity(),"hnyy_phone_login"), container, false);
        view.setClickable(true);



        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        et_user_phone = view.findViewById(ResourceUtil.getId(getActivity(),"et_user_phone"));
        et_user_code = view.findViewById(ResourceUtil.getId(getActivity(),"et_user_code"));
        cb_register = view.findViewById(ResourceUtil.getId(getActivity(),"cb_register"));

        tv_tip = view.findViewById(ResourceUtil.getId(getActivity(),"tv_tip"));
        tv_tip.setOnClickListener(this);
        tv_private_policy = view.findViewById(ResourceUtil.getId(getActivity(),"tv_private_policy"));
        tv_private_policy.setOnClickListener(this);
        btn_get_code = view.findViewById(ResourceUtil.getId(getActivity(),"btn_get_code"));
        btn_get_code.setOnClickListener(this);
        btn_account_login = view.findViewById(ResourceUtil.getId(getActivity(),"btn_account_login"));
        btn_account_login.setOnClickListener(this);
        btn_guest_login = view.findViewById(ResourceUtil.getId(getActivity(),"btn_guest_login"));
        btn_guest_login.setOnClickListener(this);
        btn_reg_compete = view.findViewById(ResourceUtil.getId(getActivity(),"btn_reg_compete"));
        btn_reg_compete.setOnClickListener(this);




    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int id = v.getId();
        if(id == ResourceUtil.getId(getActivity(), "tv_tip")){


            new WvPageListDialog(getActivity(),ResourceUtil.getStyleId(getActivity(),"hnyy_base_dialog"),SDKSettings.initConfig.agreement_user).show();


        }else if(id == ResourceUtil.getId(getActivity(), "tv_private_policy")){



            new WvPageListDialog(getActivity(),ResourceUtil.getStyleId(getActivity(),"hnyy_base_dialog"),SDKSettings.initConfig.agreement_privacy).show();

        }else if(id == ResourceUtil.getId(getActivity(), "btn_reg_compete")){

            if (System.currentTimeMillis() - clickLoginTime < CLICK_INTERVAL) {
                YYLog.i("调用登录接口太频繁，拦截此次操作");
                return;
            }
            clickLoginTime = System.currentTimeMillis();

            registerWithPhone(getActivity());

        }else if(id == ResourceUtil.getId(getActivity(), "btn_get_code")){

            String phone =  et_user_phone.getText().toString();

            if (phone.length() < 10) {
                new TosUtil(getActivity(),TosUtil.TOAST_ERROR, getString(ResourceUtil.getStringId(getActivity(), "hnyy_pls_input_right_phone"))).show();

                return;
            }
            getPhoneCaptcha(getActivity(),phone,"register");

        }else if(id == ResourceUtil.getId(getActivity(), "btn_account_login")){

            Fragment accountLoginFragment = FragmentUtils.getSdkFragment(getActivity(),FragmentUtils.SDK_LOGIN_TAG);
            replaceFragmentToActivity(getFragmentManager(),accountLoginFragment,ResourceUtil.getId(getActivity(),"hnyy_content"));

        }else if(id == ResourceUtil.getId(getActivity(), "btn_guest_login")){
            Fragment accountLoginFragment = FragmentUtils.getSdkFragment(getActivity(),FragmentUtils.SDK_REGISTER_TAG);
            replaceFragmentToActivity(getFragmentManager(),accountLoginFragment,ResourceUtil.getId(getActivity(),"hnyy_content"));

        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (codeVerifyTimeCount != null){
            codeVerifyTimeCount.cancel();
        }

    }

    private void registerWithPhone(final Activity activity){
        final String code = et_user_code.getText().toString();
        final String account = et_user_phone.getText().toString();


        if(account.length() < 10 || Utils.judgeStrNull(account))
        {
            new TosUtil(getActivity(),TosUtil.TOAST_ERROR,getString(ResourceUtil.getStringId(getActivity(), "hnyy_pls_input_right_phone"))).show();


            return;
        }

        if(code.length() < 4 || Utils.judgeStrNull(code))
        {
            new TosUtil(getActivity(),TosUtil.TOAST_ERROR, getString(ResourceUtil.getStringId(getActivity(), "hnyy_pls_input_right_code"))).show();

            return;
        }

        if (!cb_register.isChecked()){

            new TosUtil(getActivity(), TosUtil.TOAST_ERROR,getString(ResourceUtil.getStringId(getActivity(), "hnyy_pls_checked_reg_tip"))).show();

            return;

        }



        NetRequestApi.phoneLoginWithSms(activity,account ,code, new PhoneLoginCallback() {
            @Override
            public void onPhoneLoginSuccess(String msg) {

                YyrhSdkManager.defaultManager().saveUserLoginInfo(getActivity(),account,"",SDKSettings.loginData.login_token,msg);

                SDKEntry.getSdkInstance().adSdkCallback.onRegisterSuccess(account);

                getActivity().finish();
            }

            @Override
            public void onPhoneLoginFailed(String msg) {
                new TosUtil(getActivity(),TosUtil.TOAST_ERROR, msg).show();
            }

            @Override
            public void onPhoneNewLogin() {
                Fragment accountLoginFragment = FragmentUtils.getSdkFragment(getActivity(),FragmentUtils.SDK_PHONE_SET_LOGIN_PWD_TAG);
                Bundle bundle  = new Bundle();
                bundle.putString("account",account);
                bundle.putString("code",code);
                accountLoginFragment.setArguments(bundle);
                replaceFragmentToActivity(getFragmentManager(),accountLoginFragment,ResourceUtil.getId(getActivity(),"hnyy_content"));

            }

        });
    }


    private void  getPhoneCaptcha(Activity activity, String phone, String action){
        NetRequestApi.getPhoneCaptcha(activity, phone, action, new CaptchaCallback() {
            @Override
            public void onGetSuccess(String msg) {
                getCodeSuccess();

                new TosUtil(getActivity(),TosUtil.TOAST_GREEN,getString(ResourceUtil.getStringId(getActivity(), "hnyy_send_code_success"))).show();


            }

            @Override
            public void onGetFailed(String msg) {

                new TosUtil(getActivity(),TosUtil.TOAST_ERROR,msg).show();

            }
        });
    }
    private void getCodeSuccess() {
        btn_get_code.setEnabled(false);
        btn_get_code.setText("60s");

        codeVerifyTimeCount = new CodeVerifyTimeCount(60000, 1000);
        codeVerifyTimeCount.start();
    }

    class CodeVerifyTimeCount extends CountDownTimer {

        public CodeVerifyTimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub
            btn_get_code.setText(millisUntilFinished / 1000 + "s");

        }

        @Override
        public void onFinish() {
            // TODO Auto-generated method stub
            btn_get_code.setEnabled(true);

            btn_get_code.setText(ResourceUtil.getStringId(getActivity(), "hnyy_get_phone_code"));
        }

    }

    public interface CaptchaCallback {

        void onGetSuccess(String msg);
        void onGetFailed(String msg);


    }

    public interface PhoneLoginCallback {

        void onPhoneLoginSuccess(String msg);
        void onPhoneLoginFailed(String msg);
        void onPhoneNewLogin();

    }




}
