import 'package:fis_common/index.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/values/spacings.dart';
import 'package:fis_ui/widgets/layout/button_group.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/views/common/device_live/device_live_list/state.dart';
import 'package:flyinsono/views/common/device_live/device_live_list/widgets/device_info_card.dart';
import 'package:flyinsono/views/desktop/device_live/device_live_list/widgets/management_dialog.dart';
import 'package:flyinsono/views/desktop/device_live/device_live_list/widgets/upload_package_dialog.dart';
import 'package:flyinsono/views/desktop/device_live/device_live_list/widgets/upload_printer_driver_dialog.dart';

import 'controller.dart';

class DeviceLiveListDesktopPage extends FisView<DeviceLiveListDesktopController>
    implements FPage {
  @override
  final String pageName = 'DeviceLiveList';

  @override
  FWidget build(BuildContext context) {
    return FContainer(
      padding: const EdgeInsets.symmetric(
        vertical: FSpacings.M,
        horizontal: FSpacings.XXL,
      ),
      child: FColumn(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          FSizedBox(height: 50, child: _buildSearchBar(context)),
          FDivider(),
          const FSizedBox(height: FSpacings.M),
          FExpanded(child: _buildListPanel()),
        ],
      ),
    );
  }

  FWidget _buildListPanel() {
    return FObx(() {
      final count = controller.state.deviceList.length;
      if (count == 0) {
        // 暂无数据
        return FCenter(
          child: FText(i18nBook.common.noData.t),
        );
      }
      const width = 220;
      const height = 260;
      const aspectRatio = height / width;
      return FScrollbar(
        isAlwaysShown: true,
        controller: controller.listScrollController,
        child: FSingleChildScrollView(
          padding: EdgeInsets.only(right: 25),
          controller: controller.listScrollController,
          child: FWrap(
            spacing: 8.0, // 主轴(水平)方向间距
            runSpacing: 8.0, // 纵轴（垂直）方向间距
            direction: Axis.horizontal,
            alignment: WrapAlignment.start,
            children: List.generate(
              count,
              (index) => FSizedBox(
                width: 220,
                child: DeviceInfoCard(
                  index,
                  aspectRatio: aspectRatio,
                ),
              ),
            ),
          ),
        ),
      );
    });
  }

  FWidget _buildSearchBar(BuildContext context) {
    return FRow(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        const FSizedBox(width: FSpacings.XS),
        FBorderInput(
          focusNode: controller.searchFocusNode,
          hintSize: 16,
          contentSize: 16,
          maxLength: 20,
          borderColor: const Color.fromARGB(255, 187, 180, 180),
          suffixIcon: FMaterial(
            color: Colors.transparent,
            child: FIconButton(
              name: "SearchInputOfDeviceLive",
              onPressed: () {
                controller.reloadList();
              },
              icon: FIcon(Icons.search),
              businessParent: this,
            ),
          ),
          height: 38,
          width: 600,
          hintText: i18nBook.remedical.searchKeyword.t,
          onChanged: (value) {
            controller.state.searchKeyword = value;
          },
        ),
        FIconButton(
          name: "RefreshOfDeviceLive",
          onPressed: () {
            controller.reloadList();
          },
          icon: FIcon(
            Icons.refresh,
            color: Theme.of(context).colorScheme.secondary,
          ),
          businessParent: this,
        ),

        /// 远程控制的权限
        if (controller.state.hasRemoteManager)
          FButtonGroup(
            children: [
              _buildUpdatePackageManagement(),
              _buildPrinterDriverManagement()
            ],
          )
      ],
    );
  }

  // 更新包管理
  FWidget _buildUpdatePackageManagement() {
    return _textButton(i18nBook.remoteControl.updateManagement.t, () {
      router.dialog(
        () => FObx(
          () => ManagementDialog(
            dialogName: i18nBook.remoteControl.updateManagement.t,
            tableColumn: PackageTableColumn.updatePackageList(),
            tableData: controller.state.updatePackageTableContent,
            tableLoading: controller.state.tableLoading,
            onRefresh: (value) => controller.findDevicePatchPagesAsync(value),
            onDelete: (value) {
              controller.deletePatchByCodeAsync(value);
            },
            onUpdate: (DevicePatchDTO value) async {
              controller.state.packageName = value.name!;
              await router.dialog(
                () => UploadPackageDialog(
                  isEdit: true,
                  packageCode: value.code,
                  packageData: value,
                ),
                dismissible: false,
              );
            },
            onUpload: () async {
              await router.dialog(
                () => UploadPackageDialog(),
                dismissible: false,
              );
            },
          ),
        ),
        dismissible: false,
      );
    });
  }

  // 打印机驱动管理
  FWidget _buildPrinterDriverManagement() {
    return _textButton(i18nBook.remoteControl.printerDriverManagement.t, () {
      router.dialog(
        () => FObx(
          () => ManagementDialog(
            dialogName: i18nBook.remoteControl.printerDriverManagement.t,
            tableColumn: PrintMachineTableColumn.printMachineList,
            tableLoading: controller.state.tableLoading,
            tableData: controller.state.printDriverTableDatas,
            onUpload: (FPlatform.isWindows || FPlatform.isMacOS)
                ? () async {
                    await router.dialog(
                      () => UploadPrinterDriverDialog(),
                      dismissible: false,
                    );
                  }
                : null,
            onRefresh: (keyWord) {
              controller.findPrintDriverDatas(keyWord: keyWord);
            },
            onDelete: (value) {
              controller.deletePrintDriverDatas(value.code);
            },
            onSearch: (keyWord) {
              controller.findPrintDriverDatas(keyWord: keyWord);
            },
          ),
        ),
        dismissible: false,
      );
    });
  }

  FWidget _textButton(String textString, Function onPressed) {
    return FElevatedButton(
      onPressed: () => onPressed.call(),
      child: FText(
        textString,
        style: TextStyle(color: Colors.white),
      ),
      style: ButtonStyle(
        padding: MaterialStateProperty.all(EdgeInsets.all(0)),
      ),
      businessParent: this,
      name: textString,
    );
  }
}
