import 'package:fis_i18n/i18n.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/usual/tab_button.dart';
import 'package:fis_ui/usual/tab_button_group.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/desktop/names.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/pages/user/user_device/widgets/ai_application.dart';
import 'package:flyinsono/pages/user/user_device/widgets/correlation_user.dart';
import 'package:flyinsono/pages/user/user_device/widgets/mobile_device_card.dart';
import 'package:flyinsono/pages/user/user_device/widgets/terminal_card.dart';
import 'package:flyinsono/pages/user/user_device/widgets/terminals.dart';
import 'package:flyinsono/pages/user/widgets/search_input.dart';
import 'package:get/get.dart';

import 'index.dart';

///用户设备
class UserDevicePage extends FisView<DeviceController> implements FPage {
  @override
  final String pageName;
  const UserDevicePage({this.pageName = 'UserDevicePage', Key? key})
      : super(key: key);
  @override
  FWidget build(BuildContext context) {
    return context.fResponsiveVoid(
      mobile: () => _MobileLayout(this),
      desktop: () => _DesktopLayout(this),
    );
  }
}

class _BuildTabs extends FisView<DeviceController> {
  final int index;

  ///父级节点
  final FPage businessParent;

  _BuildTabs(this.businessParent, this.index, {Key? key}) : super(key: key);

  @override
  FWidget build(BuildContext context) {
    return FContainer(
      child: FFlex(
        direction: Axis.horizontal,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          FExpanded(
            child: FContainer(
                height: 40,
                alignment: Alignment.center,
                child: FTabButtonGroup([
                  FTabButton(
                    name: "deviceDetails",
                    businessParent: businessParent,
                    tabTitle: i18nBook.user.deviceDetails.t,
                    index: 0,
                    activeIndex: controller.state.selectIndex,
                    onCallbackTap: () {
                      controller.state.selectIndex = 0;
                    },

                    /// TODO:[Gavin] 多语言-UI-整合
                    width: i18nBook.isCurrentChinese ? 100 : 200,
                  ),
                  FObx(() {
                    if (controller.state.isOrgDevice) {
                      return FRow(
                        children: [
                          FTabButton(
                            name: "userRelated",
                            businessParent: businessParent,
                            tabTitle: i18nBook.user.userRelated.t,
                            index: 1,
                            padding: EdgeInsets.symmetric(
                              horizontal: 0,
                              vertical: 8,
                            ),
                            activeIndex: controller.state.selectIndex,
                            onCallbackTap: () {
                              controller.state.selectIndex = 1;
                            },

                            /// TODO:[Gavin] 多语言-UI-整合
                            width: i18nBook.isCurrentChinese ? 100 : 200,
                          ),
                          FTabButton(
                            name: "aiApplication",
                            businessParent: businessParent,
                            tabTitle: i18nBook.user.aiApplication.t,
                            index: 2,
                            activeIndex: controller.state.selectIndex,
                            padding: EdgeInsets.symmetric(
                              horizontal: 0,
                              vertical: 8,
                            ),
                            onCallbackTap: () {
                              controller.state.selectIndex = 2;
                            },

                            /// TODO:[Gavin] 多语言-UI-整合
                            width: i18nBook.isCurrentChinese ? 100 : 200,
                          ),
                        ],
                      );
                    } else {
                      return FSizedBox();
                    }
                  }),
                ])),
          ),
        ],
      ),
    );
  }
}

///设备列表
class _BuildTerminals extends FisView<DeviceController> {
  @override
  FWidget build(BuildContext context) {
    final itemCount = controller.state.terminals.length;
    return FContainer(
      child: FListView.builder(
        shrinkWrap: true,
        itemCount: itemCount,
        controller: controller.terminalController,
        itemBuilder: (context, index) {
          return FObx(() {
            final terminal = controller.state.terminals[index];
            return SwipeCard(
              index: index,
              isActive: controller.state.selectTerminalCardIndex == index,
              onTap: () {
                controller.changeCard(index, terminal);
              },
              child: TerminalCard(
                controller.state.selectTerminalCardIndex == index,
                terminal,
              ),
            );
          });
        },
      ),
    );
  }
}

class _DesktopLayout extends FisView<DeviceController> implements FWidget {
  ///父级节点
  final FPage businessParent;

  _DesktopLayout(this.businessParent);
  @override
  FWidget build(BuildContext context) {
    return FContainer(
      color: FTheme.ins.colorScheme.background,
      child: FRow(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          FContainer(
            decoration: BoxDecoration(
              color: Colors.white,
            ),
            width: 400,
            child: FColumn(
              children: [
                SearchInput(
                  businessParent: businessParent,
                  onChanged: (value) {
                    controller.state.queryString = value;
                  },
                  serchOnPressed: () {
                    controller.searchTerminal();
                  },
                  focusNode: controller.searchFocusNode,
                  hintText: i18nBook.user.deviceSearch.t,
                  controller: controller.searchController,
                ),
                FContainer(
                  margin: EdgeInsets.only(
                    left: 10,
                    right: 10,
                  ),
                  child: FContainer(
                    padding: EdgeInsets.symmetric(
                      horizontal: 20,
                    ),
                    child: _buildDeviceOperates(context),
                  ),
                ),
                const FSizedBox(height: 7),
                FPadding(
                  padding: EdgeInsets.symmetric(
                    horizontal: 20,
                  ),
                  child: const FDivider(height: 1, color: Colors.grey),
                ),
                const FSizedBox(
                  height: 10,
                ),
                FObx(
                  () => controller.state.terminals.length == 0
                      ? FContainer(
                          margin: EdgeInsets.only(top: 80),
                          child: FColumn(
                            children: [
                              FCenter(
                                child: FImage.asset(
                                  "assets/images/no_data.png",
                                  width: 300,
                                  height: 300,
                                  fit: BoxFit.cover,
                                ),
                              ),
                              FText(i18nBook.common.noneDataTip.t),
                            ],
                          ),
                        )
                      : FExpanded(
                          child: _BuildTerminals(),
                        ),
                ),
              ],
            ),
          ),
          _buildTermianlContentView(),
        ],
      ),
    );
  }

  ///设备所需操作按钮
  FWidget _buildDeviceOperates(BuildContext context) {
    return FRow(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        _buildTextButton(
          Icons.filter_alt_outlined,
          i18nBook.common.filter.t,
          () {
            controller.findTerminals();
          },
        ),
        _buildTextButton(
          Icons.add_box_outlined,
          i18nBook.common.add.t,
          () {
            controller.addTerminalDevice();
          },
        ),
        _buildTextButton(
          Icons.refresh,
          i18nBook.common.refresh.t,
          () {
            //controller.refersh();
            controller.searchTerminal();
          },
        ),
      ],
    );
  }

  ///设备内容展示
  FWidget _buildTermianlContentView() {
    return FExpanded(
      child: FContainer(
        child: FColumn(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const FSizedBox(height: 10),
            FContainer(
              margin: EdgeInsets.only(left: 15, right: 15),
              child: FObx(() =>
                  _BuildTabs(businessParent, controller.state.selectIndex)),
            ),
            FExpanded(
              child: FContainer(
                margin: EdgeInsets.only(left: 15, right: 15, bottom: 15),
                child: FContainer(
                  child: FScaffold(
                    backgroundColor: Colors.white,
                    body: FDefaultTabController(
                      length: 1,
                      child: FObx(
                        () {
                          return controller.state.selectIndex == 0
                              // 设备详情
                              ? TerminalInfosPage()
                              // 关联用户
                              : controller.state.selectIndex == 1
                                  ? CorrelationUser()
                                  : AiApplication();
                        },
                      ),
                    ),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  FWidget _buildTextButton(IconData icons, String text, Function onTap) {
    return FGestureDetector(
      name: "$text",
      businessParent: this.businessParent,
      onTap: () async {
        onTap.call();
      },
      child: FMouseRegion(
        cursor: SystemMouseCursors.click,
        child: FCenter(
          child: FRow(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              FIcon(
                icons,
                size: 24,
                color: FTheme.ins.colorScheme.primary,
              ),
              FText(
                text,
                style: TextStyle(
                  height: 1,
                  fontSize: 16,
                  color: Colors.black,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _MobileLayout extends FisView<DeviceController> implements FWidget {
  ///父级节点
  final FPage businessParent;
  final ScrollController _scrollController = ScrollController();
  _MobileLayout(this.businessParent);

  @override
  FWidget build(BuildContext context) {
    bool isOrgdevice = router.getParams()?['isOrgdevice'] == 'true';
    return FSafeArea(
      top: false,
      child: FScaffold(
        appBar: FAppBar.simple(
            title: isOrgdevice
                ? i18nBook.homePage.organizationDevices.t
                : i18nBook.user.myDevices.t,
            onBackClicked: () => Get.back(),
            actions: [
              FElevatedButton(
                onPressed: () async {
                  await router.to(RouteNames.Org.AddDevice);
                  _dispose();
                },
                style: ButtonStyle(
                    elevation: MaterialStateProperty.all<double>(0)),
                businessParent: businessParent,
                name: 'add',
                child: FText(
                  i18nBook.common.add.t,
                  style: TextStyle(color: Colors.white),
                ),
              )
            ]),
        backgroundColor: Color.fromRGBO(239, 239, 239, 1),
        body: _buildDevicesContentView(isOrgdevice, context),
      ),
    );
  }

  Future<void> onScanData(String code) async {
    await router.replace(
      RouteNames.Org.AddDevice,
      parameters: {
        'scanData': code,
      },
    );
  }

  ///设备列表
  FWidget _buildDevicesContentView(bool isOrgdevice, BuildContext context) {
    return FScaffold(
      appBar: FAppBar(
        leading: FSizedBox(width: 0),
        leadingWidth: 0,
        centerTitle: true,
        elevation: 0,
        backgroundColor: Colors.white,
        title: FRow(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            FBorderInput(
              focusNode: controller.searchFocusNode,
              controller: controller.searchController,
              fillColor: Colors.white,
              hintSize: 14,
              contentSize: 14,
              maxLength: 50,
              borderColor: Color.fromARGB(255, 185, 184, 184),
              suffixIcon: FIconButton(
                businessParent: businessParent,
                name: "searchTerminal",
                onPressed: () {
                  controller.searchTerminal();
                },
                icon: FIcon(
                  Icons.search,
                  size: 20,
                ),
              ),
              height: 36,
              hintText: i18nBook.user.deviceSearch.t,
              onChanged: (value) {
                controller.state.queryString = value;
              },
            ),
          ],
        ),
      ),
      body: FColumn(
        children: [
          FExpanded(
            child: FObx(
              () => FAlwaysScrollListView(
                scrollController: _scrollController,
                child: QuickFWidget(ScrollConfiguration(
                  behavior: ScrollConfiguration.of(context)
                      .copyWith(scrollbars: false),
                  child: FListView.builder(
                    shrinkWrap: true,
                    controller: _scrollController,
                    itemCount: controller.state.terminals.length,
                    itemBuilder: (context, index) {
                      return FContainer(
                        child: MobileDeviceCard(
                          businessParent,
                          deviceExtendInfoDTO:
                              controller.state.terminals[index],
                          isOrgdevice: isOrgdevice,
                          index: index,
                        ),
                      );
                    },
                  ),
                )),
              ),
            ),
          ),
          FSizedBox(
            height: 15,
          ),
        ],
      ),
    );
  }

  void _dispose() {
    controller.nameEditingController.text = '';
    controller.shortCodeController.text = '';
    controller.deviceTypeController.text = '';
    controller.deviceModelController.text = '';
    controller.deviceNameEditingController.text = '';
    controller.state.deviceInfo.isNewDevice = false;
    // controller.orgNameController.text = '';
    controller.textEditingController.text = '';
  }
}
