import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutterappfuyou/code/base/YSNetWorking.dart';
import 'package:flutterappfuyou/code/base/YSTools.dart';
import 'package:flutterappfuyou/code/version2/YSChangePassWord.dart';
import 'package:flutterappfuyou/code/version2/YSUrlPage.dart';
import 'package:package_info/package_info.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'YSBindInfo.dart';
import 'YSlogin.dart';
import 'base/YSBase.dart';

class YSSetting extends StatefulWidget {
  @override
  _YSSettingState createState() => _YSSettingState();
}

class _YSSettingState extends State<YSSetting> {
  String webStr,healthName;
  int healthId;
  List _showArray = [
    {'title':'账号绑定'},
    {'title':'推送设置','value':false},
    {'title':'服务条款'},
    {'title':'隐私政策'},
    {'title':'密码设置'},
    {'title':'清理缓存','value':'0.0B'},
    {'title':'版本号'},
    {'title':'账号注销'},
    {'title':'退出登录'}
  ];
  @override
  void initState() {
    Future.delayed(Duration(seconds: 0)).then((value){
      _getUserData();
      loadCache();
    });
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return YSBase(
      ystitle: '设置',
      yschild: Container(
        child: Column(
          children: [
            Container(
              child: ListView.separated(
                itemBuilder: (context,index){
                  Map item = _showArray[index];
                  return Container(
                    color: Colors.white,
                    width: ysWidth(context),
                    padding: EdgeInsets.only(top: 18,bottom: 18,left: 18,right: 18),
                    child: LayoutBuilder(
                      builder: (context,conSize){
                        return GestureDetector(
                          onTap: () async{
                            if(item['title']=='账号绑定'){
                              Navigator.of(context).push(
                                  CupertinoPageRoute(
                                      builder: (context){
                                        return YSBindInfo();
                                      }
                                  )
                              );
                            }else if(item['title']=='推送设置'){
                              // item['value'] = !item['value'];
                              // setState(() {});
                            }else if(item['title']=='服务条款'||item['title']=='隐私政策'){
                              Navigator.of(context).push(
                                  CupertinoPageRoute(
                                      builder: (context){
                                        return YSUrlPage(
                                          url: item['title']=='服务条款'?'https://fy.niwoshenghuo.com/tool/service':'https://fy.niwoshenghuo.com/tool/privacy',
                                          title: item['title'],
                                        );
                                      }
                                  )
                              );
                            }else if(item['title']=='密码设置'){
                              Navigator.of(context).push(
                                  CupertinoPageRoute(
                                      builder: (context){
                                        return YSChangePassWord();
                                      }
                                  )
                              );
                            }else if(item['title']=='清理缓存'){
                              showDialog(
                                  context:context,
                                  builder:(context){
                                    return AlertDialog(
                                      title: Text('提示',style: TextStyle(fontSize: 16,color: Color(0xFF292929),decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                      content: Text('确认清除缓存？',style: TextStyle(fontSize: 13,color: Color(0xFF292929),decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                      actions: [
                                        CupertinoButton(
                                          padding: EdgeInsets.all(0),
                                          child: Text('取消',style: TextStyle(fontSize: 13,color: Color(0xFF292929),decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                          onPressed: (){
                                            Navigator.pop(context);
                                          },
                                        ),
                                        CupertinoButton(
                                          padding: EdgeInsets.all(0),
                                          child: Text('确认',style: TextStyle(fontSize: 13,color: Color(0xFF292929),decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                          onPressed: (){
                                            Navigator.pop(context);
                                            _clearCache();
                                          },
                                        ),
                                      ],
                                    );
                                  }
                              );
                            }else if(item['title']=='版本号'){

                            }else if(item['title']=='账号注销'){
                              User.instance.idCard = null;
                              bool isCheck = await checkValue(context,tips: '您已经领取两筛免费券，如需注销请联系发券机构');
                              if(isCheck){
                                ysShowCenterAlertView(context, YSTipsAlertView(
                                  tipsStr: '是否注销此账号?',
                                  valueSetter: (value) async{
                                    if(value){
                                      Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'sign/delete', {});
                                      if(dict!=null){
                                        SharedPreferences prefer = await SharedPreferences.getInstance();
                                        prefer.remove('chapters');
                                        prefer.remove('token');
                                        prefer.remove('isMeans');
                                        Navigator.of(context).push(
                                            CupertinoPageRoute(
                                                builder: (context){
                                                  return YSLogin(isCheck: true,);
                                                }
                                            )
                                        );
                                      }
                                    }
                                  },
                                ));
                              }
                            }else if(item['title']=='退出登录'){
                              ysShowCenterAlertView(context, YSTipsAlertView(
                                tipsStr: '是否退出登录?',
                                valueSetter: (value) async{
                                  if(value){
                                    SharedPreferences prefer = await SharedPreferences.getInstance();
                                    prefer.remove('token');
                                    User.instance.idCard = null;
                                    Navigator.of(context).push(
                                        CupertinoPageRoute(
                                            builder: (context){
                                              return YSLogin(isCheck: true,);
                                            }
                                        )
                                    );
                                  }
                                },
                              ));
                            }
                          },
                          behavior: HitTestBehavior.opaque,
                          child: Row(
                            children: [
                              Container(
                                width: conSize.maxWidth*0.3,
                                child: Text(item['title'],style: TextStyle(color: Color(0xFF292929),fontSize: 14,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                              ),
                              Container(
                                width: conSize.maxWidth*0.7,
                                child: item['title']=='推送设置'?GestureDetector(
                                  onTap: (){
                                    item['value'] = !item['value'];
                                    setState(() {});
                                  },
                                  behavior: HitTestBehavior.opaque,
                                  child: Image.asset(
                                    'lib/images/${item['value']?'shut':'open'}.png',
                                    height: 20,
                                    width: 80,
                                  ),
                                ):Row(
                                  children: [
                                    Container(
                                      width: conSize.maxWidth*0.7-(item['title']!='版本号'?20:0),
                                      alignment: Alignment.centerRight,
                                      child: Text(item['value']??'',style: TextStyle(color: Color(0xFFAEB3BD),fontSize: 14,decoration: TextDecoration.none,fontWeight: FontWeight.normal)),
                                    ),
                                    if(item['title']!='版本号')Icon(Icons.chevron_right,size: 20,color: Color(0xFFAEB3BD),)
                                  ],
                                ),
                                alignment: Alignment.centerRight,
                              ),
                            ],
                          ),
                        );
                      },
                    ),
                  );
                },
                separatorBuilder: (context,index){
                  Map item = _showArray[index];
                  return item['title']=='推送设置'||item['title']=='账号注销'?Container(
                    height: 5,
                  ):Container(
                    height: 1.4,
                    padding: EdgeInsets.only(left: 18,right: 18),
                    width: ysWidth(context),
                    child: Image.asset('lib/images/line.png',fit: BoxFit.fitWidth,),
                  );
                },
                itemCount: _showArray.length,
                shrinkWrap: true,
                physics: NeverScrollableScrollPhysics(),
                padding: EdgeInsets.all(0),
              ),
            )
          ],
        ),
      ),
    );
  }

  _getUserData() async{
    Map dict = await ysRequestHttp(context, requestType.get, 'user/info', {});
    if(dict!=null){
      healthName = dict['health_name'];
      healthId = dict['health_id'];
      _getWebData();
    }
  }

  _getWebData() async{
    Map dict = await ysRequestHttpNoLoading(context, requestType.get, 'basic/info', {});
    if(dict!=null){
      webStr = dict['data']['service'];
      setState(() {});
    }
  }

  void _clearCache() async {
    Directory tempDir = await getTemporaryDirectory();
    //删除缓存目录
    await delDir(tempDir);
    await loadCache();
    ysFlutterToast(context, '清除缓存成功');
  }
  Future<Null> delDir(FileSystemEntity file) async {
    if (file is Directory) {
      final List<FileSystemEntity> children = file.listSync();
      for (final FileSystemEntity child in children) {
        var isHave =await child.exists(); //返回真假
        if(isHave){
          await delDir(child);
        }
      }
    }
    await file.delete();
  }
  Future<Null> loadCache() async {
    Directory tempDir = await getTemporaryDirectory();
    double value = await _getTotalSizeOfFilesInDir(tempDir);
    /*tempDir.list(followLinks: false,recursive: true).listen((file){
          //打印每个缓存文件的路径
        print(file.path);
      });*/
    print('临时目录大小: ' + value.toString());
    Map cacheMap = _showArray.firstWhere((element) => element['title']=='清理缓存');
    Map versionMap = _showArray.firstWhere((element) => element['title']=='版本号');
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    versionMap['value'] = packageInfo.version;
    cacheMap['value'] = _renderSize(value);
    // LogUtil.d('packageInfo========${versionMap['value']}=====${cacheMap['value']}');
    setState(() {});
  }
  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) {
      final List<FileSystemEntity> children = file.listSync();
      double total = 0;
      if (children != null)
        for (final FileSystemEntity child in children)
          total += await _getTotalSizeOfFilesInDir(child);
      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];
  }
}
