part of library;

class LibraryController extends GetxController with GetTickerProviderStateMixin{

  final BuildContext context;
  LibraryController(this.context);
  // 分类数据
  List<CategoryModel> categories = [];
  // 标签数据
  List<LabelModel> labels = [];

  // 广告数组
  List<AdModel> ads = [];
  // 选中标签
  late FilterModel selectedLabel = FilterModel();
  // 选中分类
  late FilterModel selectedCategory = FilterModel();
  // 选中是否收费
  late FilterModel selectedFree = FilterModel();
  // 选中排序的 方式
  late FilterModel selectedDown = FilterModel();


  // late TabController tabController = TabController(length:categories.length, vsync: this);

  final EasyRefreshController refreshController = EasyRefreshController(
    controlFinishLoad: true,
    controlFinishRefresh: true,
  );

  // 图书列表数据
  List<CourseModel> books = [];

  List<FilterModel> filterCategories = [];
  List<FilterModel> filterLabels = [];
  List<FilterModel> filterFree = [
    FilterModel(id: '0', name: '收费',selected: false),
    FilterModel(id: '1', name: '免费',selected: false)
  ];
  List<FilterModel> filterDown = [
    FilterModel(id: 'read_num', name: '读过'),
    FilterModel(id: 'rating', name: '评分')
  ];


  final int _limit = 10;
  int _page = 1;
  bool _noMore = false;


  late AnimationController _controller;
  bool _show = false;

  late UModel _getModel;

  bool get show => _show;
  void setShow(bool value) {
    _show = !value;
    if (_show) {
      /// 开启动画
      _controller.forward();
    }
    else {
      /// 收回动画
      _controller.reverse();
    }
    update();
  }


  AnimationController get controller => _controller;

  @override
  void onInit() {
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 100),
    );
    
    super.onInit();

  }

  @override
  void onReady() async {
    // 获取标签数据
    _getLabels();
    // 获取分类数据
    _getTabs();
    // 获取广告数据
    _getAds();
    // 检测版本
    // if(Platform.isAndroid){
    //   _checkUpdates();
    // }
    // 测试添加数据库数据
    // testInsertData();


    final result = await Tools.checkCurrentNetStatus();
    // 有网络 并且是登录状态 的时候上传 笔记
    if (result && UserStore.to.isLogin){
      upload();
    }
    super.onReady();
  }

  @override
  void onClose() {
    // tabController.dispose();
    refreshController.dispose();
    super.onClose();
  }

  /// 重置
  void resetFilter() {
    for(FilterModel model in filterCategories){
      model.selected = false;
    }
    if(filterCategories.isNotEmpty){
      selectedCategory = filterCategories.first;
      selectedCategory.selected = true;

    }
    for(FilterModel model in filterLabels){
      model.selected = false;
    }
    if(filterLabels.isNotEmpty){
      selectedLabel = filterLabels.first;
      selectedLabel.selected = true;
    }

    for(FilterModel model in filterFree){
      model.selected = false;
    }

    for(FilterModel model in filterDown){
      model.selected = false;
    }

    // onRefresh();
    update();
  }

  /// 确定
  void sureFilter(){
    // WidgetsBinding.instance!.addPostFrameCallback((_) {
    //   tabController.animateTo(3); // 你想要的标签索引
    // });
    //  update();
    for(FilterModel model in filterCategories){
      if (model.selected){
        selectedCategory = model;
      }
    }

    for(FilterModel model in filterLabels){
      if(model.selected){
        selectedLabel= model;
      }
    }
    for(FilterModel model in filterFree){
      if(model.selected){
        selectedFree= model;
      }
    }

    for(FilterModel model in filterDown){
      if(model.selected){
        selectedDown= model;
      }
    }

    onRefresh();

  }

  void selectLabel(FilterModel model){
    for (FilterModel m in filterLabels){
      m.selected = false;
    }
    model.selected = true;
    selectedLabel = model;
    onRefresh();
  }

  void selectCategory(FilterModel model){
    for (FilterModel m in filterCategories){
      m.selected = false;
    }
    model.selected = true;
    selectedCategory = model;
    onRefresh();
  }

  /// 获取广告数据
  void _getAds() async {
    ads = await CommonAPI.list(type: '3');
    update();
  }

  /// 获取tab分类数据
  void _getTabs() async {

    categories = await LibraryAPI.categories();
    // tabController.dispose();
    // tabController = TabController(length:categories.length, vsync: this);

    filterCategories = categories.map((model) {
      return FilterModel(id: model.categoryId.toString(), name: model.name??'',selected: model.selected);
    }).toList();
    if(filterCategories.isNotEmpty){
      selectedCategory = filterCategories.first;
      selectedCategory.selected = true;
    }
    update();
  }

  /// 获取标签数据
  void _getLabels() async {
    labels = await LibraryAPI.labels();

    filterLabels = labels.map((model) {
      return FilterModel(id: model.labelId.toString(), name: model.name??'',selected: model.selected);
    }).toList();
    if (filterLabels.isNotEmpty){
      selectedLabel = filterLabels.first;
      selectedLabel.selected = true;
    }
    update(['label']);


  }

  /// 收藏 与 取消收藏
  void love({
    required CourseModel model
  }) async {

    num isCollection = 0;
    if (model.isCollection == 0){
      isCollection = 1;
    }

    bool result = await CommonAPI.love(bookId: model.bookId.toString(), love: isCollection.toString());
    if (result) {
      model.isCollection = isCollection;
    }
    update();
  }

  /// 批量上传离线笔记、高亮、划线的内容
  void upload() async{
    List<Map<String, dynamic>> data = await SqlManager.queryNoUploadData();

    Console.log('Sql-----查询到的数据-----------------------$data');
    if(data.isNotEmpty){
      for (Map<String, dynamic> temp in data){

        // 如果是笔记
        if (temp['type'] == '3'){
          // 存储url的数组
          List<String> finalAudios = [];
          // 存储url的数组
          List<String> finalImages = [];

          Map<String,dynamic> contentMap =  jsonDecode(temp['note_content']);
          List<String> audios = contentMap['audio'];
          if(audios.isNotEmpty){
            for(String path in audios){
              final url = await uploadSource(path: path);
              finalAudios.add(url);
            }
          }
          List<String> images = contentMap['image'];
          if(images.isNotEmpty){
            for(String path in images){
              final url = await uploadSource(path: path);
              finalImages.add(url);
            }
          }
          Map<String,dynamic> finalContentMap = {
            'text':contentMap['text'],
            'audio': finalAudios,
            'image': finalImages
          };
          temp['note_content'] = finalContentMap;
        }
      }
      final result = await LibraryAPI.uploadOffline(node: jsonEncode(data));
      // 上传成功后 更新数据库中的字段
      if (result) {
        SqlManager.updateUploadStatus();
      }
    }

  }

  // 上传文件
  Future<String> uploadSource({
    required String path
  }) async {
    // String result  = await CommonAPI.upload(path:path,fileTypes: 'comment');
    // return result;
    OssTool tool = OssTool('zxts-comment-file');
    final response = await tool.putObjectFile(path);
    Console.log('------response--------------------------${response.realUri}');
    return response.realUri.toString();
  }


  /// 获取图书列表数据
  Future<void> _getBooks([bool isRefresh = false]) async {
    _getAds();

    String sort = '';
    if (selectedDown.selected == true){
      if(selectedDown.up){
        sort = 'desc';
      }
      else{
        sort = 'asc';
      }
    }

    String sortField = '';
    if (selectedDown.selected == true){
      sortField = selectedDown.id ??'';
    }
    String isFree = '';
    if (selectedFree.selected == true){
      isFree = selectedFree.id ??'';
    }

    if (isRefresh) _page = 1;
    // 网路请求
    final result = await LibraryAPI.books(
      page: _page,
      limit: _limit,
      categoryId: selectedCategory.id??'',
      labelId: selectedLabel.id??'',
      isFree: isFree,
      sortField: sortField,
      sort :sort
      // sort:selectedDown.id!.isEmpty?'':selectedDown.up ==true?'desc':'asc'
    );
    // 如果是刷新 清理数据
    if (isRefresh) books.clear();
    books.addAll(result);
    _page ++;
    _noMore = result.length < _limit;
    update();

  }

  void onRefresh() async {
    try {
      await _getBooks(true);
      refreshController.finishRefresh(IndicatorResult.success);
      refreshController.resetFooter();
    } catch (error) {
      Console.log('----------获取图书---------------------------------------$error---------------');
      refreshController.finishRefresh(IndicatorResult.fail);
    }
  }

  void onLoading() async {
    if (_noMore) {
      refreshController.finishLoad(IndicatorResult.noMore);
      return;
    }
    try {
      await _getBooks();
      refreshController.finishLoad();
    } catch (error) {
      Console.log('----------获取图书---------------------------------------$error---------------');
      refreshController.finishLoad(IndicatorResult.fail);
    }
  }

  void testInsertData() async{
    Map<String, dynamic> data = {
      'types': 1,
      'book_id': 175,
      'chapter_id': 334,
      'is_open': 1,
      'color': 'blue',
      'content': 'This is a note content',
      'upload': 0,
      'positioning': 'top',
      'note_content': 'This is a note',
      'node_id': 0,
    };

    await SqlManager.insertData(data);
  }

  void _checkUpdates() async {
    UModel model = await MineAPI.update();
    _getModel = model;
    final packageInfo = await PackageInfo.fromPlatform();
    int update =  verifyVersion(model.version!,packageInfo.version);
    if (update == 1) {
      _showUpdateDialog(false);
    }
  }

  int verifyVersion(String newVersion, String oldVersion) {
    List<String> newVersionArr = newVersion.split('.');
    List<String> oldVersionArr = oldVersion.split('.');

    for (int i = 0; i < 3; i++) {
      int newVersionNumber = int.parse(newVersionArr[i]);
      int oldVersionNumber = int.parse(oldVersionArr[i]);

      if (newVersionNumber < oldVersionNumber) {
        return -1; // 新版本小于旧版本
      } else if (newVersionNumber > oldVersionNumber) {
        return 1; // 新版本大于旧版本
      }
    }

    return 0; // 两个版本号相等
  }

  _showUpdateDialog(bool forcedUpgrade) {
    showDialog(
      context: context,
      barrierDismissible: !forcedUpgrade,
      builder: (BuildContext context) {
        return WillPopScope(
          onWillPop: () => Future.value(!forcedUpgrade),
          child: AlertDialog(
            insetPadding: EdgeInsets.zero, // 设置水平边距
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8.0.w),
            ),
            // 去除操作按钮区域的内边距
            actionsPadding: EdgeInsets.zero,
            actions: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      SizedBox(
                        height: 25.5.w,
                      ),
                      SizedBox(
                        height: 92.w,
                        width: 92.w,
                        child: Image.asset('assets/images/app_update.png'),
                      ),
                      SizedBox(
                        height: 13.w,
                      ),
                      Text(
                        "版本更新",
                        style: TextStyle(
                            fontSize: 14.w,
                            color: Colours.c3,
                            fontWeight: Fonts.medium),
                      ),
                      Padding(
                        padding: EdgeInsets.only(top: 5.5.w),
                        child: Text(
                          '发现新版本V${_getModel.version}',
                          style: TextStyle(
                              fontSize: 10.w,
                              color: Colours.c9,
                              fontWeight: Fonts.medium),
                        ),
                      ),
                      SizedBox(
                        height: 22.w,
                      ),
                      Container(
                        height: 1, // 设置分割线的高度
                        width: 216.5.w, // 设置分割线的宽度
                        color: Colours.cLine, // 设置分割线的颜色
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          if (!forcedUpgrade)
                            Padding(padding: EdgeInsets.only(right: 28.w),
                              child:  GestureDetector(
                                child:
                                Container(
                                  width: 85.w,
                                  color: Colours.cFF,
                                  alignment: Alignment.center,
                                  child:  const Text(
                                    '稍后再说',
                                    style: TextStyle(
                                        color: Colours.c6,
                                        fontSize: 15,
                                        fontWeight: Fonts.medium),
                                  ),
                                ),
                                onTap: () => Navigator.of(context).pop(),
                              ),),

                          Container(
                            height: 39.5.w, // 设置分割线的高度
                            width: 1, // 设置分割线的宽度
                            color: Colours.cLine, // 设置分割线的颜色
                          ),
                          Padding(padding: EdgeInsets.only(left: 28.w),
                            child:   GestureDetector(
                              child: Container(
                                width: 85.w,
                                color: Colours.cFF,
                                alignment: Alignment.center,
                                child:  const Text(
                                  '立即更新',
                                  style: TextStyle(
                                      color: Colours.cAB1941,
                                      fontSize: 15,
                                      fontWeight: Fonts.boldSemi),
                                ),
                              ),
                              onTap: () {
                                _appUpdate();
                                if (!forcedUpgrade) {
                                  Navigator.of(context).pop();
                                }
                              },
                            ),
                          ),

                        ],
                      ),
                    ],
                  ),
                ],
              ),
            ],
          ),
        );
      },
    );
  }

  /// TODO: 苹果市场app地址
  _appUpdate() {
    UpdateModel model = UpdateModel(
      _getModel.url!,
      "zijing.apk",
      "ic_launcher",
      'https://apps.apple.com/us/app/%E7%B4%AB%E8%8D%86%E6%95%B0%E6%99%BA%E5%AD%A6%E5%A0%82/id6476735372',
    );
    AzhonAppUpdate.update(model).then((value) => debugPrint('$value'));
  }

}