package com.naz.sdkdemo.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.naz.sdkdemo.NewMainActivity;
import com.naz.sdkdemo.R;
import com.naz.sdkdemo.base.BaseActivity;
import com.naz.sdkdemo.bean.UserDetail;
import com.naz.sdkdemo.comm.Constants;
import com.naz.sdkdemo.http.Api;
import com.naz.sdkdemo.okgo.callback.DialogCallback;
import com.naz.sdkdemo.okgo.module.BaseResponse;
import com.naz.sdkdemo.utils.SPUtils;
import com.naz.sdkdemo.weight.ActivityManager;
import com.naz.sdkdemo.weight.UserCache;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Description:登录
 * Author: ydd
 * Date:2020/10/27
 */
public class LoginActivity extends BaseActivity {
    @BindView(R.id.account_edt)
    EditText accountEdt;
    @BindView(R.id.password_edt)
    EditText passwordEdt;
    @BindView(R.id.select_factory)
    RelativeLayout selectFactory;
    @BindView(R.id.factory)
    TextView factory;
    @BindView(R.id.login_btn)
    Button loginBtn;

    @BindView(R.id.select)
    Spinner selectSpinner;

    @BindView(R.id.device_code)
    EditText deviceCodeTv;

    @Override
    public int getLayoutResId() {
        return R.layout.login_activity;
    }

    @Override
    public void initView() {
        String[] menuItems = {"请选择", "选项1", "选项2", "选项3", "选项4"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, menuItems);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        selectSpinner.setAdapter(adapter);
        selectSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }

        });
        deviceCodeTv.setText(UserCache.getDeviceId());
    }

    @OnClick({R.id.select_factory, R.id.login_btn, R.id.device_code})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.select_factory:

                break;
            case R.id.login_btn:
                UserCache.saveDeviceId(deviceCodeTv.getText().toString());
                String mPsw = passwordEdt.getText().toString().trim();
                if (mPsw.length() > 12 || mPsw.length() < 6) {
                    showToast("密码的长度在6-12位之间");
                    return;
                }
                loginByPswTask();
                break;
        }
    }

    /**
     * 登录
     */
    private void loginByPswTask() {
        JSONObject raw = new JSONObject();
        try {
            raw.put("name", accountEdt.getText().toString());
            raw.put("password", passwordEdt.getText().toString());
            raw.put("rememberMe", true);
            raw.put("imageCode", null);
            raw.put("loginBindingParameters", new JSONObject());
        } catch (JSONException e) {

        }
        OkGo.<BaseResponse<UserDetail>>post(Api.POST_LOGIN_CODE())
                .tag(this)
                .upJson(raw)
                .execute(new DialogCallback<BaseResponse<UserDetail>>(this) {
                    @Override
                    public void onSuccess(Response<BaseResponse<UserDetail>> response) {
                        UserDetail detail = response.body().userDto;
                        Log.d("Token", "token="+response.body().token);
                        SPUtils.setString(Constants.TOKEN, response.body().token);
                        SPUtils.setBoolean(Constants.IS_LOING, true);
                        UserCache.saveUserInfoDetail(detail);
                        Bundle bundle = new Bundle();
                        GoPathAndFinish(NewMainActivity.class,bundle);
                    }
                });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            MyFinish();// 连续点击两次退出系统
            return true;
        }
        return false;
    }

    long firstTime = 0;

    private void MyFinish() {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstTime > 2000) { // 如果两次按键时间间隔大于2秒，则不退出
            showToast("再按一次退出程序");
            firstTime = secondTime;// 更新firstTime
        } else { // 两次按键小于2秒时，退出应用
            ActivityManager.getActivityManager().exitApp();
            System.exit(0);
        }
    }
}
