import 'dart:convert';

import 'package:ef/ef.dart';
import 'package:vbvs_app/common/util/Dio.dart';
import 'package:vbvs_app/common/util/MyUtils.dart';
import 'package:vbvs_app/controller/user_info_controller.dart';

class BookExperienceListModel {
  List bookInfoList = []; //预约列表
  List experienceStoreModelList = [];
}

class BookExperienceListController
    extends GetControllerEx<BookExperienceListModel> {
  BookExperienceListController() {
    attr = GetModel(BookExperienceListModel()).obs;
  }

  resetParm() {
    model.bookInfoList = [];
    model.experienceStoreModelList = [];
    total = 0;
    page = 0;
    lock = false;
    updateAll();
  }

  getAllBook() {
    ApiService.reservation
        .get(
            "/agent/userBook/config/getBookStoreList?storeName=&latitude=31.8512&longitude=117.26061&page=0&size=20000&sort=distance")
        .then((d) {
      model.experienceStoreModelList = d.data["records"];
      updateAll();
    });
  }

  int total = 0;
  int page = 0;
  bool lock = false;

  getData({int count = 10, Function? finished}) {
    if (page != 0 && page * count > total) {
      finished?.call();
      return;
    }
    if (lock) {
      finished?.call();
      return;
    }
    lock = true;
    int page_ = page;
    String tel = Get.find<UserInfoController>().model.user?.phone ?? "";
    if (tel.isEmpty) {
      showToast("用户未存在手机号");
      finished?.call();
      return;
    }
    ApiService.reservation
        .get(
            "/agent/userBook/list?extUserId=$tel&page=$page_&size=$count&sort=create_time,desc")
        .then((d) {
      lock = false;
      finished?.call();
      if (page == 0) {
        model.bookInfoList = d.data["records"];
      } else {
        int index = 0;
        d.data["records"]?.forEach((item) {
          if (model.bookInfoList
                  .indexWhere((item2) => item2["id"] == item["id"]) ==
              -1) {
            model.bookInfoList.add(item);
          } else {
            model.bookInfoList[index] = item;
          }
          index++;
        });
      }
      page = page_ + 1;
      total = d.data["total"];
      updateAll();
    }).catchError((d) {
      lock = false;
      finished?.call();
    });
  }

  cancelBook(id, {Function? success}) {
    String tel = Get.find<UserInfoController>().model.user?.phone ?? "";
    if (tel.isEmpty) {
      showToast("用户未存在手机号");
      return;
    }
    LoadingDialog.show("提交中...");
    ApiService.reservation
        .post("/agent/userBook/cancel?extUserId=$tel&id=$id")
        .then((d) {
      page = 0;
      getData(finished: () {
        LoadingDialog.hide();
      });
      success?.call();
    }).catchError((d) {
      LoadingDialog.hide();
    });
  }

  messageAdd(Map data) {
    return ApiService.request.post("/api/message/info", data: {
      "type": 0,
      "status": 1,
      "read": 1,
      "data": jsonEncode(data)
    });
  }
}
