import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sport/provider/bluetooth.dart';
import 'package:sport/router/navigator_util.dart';
import 'package:sport/services/Converter.dart';
import 'package:sport/widgets/appbar.dart';
import 'package:sport/widgets/box.dart';
import 'package:sport/widgets/dialog/search_device.dart';
import 'package:sport/widgets/image.dart';
import 'package:sport/widgets/loading.dart';

class DeviceInfoPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _PageState();
}

class _PageState extends State<DeviceInfoPage> {
  var labelPadding = const EdgeInsets.symmetric(horizontal: 12.0, vertical: 10.0);
  var contentPadding = const EdgeInsets.symmetric(horizontal: 0.0);

  bool _vibrate = true;

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

  void loadSetting() {
    SharedPreferences.getInstance().then((value) {
      _vibrate = value.getBool("vibrate") ?? true;
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: CustomScrollView(
      slivers: <Widget>[
        buildSliverAppBar(context, "设备详情", backgroundColor: Theme.of(context).scaffoldBackgroundColor),
        SliverToBoxAdapter(
            child: Selector<Bluetooth, BluetoothDevice>(
                selector: (_, bluetooth) => bluetooth.device,
                builder: (_, device, ___) {
                  return device == null ? RequestLoadingWidget() : _infoWidget(context, device);
                })),
      ],
    ));
  }

  Widget _infoWidget(BuildContext context, BluetoothDevice device) {
    return Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
      Padding(
        padding: labelPadding,
        child: Text("设置", style: Theme.of(context).textTheme.bodyText2),
      ),
      BoxWidget(
          paddingAll: false,
          body: ListView(
              padding: EdgeInsets.all(0),
              physics: NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              children: ListTile.divideTiles(context: context, tiles: [
                ListTile(
                  title: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text("当前设备"),
                      Text(
                        "${device.name}",
                        style: Theme.of(context).textTheme.bodyText2,
                      )
                    ],
                  ),
                  contentPadding: contentPadding,
                  onTap: () {},
                ),
                ListTile(
                  title: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text("设备状态"),
                      StreamBuilder<BluetoothDeviceState>(
                          stream: device.state,
                          initialData: BluetoothDeviceState.connecting,
                          builder: (c, snapshot) => Text(
                                (snapshot.data == BluetoothDeviceState.connected) ? "已连接" : "未连接",
                                style: Theme.of(context).textTheme.bodyText2.copyWith(color: Theme.of(context).accentColor),
                              ))
                    ],
                  ),
                  contentPadding: contentPadding,
                ),
                ListTile(
                  title: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text("更换设备"),
                    ],
                  ),
                  contentPadding: contentPadding,
                  trailing: arrowRight5(),
                  onTap: () {
                    showDialog(context: context, child: SearchDeviceDialog());
                  },
                ),
                ListTile(
                  title: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text("设备测试"),
                    ],
                  ),
                  contentPadding: contentPadding,
                  trailing: arrowRight5(),
                  onTap: () {
                    var device = Provider.of<Bluetooth>(context, listen: false)?.device;
                    if (device != null) {
                      NavigatorUtil.goPage(
                          context,
                          (context) => DeviceScreen(
                                device: device,
                              ));
                    }
                  },
                ),
              ]).toList())),
      BoxWidget(
          paddingAll: false,
          body: ListView(
              padding: EdgeInsets.all(0),
              physics: NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              children: ListTile.divideTiles(context: context, tiles: [
                ListTile(
                  title: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text("震动反馈开关"),
                      Switch(
                        value: _vibrate,
                        onChanged: (bool value) {
                          SharedPreferences.getInstance().then((prefs) {
                            _vibrate = value;
                            prefs.setBool("vibrate", value);
                            setState(() {});
                          });
                        },
                      )
                    ],
                  ),
                  contentPadding: contentPadding,
                ),
              ]).toList())),
      Padding(
        padding: labelPadding,
        child: Text("设备数据", style: Theme.of(context).textTheme.bodyText2),
      ),
      BoxWidget(
          paddingAll: false,
          body: ValueListenableBuilder(
              valueListenable: Provider.of<Bluetooth>(context, listen: false).dataNotifier,
              builder: (_, data, ___) => ListView(
                  padding: EdgeInsets.all(0),
                  physics: NeverScrollableScrollPhysics(),
                  shrinkWrap: true,
                  children: ListTile.divideTiles(context: context, tiles: [
                    ListTile(
                      title: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Text("设备电量"),
                          Text(
                            // "${min(Converter.toInt(data['0_electricity']),Converter.toInt(data['1_electricity']))}%",
                            "${Converter.toInt(data['0_electricity'])}%\t\t/\t\t${Converter.toInt(data['1_electricity'])}%",
                            style: Theme.of(context).textTheme.bodyText2,
                          )
                        ],
                      ),
                      contentPadding: contentPadding,
                      onTap: () {
                        Provider.of<Bluetooth>(context, listen: false).queryDeviceData();
                      },
                    ),
                    ListTile(
                      title: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Text("鞋内温度"),
                          Text(
                            "${data['0_temperature'] ?? 0}℃\t\t/\t\t${data['1_temperature'] ?? 0}℃",
                            style: Theme.of(context).textTheme.bodyText2,
                          )
                        ],
                      ),
                      contentPadding: contentPadding,
                    ),
                    ListTile(
                      title: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Text("压力指数"),
                          Text(
                            "${data['0_pressure'] ?? 0}\t\t/\t\t${data['1_pressure'] ?? 0}",
                            style: Theme.of(context).textTheme.bodyText2,
                          )
                        ],
                      ),
                      contentPadding: contentPadding,
                    ),
                  ]).toList()))),
      Padding(
        padding: labelPadding,
        child: Text("基本信息", style: Theme.of(context).textTheme.bodyText2),
      ),
      BoxWidget(
          paddingAll: false,
          body: ValueListenableBuilder(
              valueListenable: Provider.of<Bluetooth>(context, listen: false).infoNotifier,
              builder: (_, data, ___) => ListView(
                  padding: EdgeInsets.all(0),
                  physics: NeverScrollableScrollPhysics(),
                  shrinkWrap: true,
                  children: ListTile.divideTiles(context: context, tiles: [
                    ListTile(
                      title: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Text("设备型号"),
                          Text(
                            "${data['name']?.toString()?.trim() ?? 'SHOES'}",
                            style: Theme.of(context).textTheme.bodyText2,
                          )
                        ],
                      ),
                      contentPadding: contentPadding,
                      onTap: () {
                        Provider.of<Bluetooth>(context, listen: false).queryDeviceInfo();
                      },
                    ),
                    // ListTile(
                    //   title: Row(
                    //     mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    //     children: <Widget>[
                    //       Text("鞋码"),
                    //       Text(
                    //         "42码",
                    //         style: Theme.of(context).textTheme.bodyText2,
                    //       )
                    //     ],
                    //   ),
                    //   contentPadding: contentPadding,
                    // ),
                    ListTile(
                      title: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Text("软件版本"),
                          Text(
                            "V${data['softwareVer'] ?? 0}",
                            style: Theme.of(context).textTheme.bodyText2,
                          )
                        ],
                      ),
                      contentPadding: contentPadding,
                    ),
                    ListTile(
                      title: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Text("硬件版本"),
                          Text(
                            "V${data['hardwareVer'] ?? 0}",
                            style: Theme.of(context).textTheme.bodyText2,
                          )
                        ],
                      ),
                      contentPadding: contentPadding,
                    ),
                    ListTile(
                      title: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Text("蓝牙地址"),
                          Text(
                            "${Provider.of<Bluetooth>(context, listen: false)?.device?.id?.id ?? ""}",
                            style: Theme.of(context).textTheme.bodyText2,
                          )
                        ],
                      ),
                      contentPadding: contentPadding,
                    ),
                  ]).toList()))),
    ]);
  }
}
