package com.example.register.netrequest;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.example.register.entity.OrangeProduct;
import com.example.register.entity.OrangeProductPack;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpClientProduct {

    /**
     * 查询商品信息
     *
     * @return
     */
    public List<OrangeProduct> getProduct() throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://192.168.43.115:8081/orange/product/search")
                .build();
        Response response = okHttpClient.newCall(request).execute();
        JSONObject jsonObject = JSON.parseObject(Objects.requireNonNull(response.body()).string());
        List<OrangeProduct> list = JSON.parseObject(jsonObject.getString("data"), new TypeReference<List<OrangeProduct>>() {
        });
        return list;
    }

    /**
     * 获取图片
     *
     * @param imgUrl
     * @return
     * @throws IOException
     */
    public Bitmap getImageBitMap(String imgUrl) throws IOException {
        Bitmap bitmap;
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(imgUrl)
                .build();
        Response response = okHttpClient.newCall(request).execute();
        byte[] bytes = Objects.requireNonNull(response.body()).bytes();
        bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        return bitmap;

    }

    /**
     * 封装信息
     *
     * @return
     * @throws IOException
     */

    public List<OrangeProductPack> getProductPack() throws IOException {
        List<OrangeProductPack> packList = new ArrayList<>();
        List<OrangeProduct> list = getProduct();
        for (OrangeProduct orangeProduct : list) {
            OrangeProductPack orangeProductPack = new OrangeProductPack();
            orangeProductPack.setId(orangeProduct.getId());
            orangeProductPack.setImgBitmap(getImageBitMap(orangeProduct.getImgUrl()));
            orangeProductPack.setAddTime(orangeProduct.getAddTime());
            orangeProductPack.setPrice(orangeProduct.getPrice());
            packList.add(orangeProductPack);
        }
        return packList;
    }
}
