package com.huawei.hwmdemo.view.sdk;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.huawei.cloudlink.openapi.HWMSdk;
import com.huawei.hwmbiz.eventbus.LoginResult;
import com.huawei.hwmbiz.login.api.AppIdAuthParam;
import com.huawei.hwmconf.presentation.error.ErrorMessageFactory;
import com.huawei.hwmdemo.R;
import com.huawei.hwmdemo.constant.ConfigConstant;
import com.huawei.hwmdemo.utils.AppIdContants;
import com.huawei.hwmdemo.utils.DemoUtil;
import com.huawei.hwmdemo.utils.PreferencesUtil;
import com.huawei.hwmdemo.view.base.BaseDialogFragment;
import com.huawei.hwmfoundation.HwmContext;
import com.huawei.hwmfoundation.callback.HwmCallback;
import com.huawei.hwmlogger.HCLog;

public class AppIdLoginFragment extends BaseDialogFragment {
    public final static String TAG = AppIdLoginFragment.class.getSimpleName();

    private Context context;
    private View rootView;

    private TextView appIdView;
    private TextView corpIdView;
    private TextView userIdView;
    private TextView nonceView;
    private TextView expireTimeView;
    private TextView signatureView;
    private TextView userNameView;
    private TextView userEmailView;
    private TextView userPhoneView;
    private TextView deptCodeView;


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        rootView = inflater.inflate(R.layout.sdk_appid_login, container, false);
        initView();
        Button joinBtn = rootView.findViewById(R.id.btn_2);
        joinBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login(v);
            }
        });
        return rootView;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    //通过配置，把默认值绑定在界面
    private void initView() {
        appIdView = rootView.findViewById(R.id.app_id);
        appIdView.setText(PreferencesUtil.getStringPreference(this.getActivity().getApplicationContext(),
            ConfigConstant.KEY_APP_ID, AppIdContants.APP_ID));
        appIdView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                PreferencesUtil.setStringPreferences(AppIdLoginFragment.this.getActivity().getApplicationContext(),
                    ConfigConstant.KEY_APP_ID, editable.toString());
            }
        });


        corpIdView = rootView.findViewById(R.id.corp_id);
        corpIdView.setText(AppIdContants.CORP_ID);

        userIdView = rootView.findViewById(R.id.user_id);

        nonceView = rootView.findViewById(R.id.nonce);

        expireTimeView = rootView.findViewById(R.id.expire_time);
        expireTimeView.setText("" + AppIdContants.EXPIRE_TIME);

        signatureView = rootView.findViewById(R.id.signature);
        
        userNameView = rootView.findViewById(R.id.user_name);
        userEmailView = rootView.findViewById(R.id.user_email);
        userPhoneView = rootView.findViewById(R.id.user_phone);
        deptCodeView = rootView.findViewById(R.id.dept_code);
    }




    private void login(View v) {
        String corpId = corpIdView.getText().toString();
        String userId = userIdView.getText().toString();
        String nonce = nonceView.getText().toString();
        long expireTime = Long.parseLong(expireTimeView.getText().toString());
        String userName = userNameView.getText().toString();
        String userEmail = userEmailView.getText().toString();
        String userPhone = userPhoneView.getText().toString();
        String deptCode = deptCodeView.getText().toString();
        String signature = signatureView.getText().toString();

        showLoading();

        AppIdAuthParam appIdAuthParam = new AppIdAuthParam();
        appIdAuthParam.setNonce(nonce);
        appIdAuthParam.setCorpId(corpId);
        appIdAuthParam.setUserName(userName);
        appIdAuthParam.setThirdUserId(userId);
        appIdAuthParam.setSignature(signature);
        appIdAuthParam.setUserEmail(userEmail);
        appIdAuthParam.setExpireTime(expireTime);
        //注意邮箱需要符合邮箱格式要求
        //注意手机号码必须符合手机格式，比如(^$|^[+]?[0-9]+$)
        appIdAuthParam.setUserPhone(userPhone);
        appIdAuthParam.setDeptCode(deptCode);

        HWMSdk.getOpenApi(getActivity().getApplication()).loginByAppId(appIdAuthParam, new HwmCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                doDismissDialogAndFragment();
                if (loginResult != null) {
                    DemoUtil.showToast("登录成功" + loginResult.getUserUuid() + "; account:" + loginResult.getAccount()
                        + "; thirdAccount:" + loginResult.getThirdAccount());
                } else {
                    DemoUtil.showToast("已登录");
                }
            }

            @Override
            public void onFailed(int retCode, String desc) {
                HCLog.i(TAG,"loginByAppId onFailed" + retCode + " " + desc);
                HwmContext.getInstance().runOnMainThread(() -> {
                    String err = ErrorMessageFactory.create(retCode);
                    if (TextUtils.isEmpty(err)) {
                        err = desc;
                    }
                    DemoUtil.showToastDialog("loginByAppId", retCode, err);
                    doDismissDialogAndFragment();
                });
            }
        });
    }


}
