package com.example.register.netrequest;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.register.entity.User;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpUser {

    /**
     * 用户登录验证
     *
     * @param orangeUser
     */
    public User userLogin(User orangeUser) throws IOException {
        OkHttpClient okHttpClient= new OkHttpClient();
        //数据类型为json格式
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        //将对象转为JSON字符串
        String jsonStr = JSONObject.toJSONString(orangeUser);

        RequestBody requestBody = RequestBody.create(jsonStr, mediaType);
        Request request = new Request.Builder()
                .url("http://192.168.43.115:8081/orange/user/login")
                .post(requestBody)
                .build();

        Response response = okHttpClient.newCall(request).execute();

        String responseStr = response.body().string();
        System.out.println("responseStr = " + responseStr);
        JSONObject jsonObject = JSON.parseObject(responseStr);
        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
        User orangeUser1 = JSON.toJavaObject(jsonObject1, User.class);
        return orangeUser1;
    }

    /**
     * 用户注册
     *
     * @param orangeUser
     * @return
     * @throws IOException
     */
    public boolean userRegister(User orangeUser) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        //数据类型为json格式
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        //将对象转为JSON字符串
        String jsonStr = JSONObject.toJSONString(orangeUser);
        RequestBody requestBody = RequestBody.create(jsonStr, mediaType);
        Request request = new Request.Builder()
                .url("http://192.168.43.115:8081/orange/user/register")
                .post(requestBody)
                .build();
        Response response = okHttpClient.newCall(request).execute();
        JSONObject jsonObject = JSON.parseObject(response.body().string());
        Log.i("register", "userRegister: "+jsonObject);
        return jsonObject.getBoolean("flag");
    }


}
