package com.ahau.againstpestinfo.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.ahau.againstpestinfo.HttpProcessor.HttpCallback;
import com.ahau.againstpestinfo.HttpProcessor.HttpHelper;
import com.ahau.againstpestinfo.R;
import com.ahau.againstpestinfo.utils.LoginUtils;
import com.ahau.againstpestinfo.utils.URLUtils;

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

import java.util.HashMap;
import java.util.Map;


public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private Button loginbtn, registerbtn;
    private String username, password;
    private Boolean isrem;
    private CheckBox remembercb;
    private EditText usernameET, passwordET;
    private String userinfo_url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        // 锁定屏幕
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        intiViews();
    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.login:
                if (loginIssuccess()) {
                    Toast.makeText(LoginActivity.this, "正在登录，请稍等!", Toast.LENGTH_SHORT).show();
                    //dologin(); //不需要验证用户名，密码
                    login();
                }
                break;
            default:
                break;

        }
    }

    private void intiViews() {
        // TODO Auto-generated method stub
        loginbtn = (Button) findViewById(R.id.login);
        usernameET = (EditText) findViewById(R.id.username);
        passwordET = (EditText) findViewById(R.id.pwd);
        remembercb = (CheckBox) findViewById(R.id.remcb);
        loginbtn.setOnClickListener(this);

        //账户名密码的回显
        Map<String, String> map = LoginUtils.getUtil(getApplicationContext());
        if (map != null) {
            String username = (String) map.get("username");
            String password = (String) map.get("password");

            usernameET.setText(username);
            passwordET.setText(password);

            remembercb.setChecked(true);

        }
    }


    private boolean loginIssuccess() {

        username = usernameET.getText().toString();
        password = passwordET.getText().toString();
        isrem = remembercb.isChecked();

        if (TextUtils.isEmpty(username)) {
            // 用户输入用户名为空
            Toast.makeText(LoginActivity.this, "用户名不能为空!", Toast.LENGTH_SHORT).show();
            return false;
        } else if (TextUtils.isEmpty(password)) {
            // 密码不能为空
            Toast.makeText(LoginActivity.this, "密码不能为空!", Toast.LENGTH_SHORT).show();
            return false;
        }

        LoginUtils.saveUtil(getApplicationContext(), username, password);

        return true;

    }


    private void login() {
        /**
         * AsyncHttpClient client = new AsyncHttpClient();
         * client.get("http://www.google.com", new AsyncHttpResponseHandler() {
         *
         * @Override public void onSuccess(String response) {
         * System.out.println(response); } });
         */
        getUserinfo(username, password);
    }

    private void getUserinfo(String username, String password) {

        userinfo_url = URLUtils.defaultUrl + "/login?username=" + username + "&password="
                + password;

        System.out.println(URLUtils.defaultUrl + "/login?username=" + username + "&password="
                + password);
        // 服务器端写的是doGet()方法，因此此处必须是get请求，如果利用post请求，OnFailure()方法error会报错
        Map<String, Object> params = new HashMap<>();
        HttpHelper.obtain().get(userinfo_url, params, new HttpCallback<String>() {
            @Override
            public void onSuccess(String s) {
                if (!TextUtils.isEmpty(s)) {
                    JSONObject jsonObject;
                    try {
                        jsonObject = new JSONObject(s);

                        String status = jsonObject.getString("status");
                        if (status.equals("false")) {
                            System.out.println("denglushibai");
                            Toast.makeText(LoginActivity.this, " 用户名或密码输入错误,请重新登录!", Toast.LENGTH_SHORT).show();
                        } else if (status.equals("true")) {
                            dologin();

                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        });
    }
    public void dologin() {
        Intent intent = new Intent();
        intent.setClass(LoginActivity.this, SearchActivity.class);
        startActivity(intent);
    }
}