import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:http/http.dart';
import 'loginprefs.dart';

LoginPrefs loginPrefs = LoginPrefs();

class BaseService {
  //创建client实例
  final _client = http.Client();
  final String token =
      "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc1IiOjAsInJvbGVJZHMiOlsiODMiXSwidXNlcm5hbWUiOiJseWNzIiwidXNlcklkIjozNTYsIlBWIjoyLCJvcmciOiJhIiwiaWF0IjoxNzI1NTI2MDc0LCJleHAiOjE3MjY4MjIwNzR9.l47sd4L8OswBcHJxamGe9M5ttWqiukoJvE5QfwPARlw";

  // String baseUrl = "http://192.168.1.189:8001";//本地
  String baseUrl = "http://1.82.251.83:8001"; //线上
  String loginstatus = "登录失效";
  //发送GET请求
  getClient(String url, [bool useBaseUrl = true]) async {
    try {
      http.Response response = await _client
          .get(Uri.parse(useBaseUrl ? baseUrl + url : url), headers: {
        HttpHeaders.contentTypeHeader: "application/json",
        HttpHeaders.authorizationHeader: token,
      });
      var res = json.decode(response.body);
      if (res['message'].contains(loginstatus)) {
        loginPrefs.clearLogin();
        return;
      }
      return res;
    } catch (e) {
      print(e);
      return {};
    }
  }

  getHisFileClient(String url) async {
    String fullUrl = "$baseUrl$url";
    Map<String, String> headers = {
      HttpHeaders.contentTypeHeader: "text/plain",
      HttpHeaders.authorizationHeader: token,
    };
    Response response = await _client.get(Uri.parse(fullUrl), headers: headers);
    return response.body;
  }

  //发送POST请求
  postClient(String url, body) async {
    try {
      var data = json.encode(body);
      http.Response response = await _client.post(Uri.parse(baseUrl + url),
          headers: {
            HttpHeaders.contentTypeHeader: "application/json",
            HttpHeaders.authorizationHeader: token,
          },
          body: data);
      var res = json.decode(response.body);
      if (res['message'].contains(loginstatus)) {
        loginPrefs.clearLogin();
        return;
      }
      return res;
    } catch (e) {
      print(e);
      return {};
    }
  }
}

class GetServices {
  BaseService service = BaseService();
  // String projCode = 'CJGKJEBYYB';
  // int tid = 109;
  String projType;
  String projCode;
  GetServices({this.projCode = "WXLMB", this.projType = "cp_road"});
  // int tid = 1000;
  // String projType = "pile_cm";
// 道路边线
  Future getSideLine() async {
    try {
      Map res = await service.getClient(
          '/api/comm/side_line/list?proj_code=$projCode&proj_type=$projType');
      return res['data'];
    } catch (e) {
      return {};
    }
  }

// 设备绑定 --- 获取设备
  Future getDeviceBind() async {
    Map res = await service.getClient(
        '/api/sys/device_bind/list?proj_type=$projType&proj_code=$projCode');
    if (res['code'] == 1000) {
      return res['data'];
    } else {
      return [];
    }
  }

  getHisFileList() async {
    Map res = await service.getClient(
        '/api/cp_road/record/data_list?proj_code=$projCode&date=2023-10-26');
    return res['data'];
  }

// 文件数据
  getHisFile(String file) async {
    // String file = '12209/26/L0122.txt';
    file = file.substring(file.length - 18, file.length);
    var res = await service
        .getHisFileClient("/app/cp_road/record/data/$projCode/$file");
    return res;
  }

  getHisFil1(String file) async {
    file = file.substring(file.length - 18, file.length);
    String fullUrl =
        "http://192.168.1.154:8300/api/cp_road/record/data1/$projCode/$file";
    Map<String, String> headers = {
      // HttpHeaders.contentTypeHeader: "text/plain",
      HttpHeaders.authorizationHeader:
          "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc1JlZnJlc2giOmZhbHNlLCJpc1IiOjAsInJvbGVJZHMiOlsiMSIsIjI0Il0sInVzZXJuYW1lIjoiYWRtaW4iLCJ1c2VySWQiOjEsIlBWIjo1LCJvcmciOiJhIiwiZXhwIjoxNzI2NzE1ODE3LCJpYXQiOjE3MjU0MTk4MTd9.RZ5MpHavsF_akOZALiHo-Y3bx-f_tTp5tfgNatR-98k",
    };
    Response response =
        await http.Client().get(Uri.parse(fullUrl), headers: headers);
    var res = response.body;
    return res;
  }

  // 项目列表
  getproject() async {
    Map res = await service
        .getClient('/api/sys/project/list?org_code=a&proj_type=$projType');
    return res['data'];
  }

  // 液压夯
  getRcordData(int page, int size, String date,
      [String sort = "desc", String order = "tp_id"]) async {
    Map res = await service.getClient(
        "/api/$projType/record/page?page=$page&size=$size&org_code=a&proj_code=$projCode&date=$date&sort=$sort&order=$order");
    return res['data'];
  }

  //获取水泥搅拌桩点数据
  // getRcordData(int page, int size, String date,
  //     [String sort = "desc", String order = "pile_id"]) async {
  //   Map res = await service.getClient(
  //       "/api/$projType/record/page?page=$page&size=$size&org_code=a&proj_code=$projCode&tid=$tid&date=$date&sort=$sort&order=$order");
  //   return res['data'];
  // }

  // getRcordList(String date, String? dateEnd) async {
  //   dateEnd ??= date;
  //   Map res = await service.getClient(
  //       "/api/$projType/record/list?org_code=a&proj_code=$projCode&tid=$tid&date=$date&dateEnd=$dateEnd");
  //   return res['data'];
  // }
  getRcordList(String date, [String? dateEnd]) async {
    dateEnd ??= date;
    Map res = await service.getClient(
        "/api/$projType/record/list?org_code=a&proj_code=$projCode&date=$date&dateEnd=$dateEnd");
    if (res['code'] == 1000) {
      return res['data'];
    } else {
      return [];
    }
  }

  //获取施工记录的日期
  getworkDateData() async {
    Map res = await service.getClient(
        "/api/$projType/record/work_date?org_code=a&proj_code=$projCode");
    if (res['code'] == 1000) {
      return res['data'] ?? [];
    } else {
      return [];
    }
  }

  //施工详细记录
  getProcessData(int pileId) async {
    Map res = await service.getClient(
        "/api/$projType/process/list?pile_id=$pileId&proj_code=$projCode");
    return res['data'];
  }

  // 验证码
  getsmsCode(String phone) async {
    Map res =
        await service.postClient("/admin/base/open/smsCode", {"phone": phone});
    return res;
  }

  // 手机号登录
  phoneLogin(String phone, String smsCode) async {
    Map res = await service.postClient(
        "/admin/base/open/phone", {"phone": phone, "smsCode": smsCode});
    return res;
  }

  // 获取用户信息
  getPerson() async {
    Map res = await service.getClient("/admin/base/comm/person");
    return res['data'];
  }

  // 验证码
  getCaptcha() async {
    Map res =
        await service.getClient("/admin/base/open/captcha?height=40&width=150");
    return res['data'];
  }

  getAccountLogin(String captchaId, String password, String username,
      String verifyCode) async {
    Map res = await service.postClient("/admin/base/open/login", {
      "captchaId": captchaId,
      "password": password,
      "username": username,
      "verifyCode": verifyCode
    });
    return res;
  }

  getRtuLast() async {
    Map res = await service.getClient(
        "/api/t2n/rtu/rtu_last?proj_type=$projType&proj_code=$projCode");
    return res['data'];
  }

  getCoordTrans() async {
    Map res = await service.getClient(
        "/api/comm/coord_trans/list?proj_type=$projType&proj_code=$projCode");
    return res['data'];
  }
}