package com.yyrh.ui.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.content.SharedPreferences;
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.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.yyrh.constant.SDKSettings;
import com.yyrh.constant.URLConstants;
import com.yyrh.networking.NetRequestApi;
import com.yyrh.ui.dialog.WvPageListDialog;
import com.yyrh.ui.userlist.DatabaseHelper;
import com.yyrh.utils.ResourceUtil;
import com.yyrh.utils.TosUtil;
import com.yyrh.utils.Utils;

import java.util.HashMap;

public class UserRetrievePwdFragment extends BaseFragment {

    private EditText et_user_phone,et_user_code,et_user_pwd;
    private Button btn_get_code,reg_compete_btn;
    private ImageButton close_btn;

    private TextView tv_tip_2;

    private TimeCount timer;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(ResourceUtil.getLayoutId(getActivity(),"hnyy_retrieve_pwd"), 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"));
        et_user_pwd  = view.findViewById(ResourceUtil.getId(getActivity(), "et_user_pwd"));
        btn_get_code  = view.findViewById(ResourceUtil.getId(getActivity(), "btn_get_code"));
        reg_compete_btn  = view.findViewById(ResourceUtil.getId(getActivity(), "reg_compete_btn"));

        tv_tip_2 = view.findViewById(ResourceUtil.getId(getActivity(), "tv_tip_2"));
        tv_tip_2.setOnClickListener(this);
        close_btn  = view.findViewById(ResourceUtil.getId(getActivity(), "close_btn"));

        btn_get_code.setOnClickListener(this);
        close_btn.setOnClickListener(this);
        reg_compete_btn.setOnClickListener(this);

        timer = new TimeCount(60000, 1000);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);

        int id = v.getId();
        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,"modify_pwd");
        }else if (id == ResourceUtil.getId(getActivity(), "reg_compete_btn")) {
            String phone =  et_user_phone.getText().toString();
            String code = et_user_code.getText().toString();
            String pwd = et_user_pwd.getText().toString();
            if (phone.length() < 10) {

                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(pwd.length() < 6 || Utils.judgeStrNull(pwd))
            {
                new TosUtil(getActivity(),TosUtil.TOAST_ERROR, getString(ResourceUtil.getStringId(getActivity(), "hnyy_pwd_limit_6"))).show();

                return;
            }
            resetPwdWithPhone(getActivity(),phone,code,pwd);

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

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

        }else if (id == ResourceUtil.getId(getActivity(), "tv_tip_2")) {
            if (!Utils.judgeStrNull(SDKSettings.initConfig.service_center)){



                new WvPageListDialog(getActivity(),ResourceUtil.getStyleId(getActivity(),"hnyy_half_black_dialog"),SDKSettings.initConfig.service_center).show();

            }
        }

    }


    private void  getPhoneCaptcha(Activity activity, String phone, String action){
        NetRequestApi.getPhoneCaptcha(activity, phone, action, new UserPhoneLoginFragment.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");


        timer.start();
    }

    class TimeCount extends CountDownTimer {

        public TimeCount(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 ResetPwdCallback {

        void onResetSuccess(String msg);
        void onResetFailed(String msg);


    }

    private void resetPwdWithPhone(final Activity activity, final String phone, String code, final String pwd) {
        NetRequestApi.resetPwdWithPhone(activity, phone, code, pwd, new ResetPwdCallback() {
            @Override
            public void onResetSuccess(String msg) {



                HashMap<String, String> map = new HashMap();
                map.put("username", phone);
                map.put("password", pwd);
                map.put("login_token", "");
                Utils.setSharedPreferences("yyrh",map,getActivity());



                String timeStamp = System.currentTimeMillis() + "";
                String delete_sql = "delete from user where name = '" + phone + "'";
                String insert_sql = "insert into user(name,pwd,login_token,time) values('" + phone
                        + "','" + pwd + "','"  + "" + "','" + timeStamp + "')";

                DatabaseHelper.excuteSql(getActivity(), delete_sql);
                DatabaseHelper.excuteSql(getActivity(), insert_sql);


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

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


            }

            @Override
            public void onResetFailed(String msg) {

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

            }
        });
    }


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

    }
}
