import 'package:fis_common/event/event_type.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/values/paddings.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/router/index.dart';
import 'package:fis_lib_business_components/index.dart';
import 'package:flyinsono/views/desktop/device_live/device_live_list/controller.dart';
import 'package:get/get.dart';

// ignore: must_be_immutable
/// 这边是设计的公共的管理页面
class ManagementDialog<T> extends FStatefulWidget implements FPage {
  ManagementDialog({
    required this.dialogName,
    required this.tableColumn,
    required this.tableData,
    this.onRefresh,
    this.onUpdate,
    this.onSearch,
    this.onDelete,
    this.onUpload,
    this.onMakeSure,
    this.tableLoading = false,
    this.isSearch = true,
  });

  /// 弹框名称
  final String dialogName;

  /// 表头
  final List<FTableColumn<T>> tableColumn;

  /// 表格loadding
  final bool? tableLoading;

  /// 表格数据
  final List<T> tableData;

  /// 刷新回调
  final ValueCallback? onRefresh;

  /// 更新回调
  final ValueCallback<T>? onUpdate;

  /// 查找回调
  final ValueCallback? onSearch;

  /// 删除回调
  final ValueCallback? onDelete;

  /// 上传回调
  final VoidCallback? onUpload;

  /// 确定回调
  final ValueCallback<T>? onMakeSure;

  /// 是否可以搜索
  final bool? isSearch;

  @override
  String get pageName => dialogName;
  @override
  FState<ManagementDialog<T>> createState() => _ManagementDialogState<T>();
}

class _ManagementDialogState<T> extends FState<ManagementDialog<T>> {
  late String keyWord = '';
  late T? selectedData = null;

  /// 通知是否点击表格
  final FEventHandler<T?> onSelectTable = FEventHandler<T?>();
  late final TextEditingController _textEditingController =
      TextEditingController(text: keyWord);
  final deviceListcontroller = Get.find<DeviceLiveListDesktopController>();

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

  @override
  void dispose() {
    _textEditingController.dispose();
    super.dispose();
  }

  @override
  FWidget build(BuildContext context) {
    return FSimpleDialog(
      contentPadding: EdgeInsets.symmetric(vertical: 25, horizontal: 25),
      title: FText(
        widget.dialogName,
        style: TextStyle(
          color: Colors.white,
          fontSize: 18,
        ),
      ),
      onClose: () {
        router.back();
      },
      children: [
        FContainer(
          width: 850,
          height: 700,
          child: _buildManagementPage(),
        ),
      ],
      okString: i18nBook.common.confirm.t,
      cancelString: i18nBook.common.cancel.t,
      isDefault: false,
      bottomButton: BottomButtonGroup(
        dialogName: widget.dialogName,
        onSelectTable: onSelectTable,
        onDelete: widget.onDelete != null
            ? (value) => widget.onDelete?.call(value)
            : null,
        onMakeSure: widget.onMakeSure != null
            ? (value) => widget.onMakeSure?.call(value)
            : null,
        onUpdate: widget.onUpdate != null
            ? (value) => widget.onUpdate?.call(value)
            : null,
      ),
    );
  }

  FWidget _buildManagementPage() {
    selectedData = null;
    this.onSelectTable.emit(this, selectedData);
    return FColumn(
      children: [
        if (widget.isSearch!) _buildManagementInputAndButton(),
        FExpanded(
          child: _buildTableContent(),
        ),
      ],
    );
  }

  FWidget _buildManagementInputAndButton() {
    return FRow(
      children: [
        FExpanded(
          flex: 2,
          child: FSearchInput(
            businessParent: this.widget,
            hintText: i18nBook.common.search.t,
            onChanged: (value) {
              keyWord = value;
              deviceListcontroller.state.firstDialogSearchKeyword = keyWord;
            },
            controller: _textEditingController,
            serchOnPressed: () {
              widget.onRefresh?.call(keyWord);
            },
          ),
        ),
        FButtonGroup(
          buttonPadding: FPaddings.SECONDARY_BUTTON,
          spacing: FSpacings.L,
          children: [
            _buildCommonButton(
              i18nBook.common.refresh.t,
              _onRefresh,
            ),
            if (widget.onUpload != null)
              _buildCommonButton(
                  i18nBook.laboratory.upload.t, () => widget.onUpload?.call()),
          ],
        ),
        FSizedBox(
          width: 20,
        ),
      ],
    );
  }

  ///表格内容
  FWidget _buildTableContent() {
    return FTable<T>(
      autoHeight: false,
      noDataHintText: i18nBook.common.noData.t,
      columns: widget.tableColumn,
      source: widget.tableData,
      loading: widget.tableLoading!,
      onRowTap: (index) {
        selectedData = widget.tableData[index];
        this.onSelectTable.emit(this, selectedData);
      },
    );
  }

  /// 刷新
  void _onRefresh() {
    selectedData = null;
    setState(() {
      keyWord = '';
      _textEditingController.text = keyWord;
    });
    widget.onRefresh?.call(keyWord);
    this.onSelectTable.emit(this, selectedData);
  }

  FWidget _buildCommonButton(String buttonName, VoidCallback onPressed) {
    return FElevatedButton(
      child: FText(buttonName),
      onPressed: () {
        onPressed.call();
      },
      businessParent: this.widget,
      name: buttonName,
      style: ElevatedButton.styleFrom(
        elevation: 0,
        padding: EdgeInsets.symmetric(
          vertical: 15,
          horizontal: 25,
        ),
      ),
    );
  }
}

class BottomButtonGroup<T> extends FStatefulWidget implements FPage {
  const BottomButtonGroup({
    super.key,
    required this.onSelectTable,
    this.dialogName,
    this.onDelete,
    this.onMakeSure,
    this.onUpdate,
  });

  @override
  String get pageName => dialogName ?? '';

  final FEventHandler<T?> onSelectTable;

  /// 弹框名称
  final String? dialogName;

  /// 删除
  final ValueCallback? onDelete;

  /// 确定
  final ValueCallback? onMakeSure;

  /// 编辑
  final ValueCallback? onUpdate;

  @override
  FState<BottomButtonGroup> createState() => _BottomButtonGroupState();
}

class _BottomButtonGroupState<T> extends FState<BottomButtonGroup> {
  T? selectedData = null;
  @override
  void initState() {
    super.initState();

    widget.onSelectTable.addListener(_addListenerOnSelectTable);
  }

  @override
  FWidget build(BuildContext context) {
    if (selectedData != null)
      return FRow(
        mainAxisAlignment: MainAxisAlignment.center,
        mainAxisSize: MainAxisSize.max,
        children: [
          if (widget.onUpdate != null)
            _buildTextButton(i18nBook.common.edit.t, () {
              widget.onUpdate?.call(selectedData);
            }),
          if (widget.onDelete != null)
            _buildTextButton(i18nBook.common.delete.t, () {
              widget.onDelete?.call(selectedData);
              selectedData = null;
            }),
          if (widget.onMakeSure != null)
            _buildTextButton(i18nBook.common.confirm.t, () {
              widget.onMakeSure?.call(selectedData);
            }),
        ],
      );
    else
      return FContainer();
  }

  void _addListenerOnSelectTable(sender, e) {
    selectedData = e;
    setState(() {});
  }

  /// 构建按钮
  FWidget _buildTextButton(String textString, Function onPressed) {
    return FContainer(
      width: 110,
      margin: const EdgeInsets.only(right: 15),
      child: FElevatedButton(
        onPressed: () => onPressed.call(),
        style: ButtonStyle(
          padding: MaterialStateProperty.all(
            const EdgeInsets.symmetric(
              vertical: 15,
            ),
          ),
        ),
        businessParent: this.widget,
        name: textString,
        child: FCenter(
          child: FText(
            textString,
            style: const TextStyle(color: Colors.white),
          ),
        ),
      ),
    );
  }
}
