
import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:twongCustomer/store/models/serverModel.dart';
import 'package:twongCustomer/utils/http.dart';

import '../utils/cache.dart';
import '../models/index.dart';
import '../routes/utils.dart';
import '../utils/socket.dart';
import '../widgets/dialog.dart';

class SettingPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => SettingPageState();
}

class SettingPageState extends State<SettingPage> with WidgetsBindingObserver {
  UserInfo info;
  String serverType;
  bool _isExpanded = false;
  TextEditingController _inputController = TextEditingController();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);

    _isExpanded = info == null;

    var url = Cache.get("server");
    info = AppData.get("info");

    var type = Cache.get("server_type");
    serverType = type == null ? "http://" : type;

    _inputController.text = url == null ? "" : url;
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      setState(() {


        if(MediaQuery.of(context).viewInsets.bottom==0){
          //关闭键盘
          print("show");
        }else{
          //显示键盘
          print("hide");
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('设置'),
        ),
        body: info == null ? _buildHomeSetting() : _buildMainSetting(),
        );
  }

  Widget _buildHomeSetting () {
    return ListView(
        physics: new NeverScrollableScrollPhysics(),
        children: [
          _buildServerEditor(),
          new Divider(),
          ListTile(
            title: Text('退出'),
            leading: Icon(Icons.exit_to_app, color: Colors.red),
            onTap: this._exit,
          ),
          new Divider(),
        ]
    );
  }

  Widget _buildMainSetting() {
    return ListView(
      physics: new NeverScrollableScrollPhysics(),
      children: <Widget>[
        new Divider(),
        ListTile(
          title: Text('当前用户:\t\t' + info.name),
          leading: Icon(Icons.account_circle, color: Colors.deepOrange),
        ),
        // 分割线
        new Divider(),
        ListTile(
          title: Text('退出登陆'),
          leading: Icon(Icons.logout, color: Colors.red),
          onTap: this._logout,
        ),
        new Divider(),
      ],
    );
  }

  Widget _buildServerEditor() {
    return SingleChildScrollView(
      child: ExpansionPanelList(
        children: <ExpansionPanel>[
          ExpansionPanel(
            headerBuilder: (context, isExpanded) {
              return ListTile(
                title: Text('服务器设置'),
                leading:
                Icon(Icons.language, color: Colors.lightBlue),
              );
            },
            body: Padding(
              padding: EdgeInsets.fromLTRB(15, 0, 15, 15),
              child: ListBody(
                children: <Widget>[
                  Flex(
                    direction: Axis.horizontal,
                    children: [
                      DropdownButton(
                        items: [
                          DropdownMenuItem(child: Text("HTTP"), value: "http://",),
                          DropdownMenuItem(child: Text("HTTPS"), value: "https://",)
                        ],
                        hint: Text(serverType == "http://" ? "HTTP" : "HTTPS"),
                        onChanged: (item) {
                          setState(() {
                            serverType = item;
                          });
                        },
                        isExpanded: false,
                      ),
                      Expanded(child: Container(
                        padding: EdgeInsets.only(left: 10,),
                        margin: EdgeInsets.only(left: 10, bottom: 14),
                        decoration: BoxDecoration(
                            border: Border(bottom: BorderSide(
                                width: 1.0,
                                style: BorderStyle.solid,
                                color: Color.fromRGBO(0, 0, 0, 0.1)))),
                        child: TextField(
                          controller: _inputController,
                          decoration: InputDecoration(
                            hintText: '请输入域名或IP地址',
                            border: InputBorder.none,
                          ),
                        ),
                      ))
                    ]
                  ),
                  RaisedButton(
                    color: Colors.blue,
                    textColor: Colors.white,
                    child: Text('保存设置'),
                    onPressed: () => _saveServer(),
                  ),
                ],
              ),
            ),
            isExpanded: _isExpanded,
            canTapOnHeader: true,
          ),
        ],
        expansionCallback: (panelIndex, isExpanded) {
          setState(() {
            _isExpanded = !isExpanded;
          });
        },
        animationDuration: kThemeAnimationDuration,
      ),
    );
  }

  void _saveServer () {
    var url = _inputController.text;
    print("set server: " + serverType + url);
    Cache.set("server", url);
    Cache.set("server_type", serverType);
    // Provider.of<ServerModel>(context,listen: false).update(serverType, url);
    // Http.updateConf(type: serverType, host: url);
    Fluttertoast.showToast(msg: "保存成功！");
    Navigator.pop(context);
  }

  void _exit() async {
    showDialog(
        context: context,
        builder: (context) {
          return CustomDialog(
              content: '确认要退出天旺客服么？',
              callback: (res) {
                SystemChannels.platform.invokeMethod('SystemNavigator.pop');
              }
          );
        }
    );
  }

  void _logout () {
    showDialog(
        context: context,
        builder: (context) {
          return CustomDialog(
              content: '确认要退出当前登陆的账户么？',
              callback: (res) {
                Cache.del("token");
                Cache.del("autoLogin");
                AppData.set("info", null);
                Socket.close();

                RouterUtils.toLogin(context);
              }
          );
        }
    );
  }
}
