#define LGFX_ESP32_S3_BOX_LITE
#define LGFX_AUTODETECT
#include <WiFi.h>
#include <HTTPClient.h>
#include <LovyanGFX.hpp>

// 定义GPIO引脚
#define BUTTON_PIN 1

// 存储按键状态标志
bool buttonFlag = false;

// 设置WiFi网络
const char* ssid = "xiaogui";
const char* password = "88888888";

// 电子书服务器地址
String ebook_url = "http://192.168.123.82:5000/ebook";

// 设置电子书首页页码
int currentPage = 1;

// 设置电子书最大页码
int maxPages = 5;

// 存储电子书内容的缓冲区
String bookContent = "";

// 创建LCD对象
static LGFX gfx;

// 连接wifi
void con_wifi(){
  Serial.print("连接到wifi网络");
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
  }
  Serial.println("");
  Serial.println("网络已连接");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  gfx.println("网络已连接");
  gfx.println(WiFi.localIP());
}


// 扫描按键
void ADCKeyScan(){
  int buttonValue = analogRead(BUTTON_PIN);
  //Serial.print("buttonValue：");
  //Serial.println(buttonValue);
  if (buttonValue > 3012 && buttonValue < 3022) {
    currentPage--;
    buttonFlag = true;
    if (currentPage < 1) {
      currentPage = maxPages;
    }
  } else if (buttonValue > 978 && buttonValue < 988) {
    currentPage++;
    buttonFlag = true;
    if (currentPage > maxPages) {
      currentPage = 1;
    }
  } else {
    buttonFlag = false;
  }
}


// 发送GET请求，从服务器上获取电子书内容
void getBookContent(int page) {
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    Serial.println(currentPage);
    Serial.println(page);
    Serial.println(ebook_url + "?page=" + page);
    http.begin(ebook_url + "?page=" + page);
    int httpCode = http.GET();
    if (httpCode > 0) {
      Serial.print("HTTP响应代码：");
      Serial.println(httpCode);
      bookContent = http.getString();
      Serial.print("HTTP响应内容：");
      Serial.println(bookContent);
    }else{
      Serial.print("Error Code：");
      Serial.println(httpCode); 
      gfx.println("");  
      gfx.print("Error Code："); 
      gfx.println(httpCode);   
    }
    http.end();
  }else{
    con_wifi();
  }
}


// 更新显示电子书内容
void showBookContent(){
  // 绘制电子书内容
  gfx.clear();
  gfx.setCursor(0, 0);
  gfx.println(bookContent);
  Serial.println(bookContent);
  
  //更新LCD显示
  gfx.flush();
}

void setup() {
  //初始化串口
  Serial.begin(115200);
  
  //初始化LCD
  gfx.init();
  gfx.setTextWrap(true, true);
  gfx.setFont(&fonts::efontCN_16_b);
  gfx.setTextColor(TFT_WHITE, TFT_BLACK);
  gfx.setTextSize(1, 2);

  // 连接wifi
  con_wifi();

  // 请求电子书内容
  getBookContent(currentPage);

  // 更新显示电子书内容
  showBookContent();
}

// 主程序
void loop() {
  // 检测ADC按键并更新页码
  ADCKeyScan();  
  if (buttonFlag == true){
    // 请求电子书内容
    getBookContent(currentPage);

    // 更新显示电子书内容
    showBookContent();
  }
  delay(200);
  
}

