import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/main.dart';
import 'package:huixiang/utils/ImgCachePath.dart';
import 'package:huixiang/utils/event_type.dart';
import 'package:huixiang/utils/flutter_utils.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:huixiang/utils/min.dart';
import 'package:huixiang/view_widget/round_button.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class SettingPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _SettingPage();
  }
}

class _SettingPage extends State<SettingPage> {
  String locale = "tw";

  String cacheTotal = "0B";

  @override
  void initState() {
    super.initState();
    setLanguage();

    AppUtils.total().then((value) {
      cacheTotal = (value > 0) ? "${(value / 1024.0 ~/ 1024.0)}M" : "0B";
      setState(() {});
    });
  }

  setLanguage() async {
    SharedPreferences shared = await SharedPreferences.getInstance();
    locale = shared.getString('language');
    if (mounted) setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        backgroundColor: Colors.white,
        leading: GestureDetector(
            child: Icon(
              Icons.arrow_back_ios,
              color: Colors.black,
            ),
            onTap: () {
              Navigator.of(context).pop();
            }),
        title: Text(
         S.of(context).shezhi,
          style: TextStyle(
            fontWeight: MyFontWeight.regular,
            fontSize: 17.sp,
            color: Color(0xFF0D0D0D),
          ),
        ),
        centerTitle: true,
        elevation: 0.0,
      ),
      body: Container(
        decoration: new BoxDecoration(
          border:
              Border(bottom: BorderSide(color: Color(0xffF7F7F7), width: 0.0)),
          color: Color(0xffF7F7F7),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.max,
          children: [
            SizedBox(
              height: 16.h,
            ),
            GestureDetector(
              child: settingSingleItem(S.of(context).gerenxinxi),
              onTap: () {
                Navigator.of(context).pushNamed('/router/user_info_page');
              },
            ),
            GestureDetector(
              child: settingSingleItem(S.of(context).shouhuodi),
              onTap: () {
                Navigator.of(context).pushNamed('/router/manage_address_page');
              },
            ),
            SizedBox(
              height: 16.h,
            ),
            GestureDetector(
              child: settingSingleItem(S.of(context).zhanghaoyuanquan),
              onTap: () {
                Navigator.of(context).pushNamed('/router/account_security_page');
              },
            ),
            SizedBox(
              height: 16.h,
            ),
            GestureDetector(
              onTap: () {
                showCupertinoModalPopup(
                  context: context,
                  builder: (contetx) {
                    return CupertinoActionSheet(
                      title: Text("更换语言"),
                      actions: [
                        CupertinoActionSheetAction(
                          child: Text('简体中文'),
                          onPressed: () {
                            changeLanguage("zh");
                          },
                          isDefaultAction: true,
                          isDestructiveAction: false,
                        ),
                        CupertinoActionSheetAction(
                          child: Text('繁体中文'),
                          onPressed: () {
                            changeLanguage("tw");
                          },
                          isDefaultAction: true,
                          isDestructiveAction: false,
                        ),
                        CupertinoActionSheetAction(
                          child: Text('英文'),
                          onPressed: () {
                            changeLanguage("en");
                          },
                          isDefaultAction: true,
                          isDestructiveAction: false,
                        ),
                      ],
                      cancelButton: CupertinoActionSheetAction(
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                        child: Text("取消"),
                        isDestructiveAction: true,
                      ),
                    );
                  },
                );
              },
              child: settingItem(
                  S.of(context).yuyan,
                  locale == "tw"
                      ? S.of(context).fantizhongwen
                      : (locale == "en" ?S.of(context).yingwen:S.of(context).zhongwenjianti)),
            ),
            GestureDetector(
              child: settingSingleItem(S.of(context).quanxian),
              onTap: () {
                Navigator.of(context).pushNamed('/router/permission_setting');
              },
            ),
            SizedBox(
              height: 16.h,
            ),
            GestureDetector(
              child: settingItem(S.of(context).qinglihuancun, cacheTotal),
              onTap: () {
                clearCache();
              },
            ),
            SizedBox(
              height: 16.h,
            ),
            GestureDetector(
              child: settingSingleItem(S.of(context).zhuxiaozhanghao),
              onTap: () {
                Navigator.of(context).pushNamed('/router/logout_page');
              },
            ),
            SizedBox(
              height: 16.h,
            ),
            // GestureDetector(
            //   child: settingSingleItem(S.of(context).bangzhuyufankui),
            //   onTap: () {
            //     Navigator.of(context).pushNamed('/router/help_feedback_page');
            //   },
            // ),
            GestureDetector(
              child: settingSingleItem(S.of(context).guanyu),
              onTap: () {
                Navigator.of(context).pushNamed('/router/about_page');
              },
            ),
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.end,
                mainAxisSize: MainAxisSize.max,
                children: [
                  InkWell(
                    onTap: () {
                      logOut();
                    },
                    child: Container(
                      height: 54.h,
                      alignment: Alignment.center,
                      margin:EdgeInsets.symmetric(horizontal: 16.w,vertical:25.h),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(45),
                      ),
                      child: RoundButton(
                        text: S.of(context).tuichudenglu,
                        backgroup: Color(0xFF32A060),
                        textColor: Colors.white,
                        fontSize: 16.sp,
                        radius:45,
                        fontWeight: MyFontWeight.semi_bold,
                      ),
                    ),
                  ),
                ],
              ),
              flex: 1,
            )
          ],
        ),
      ),
    );
  }

  clearCache() async {
    if (Platform.isAndroid) {
      if (!(await Min.isInitialize())) {
        await Min.initialize();
      }
    }

    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    List<String> miniAppids = sharedPreferences.getStringList("miniAppid");
    if (miniAppids != null && miniAppids.length > 0) {
      miniAppids.forEach((element) async {
        print("appid: $element");
        await Min.closeCurrentApp();
        String path = await Min.getAppBasePath(element);
        AppUtils.deleteDirectory(Directory(path));
        String filePath = "";
        if (Platform.isAndroid) {
          filePath = (await getExternalStorageDirectory()).path;
        } else {
          filePath = (await getApplicationDocumentsDirectory()).path;
        }
        AppUtils.deleteDirectory(Directory(filePath));
      });
      sharedPreferences.setStringList("miniAppid", []);
    }
    AppUtils.deleteDirectory(Directory(ImgCachePath.instance.path));

    cacheTotal = "0B";
    setState(() {});
  }

  changeLanguage(language) {
    if (language == "zh") {
      // 语言  語言
      S.load(Locale.fromSubtags(languageCode: 'zh', countryCode: 'CN'));
      locale = "zh";
      eventBus.fire(EventType(0));
    } else if(language == "tw"){
      S.load(Locale.fromSubtags(languageCode: 'zh', countryCode: 'TW'));
      locale = "tw";
      eventBus.fire(EventType(1));
    }else {
    S.load(Locale.fromSubtags(languageCode: 'en', countryCode: 'US'));
    locale = "en";
    eventBus.fire(EventType(2));
    }
    SharedPreferences.getInstance().then((value) => {
          value.setString("language", language),
        });
    setState(() {});
    Navigator.of(context).pop();
  }

  logOut() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.setString("token", "");
    sharedPreferences.setString("user", "");
    sharedPreferences.setString("userJson", "");
    sharedPreferences.setString("userId", "");
    sharedPreferences.setString("mobile", "");
    sharedPreferences.setString("nick", "");
    sharedPreferences.setString("account", "");
    sharedPreferences.setString("password", "");


    Navigator.of(context)
        .pushNamedAndRemoveUntil('/router/new_login_page', (route) => false);
    // if (xgFlutterPlugin != null) {
    //   xgFlutterPlugin.stopXg();
    // }
  }

  Widget settingItem(left, right) {
    return Container(
      padding: EdgeInsets.fromLTRB(20, 16, 20, 16),
      decoration: BoxDecoration(
          color: Colors.white,
        ),
      child: Row(
        children: [
          Expanded(
            child: Text(
              left,
              style: TextStyle(
                fontWeight: MyFontWeight.semi_bold,
                fontSize: 15.sp,
                color: Color(0xFF353535),
              ),
            ),
            flex: 1,
          ),
          Text(
            right,
            style: TextStyle(
                fontSize: 13.sp,
                fontWeight: MyFontWeight.regular,
                color: Color(0xFF727272)),
          ),
          SizedBox(
            width: 16.w,
          ),
          Icon(
            Icons.keyboard_arrow_right,
            size: 20,
          ),
        ],
      ),
    );
  }

  Widget settingSingleItem(right) {
    return Container(
      padding: EdgeInsets.fromLTRB(20, 16, 20, 16),
      decoration: BoxDecoration(
        color: Colors.white,
      ),
      child: Row(
        children: [
          Expanded(
            child: Text(
              right,
              style: TextStyle(
                fontSize: 15.sp,
                color: Color(0xFF353535),
                fontWeight: MyFontWeight.semi_bold,
              ),
            ),
          ),
          SizedBox(
            width: 16.w,
          ),
          Icon(
            Icons.keyboard_arrow_right,
            size: 20,
          ),
        ],
      ),
    );
  }
}