import 'dart:io';

import 'package:flutter/material.dart';
import 'package:package_info/package_info.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sport/bean/UpdateInfo.dart';
import 'package:sport/provider/bluetooth.dart';
import 'package:sport/router/navigator_util.dart';
import 'package:sport/router/routes.dart';
import 'package:sport/services/api/inject_api.dart';
import 'package:sport/services/api/resp.dart';
import 'package:sport/utils/toast.dart';
import 'package:sport/widgets/appbar.dart';
import 'package:sport/widgets/button_primary.dart';
import 'package:sport/widgets/dialog/alert_dialog.dart';
import 'package:sport/widgets/dialog/request_dialog.dart';
import 'package:sport/widgets/image.dart';
import 'package:sport/widgets/list_tile.dart';
import 'package:sport/widgets/space.dart';
import 'package:url_launcher/url_launcher.dart';

class SettingPage extends StatefulWidget {
  @override
  _PageState createState() => _PageState();
}

class _PageState extends State<SettingPage> with InjectApi {
  String _cacheSizeStr = "";
  String _version = "";

  @override
  void initState() {
    super.initState();
    loadCache();
    PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
      setState(() {
        _version = packageInfo.version;
      });
    });
  }

  ///加载缓存
  Future<Null> loadCache() async {
    Directory tempDir = await getTemporaryDirectory();
    print(tempDir);

    double value = await _getTotalSizeOfFilesInDir(tempDir);
    /*tempDir.list(followLinks: false,recursive: true).listen((file){
          //打印每个缓存文件的路径
        print(file.path);
      });*/
    print('临时目录大小: ' + value.toString());
    setState(() {
      _cacheSizeStr = _renderSize(value); // _cacheSizeStr用来存储大小的值
    });
    return;
  }

  Future<double> _getTotalSizeOfFilesInDir(final FileSystemEntity file) async {
    if (file is File) {
      int length = await file.length();
      return double.parse(length.toString());
    }
    if (file is Directory) {
      double total = 0;
      try {
        final List<FileSystemEntity> children = file.listSync();
        if (children != null) for (final FileSystemEntity child in children) total += await _getTotalSizeOfFilesInDir(child).catchError((e){});
      } catch (e) {
        // print(e);
      }
      return total;
    }
    return 0;
  }

  _renderSize(double value) {
    if (null == value) {
      return 0;
    }
    List<String> unitArr = List()..add('B')..add('K')..add('M')..add('G');
    int index = 0;
    while (value > 1024) {
      index++;
      value = value / 1024;
    }
    String size = value.toStringAsFixed(2);
    return size + unitArr[index];
  }

  void _clearCache() async {
    Directory tempDir = await getTemporaryDirectory();
    //删除缓存目录
    await delDir(tempDir);
    await loadCache();
    ToastUtil.show('清除缓存成功');
  }

  ///递归方式删除目录
  Future<Null> delDir(FileSystemEntity file) async {
    if (file is Directory) {
      try {
        final List<FileSystemEntity> children = file.listSync();
        for (final FileSystemEntity child in children) {
                await delDir(child);
              }
      } catch (e) {
        print(e);
      }
    }
    await file.delete();
  }

  @override
  Widget build(BuildContext context) {
    const contentPadding = EdgeInsets.symmetric(horizontal: 0.0);
    return Scaffold(
        backgroundColor: Colors.white,
        body: CustomScrollView(
          slivers: <Widget>[
            buildSliverAppBar(context, "设置"),
            SliverPadding(
              padding: const EdgeInsets.symmetric(horizontal: 12),
              sliver: SliverToBoxAdapter(
                child: ListView(
                  padding: EdgeInsets.zero,
                  physics: NeverScrollableScrollPhysics(),
                  shrinkWrap: true,
                  children: divideTiles(
                    context: context,
                    includeLast: true,
                    tiles: [
                      ListTile(
                        title: Text('消息提醒'),
                        trailing: arrowRight5(),
                        contentPadding: contentPadding,
                        onTap: () => NavigatorUtil.go(context, Routes.messageSetting),
                      ),
                      ListTile(
                        title: Text('帐号管理'),
                        trailing: arrowRight5(),
                        contentPadding: contentPadding,
                        onTap: () => NavigatorUtil.go(context, Routes.account),
                      ),
                      ListTile(
                        title: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: <Widget>[
                            Text('清理缓存'),
                            Text(
                              "$_cacheSizeStr",
                              style: Theme.of(context).textTheme.bodyText2,
                            )
                          ],
                        ),
                        onTap: () => _clearCache(),
                        trailing: arrowRight5(),
                        contentPadding: contentPadding,
                      ),
                      ListTile(
                        title: Text('用户协议'),
                        trailing: arrowRight5(),
                        contentPadding: contentPadding,
                        onTap: () => NavigatorUtil.go(context, Routes.serviceagreement),
                      ),
                      ListTile(
                        title: Text('隐私协议'),
                        trailing: arrowRight5(),
                        contentPadding: contentPadding,
                        onTap: () => NavigatorUtil.go(context, Routes.privacypolicy),
                      ),
                      ListTile(
                        title: Row(
                          children: <Widget>[
                            Expanded(
                              child: Text(Platform.isAndroid ? '检查新版本' : '版本信息'),
                            ),
                            Text("当前版本：V$_version")
                          ],
                        ),
                        onTap: () async {
                          if (Platform.isAndroid) {
                            request(context, () async {
                              String version = (await PackageInfo.fromPlatform()).version;
                              RespData<UpdateInfo> data = await api.checkUpdate(version).catchError((err) {});
                              if (data.code == 0) {
                                UpdateInfo info = data.data;
                                if (!info.needUpdate) {
                                  ToastUtil.show("当前已是最新版本");
                                  return;
                                }
                                if (await showDialog(
                                      context: context,
                                      builder: (context) => CustomAlertDialog(
                                          title: '发现新版本 ${info.lastVersion.version}',
                                          child: Container(
                                              width: double.infinity,
                                              padding: const EdgeInsets.symmetric(horizontal: 24.0),
                                              child: Text(
                                                "${info.lastVersion.detail}",
                                                style: TextStyle(fontSize: 14, color: Color(0xff333333), height: 1.4),
                                              )),
                                          textOk: '立即更新',
                                          ok: () => Navigator.of(context).pop(true)),
                                    ) ==
                                    true) {
                                  launch(info.lastVersion.downloadUrl);
                                }
                              }else{
                                ToastUtil.show("当前已是最新版本");
                              }
                            });
                          }
                        },
                        trailing: arrowRight5(),
                        contentPadding: contentPadding,
                      )
                    ],
                  ).toList(),
                ),
              ),
            ),
            SliverPadding(
              padding: const EdgeInsets.symmetric(horizontal: 12),
              sliver: SliverToBoxAdapter(
                child: Column(
                  children: <Widget>[
                    Space(
                      height: 24,
                    ),
                    PrimaryButton(
                      content: "退出登录",
                      callback: () async {
                        if (await showDialog(
                              context: context,
                              builder: (context) => CustomAlertDialog(title: '是否退出登录', ok: () => Navigator.of(context).pop(true)),
                            ) ==
                            true) {
                          SharedPreferences prefs = await SharedPreferences.getInstance();
                          prefs.clear();
                          Provider.of<Bluetooth>(context,listen: false).disconnectDevice();
                          NavigatorUtil.goLogin(context);
                        }
                      },
                    ),
                  ],
                ),
              ),
            )
          ],
        ));
  }
}
