import 'package:amos_iot_login_tpl/amos_iot_login_tpl.dart';
import 'package:flutter/material.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:amos_flutter_utils/amos_flutter_utils.dart';
import 'package:amos_iot_login_tpl/const/const.dart';


import '../../consts/color.dart';
import '../../consts/http_config.dart';
import '../../utils/GetConfig.dart';
import '../../utils/regexp_utils.dart';
import '../../widgets/back_button.dart';

import './../../consts/global_config.dart';

/// 服务配置界面
class ServiceConfig extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ServiceConfigContent();
  }
}

class ServiceConfigContent extends StatefulWidget {
  @override
  _ServiceConfigContentState createState() => _ServiceConfigContentState();
}

class _ServiceConfigContentState extends State<ServiceConfigContent> {
  final TextEditingController gatewayCtl = TextEditingController();
  final TextEditingController updateApkCtl = TextEditingController();
  List colorSelect = [
    {'name': '蓝色', 'id': 'blue'},
    {'name': '红色', 'id': 'red'}
  ];
  String theme = '蓝色';
  String themeid = 'blue';

  @override
  void initState() {
    initializeAddress();
    initConfig();
    super.initState();
  }

  Future<void> initConfig() async {
    SharedPreferences.getInstance().then((preferences) {
      setState(() {
        themeid =
            preferences.getString('theme') ?? KColorConstant.DEFAULT_COLOR;
        theme = themeid == 'blue' ? '蓝色' : '红色';
      });
    });
  }

  Future<void> initializeAddress() async {
    final gatewayUrl = await APIUrlManager.getGatewayUrl();
    final updateApkUrl = await APIUrlManager.getUpdateApkUrl();

    gatewayCtl.text = gatewayUrl;
    updateApkCtl.text = updateApkUrl;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text(
            '服务设置',
            style: TextStyle(color: Colors.black),
          ),
          backgroundColor: Colors.white,
          centerTitle: true,
          leading: LeadingButton(
            theme: themeid,
          ),
        ),
        body: Stack(
          children: <Widget>[
            GestureDetector(onTap: () {}),
            Column(
              children: <Widget>[
                buildGatewayContent(context),
                const SizedBox(
                  height: 20,
                ),
                buildUpdateContent(context),
                SizedBox(
                  height: 20.px,
                ),
                colorButton(context),
                SizedBox(
                  height: 20.px,
                ),
                buildButton(context)
              ],
            ),
          ],
        ));
  }

  Widget buildGatewayContent(context) {
    return Padding(
      padding: EdgeInsets.all(10.px),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            '网关地址:',
            style: Theme.of(context).textTheme.headline3,
          ),
          TextField(
            controller: gatewayCtl,
          ),
        ],
      ),
    );
  }

  Widget buildUpdateContent(context) {
    return Padding(
      padding: EdgeInsets.all(10.px),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            '升级地址:',
            style: Theme.of(context).textTheme.headline3,
          ),
          TextField(
            controller: updateApkCtl,
          ),
        ],
      ),
    );
  }

  Widget colorButton(context) {
    return Padding(
        padding: EdgeInsets.all(10.px),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              '主题颜色:',
              style: Theme.of(context).textTheme.headline3,
            ),
            GestureDetector(
              child: Container(
                height: 40,
                width: MediaQuery.of(context).size.width - 20,
                padding: const EdgeInsets.only(bottom: 5),
                margin: const EdgeInsets.only(top: 10),
                //color: GetConfig.getColor(this.themeid),
                decoration: BoxDecoration(
                  color: Colors.grey[100],
                ),
                child: Stack(
                  children: <Widget>[
                    Container(
                        alignment: Alignment.centerLeft,
                        padding: const EdgeInsets.only(left: 5),
                        child: Text(
                          theme,
                          style: Theme.of(context).textTheme.headline2,
                        ),
                        height: 60,
                        width: MediaQuery.of(context).size.width - 20,
                        color: GetConfig.getColor(themeid)),
                    Container(
                      alignment: Alignment.centerRight,
                      child: const Icon(
                        Icons.keyboard_arrow_down,
                        size: 14,
                        color: Colors.white,
                      ),
                    )
                  ],
                ),
              ),
              onTap: () {
                showDialog<void>(
                  context: context,
                  builder: (BuildContext context) {
                    return SimpleDialog(
                        children: colorSelect.map((f) {
                      return Column(
                        children: <Widget>[
                          SimpleDialogOption(
                            child: Text(f['name']),
                            //color: GetConfig.getColor(f['id']),),
                            onPressed: () {
                              Navigator.of(context).pop();
                              setState(() {
                                theme = f['name'];
                                themeid = f['id'];
                              });
                            },
                          ),
                          const Divider(
                            height: 1,
                          )
                        ],
                      );
                    }).toList());
                  },
                );
              },
            ),
          ],
        ));
  }

  Widget buildButton(context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Container(
          width: MediaQuery.of(context).size.width / 2 - 30,
          height: 50.px,
          child: RaisedButton(
            child: Text('恢复默认', style: TextStyle(fontSize: 18.px)),
            onPressed: reset,
          ),
        ),
        SizedBox(
          width: 20.px,
        ),
        Container(
          width: MediaQuery.of(context).size.width / 2 - 30,
          height: 50.px,
          child: RaisedButton(
            color: GetConfig.getColor(themeid),
            child: Text(
              '确定',
              style: TextStyle(color: Colors.white, fontSize: 18.px),
            ),
            onPressed: () => confirm(context),
          ),
        )
      ],
    );
  }

  // 恢复默认
  void reset() {
    gatewayCtl.text = LoginGlobalConfig.gatewayUrl;
    updateApkCtl.text = LoginGlobalConfig.updateApkUrl;
    setState(() {
      theme = '蓝色';
      themeid = 'blue';
    });
  }

  // 确定
  void confirm(context) {
    final str1 = gatewayCtl.text;
    final str2 = updateApkCtl.text;

    // 1.判断是否为空
    if (str1.isEmpty || str2.isEmpty) {
      shortMessage('地址不能为空');
      return;
    }

    // 2.检验是否合法服务器地址
    if (!RegExpUtils.isValidUrl(str1) || !RegExpUtils.isValidUrl(str2)) {
      shortMessage('请输入合法的地址');
      return;
    }

    // 3.清除服务器内存缓存
    HttpConfig.clearMemoryCacheUrl();
    saveServerUrl();
    // 4.更新本地缓存
    APIUrlManager.saveGatewayUrl(str1);
    APIUrlManager.saveUpdateApkUrl(str2);

    Navigator.of(context).pop();
  }

  Future<void> saveServerUrl() async {
    await SharedPreferences.getInstance().then((pref) {

      pref.setString(GlobalConst.gatewayUrl, gatewayCtl.text);
      pref.setString(GlobalConst.updateUrl, updateApkCtl.text);
      pref.setString('theme', themeid);
    });
  }
}
