
import 'package:flutter/material.dart';
import 'package:flutter_app_upgrade/flutter_app_upgrade.dart';
import 'package:provider/provider.dart';
import 'package:twong/config/setting.dart';
import 'package:twong/providers/setting.dart';

import 'package:twong/utils/index.dart';
import 'package:twong/config/style.dart';
import 'package:twong/widgets/app_bar.dart';
import 'package:twong/widgets/fsuper.dart';

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

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

    Cache.loadCache().then((res) {
      Provider.of<SettingModel>(context, listen: false).updateCache(res);
    }).catchError((err) {
      Log.e(err);
    });

    FlutterUpgrade.appInfo.then((value){
      Provider.of<SettingModel>(context, listen: false)
          .updateVersion(value.versionName);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: DColors.back,
      appBar: DAppBar("设置"),
      body: SafeArea(
        child: ListView(
          physics: ClampingScrollPhysics(),
          children: [
            _buildMenus(),
            _buildLogout()
          ],
        ),
      ),
    );
  }

  Widget _buildMenus() {
    List<Widget> widgets = List<Widget>();
    for(var item in SettingConfig.data) {
      widgets.add(FSuper(height: 46.px,
        text: item.name,
        onClick: () {
          if(item.route != null) {
            Navigator.pushNamed(context, item.route);
          } else if(item.onTap != null) {
            item.onTap();
          }
        },
        textAlignment: Alignment.centerLeft,
        width: double.infinity,
        padding: EdgeInsets.only(left: 46.px),
        margin: EdgeInsets.only(top: 6.px),
        corner: FCorner.all(6.px),
        backgroundColor: Colors.white,
        child1: Icon(item.icon),
        child1Alignment: Alignment.centerLeft,
        child1Margin: EdgeInsets.only(left: 6.px),
        child2: item.subText == null ? Icon(Icons.chevron_right,
          color: Colors.grey) : item.subText,
        child2Alignment: Alignment.centerRight,
        child2Margin: EdgeInsets.only(right: 12.px),
      ));
    }

    return Container(
        margin: EdgeInsets.only(left: 12.px, right: 12.px),
        child: Column(
        children: widgets
      ),
    );
  }

  Widget _buildLogout () {
    return Container(
      padding: EdgeInsets.all(12.px),
      child: FlatButton(
        color: DColors.Main,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20))),
        onPressed: () {
          Utils.showAlert(context, title: "确定退出登陆？", ok: () {
            Cache.clearAll();
            Navigator.pop(context);
          });
        },
        child: Text('退出登录', style: TextStyle(color: Colors.white)),
      ),
    );
  }
}