import 'package:fis_common/index.dart';
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:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/pages/upload/image_upload_card.dart';
import 'package:flyinsono/pages/user/user_device/widgets/add_or_edit_device.dart';
import 'package:flyinsono/pages/user/user_device/widgets/select_sheet.dart';
import 'package:flyinsono/pages/user/user_device/index.dart';
import 'package:get/get.dart';

///添加or编辑超声机
class AddorEditTerminalPage extends FStatefulWidget implements FPage {
  final bool isEdit;

  @override
  final String pageName;

  AddorEditTerminalPage({
    Key? key,
    this.pageName = "AddorEditTerminalPage",
    this.isEdit = false,
  }) : super(key: key);

  @override
  FState<AddorEditTerminalPage> createState() => _AddOreditTerminalState();
}

class _AddOreditTerminalState extends FState<AddorEditTerminalPage> {
  final controller = Get.find<DeviceController>();
  @override
  FWidget build(BuildContext context) {
    return FSimpleDialog(
      backgroundColor: Colors.white,
      title: FText(
        widget.isEdit
            ? i18nBook.user.modifyDeviceInfo.t
            : i18nBook.user.addDevice.t,
        style: TextStyle(
          color: Colors.white,
          fontSize: 18,
        ),
      ),
      okString: i18nBook.common.confirm.t,
      cancelString: i18nBook.common.cancel.t,
      children: [
        FContainer(
          alignment: Alignment.center,
          margin: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
          width: 580,
          child: FColumn(
            children: [
              FContainer(
                padding: EdgeInsets.symmetric(
                  horizontal: 20,
                ),
                child: BuildAddOrEditTerminal(
                  isEdit: widget.isEdit,
                ),
              ),
            ],
          ),
        ),
      ],
      onClose: () {
        controller.closeBindDevice();
      },
      bottomButton: _TerminalPageBottomButton(widget, widget.isEdit),
    );
  }
}

class _TerminalPageBottomButton extends FisView<DeviceController> {
  final bool isEdit;

  ///父级节点
  final FPage businessParent;
  _TerminalPageBottomButton(this.businessParent, this.isEdit, {Key? key})
      : super(key: key);

  @override
  FWidget build(BuildContext context) {
    return FContainer(
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(vertical: 15),
      child: FFlex(
        direction: Axis.horizontal,
        mainAxisSize: MainAxisSize.min,
        children: [
          FElevatedButton(
            businessParent: businessParent,
            name: "updateTerminalInfo",
            onPressed: () {
              if (isEdit) {
                controller.updateTerminalInfo();
              } else {
                controller.bindDevice(businessParent);
              }
            },
            style: ButtonStyle(
              padding: MaterialStateProperty.all(
                EdgeInsets.symmetric(
                  vertical: 15,
                  horizontal: 25,
                ),
              ),
            ),
            child: FText(i18nBook.common.save.t),
          ),
          FSizedBox(
            width: 20,
          ),
          FOutlinedButton(
            name: "closeBindDevice",
            businessParent: businessParent,
            onPressed: () {
              isEdit ? router.back() : controller.closeBindDevice();
            },
            style: ButtonStyle(
              backgroundColor: MaterialStateProperty.all(
                Colors.white,
              ),
              padding: MaterialStateProperty.all(
                EdgeInsets.symmetric(vertical: 15, horizontal: 25),
              ),
            ),
            child: FText(
              i18nBook.common.cancel.t,
              style: TextStyle(
                color: Color.fromRGBO(61, 146, 252, 1),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

/// 手机端的添加设备
class AddorEditMobileTerminalPage extends FStatefulWidget implements FPage {
  @override
  final String pageName = 'AddorEditMobileTerminalPage';

  @override
  FState<FStatefulWidget> createState() {
    return AddorEditMobileTerminalState();
  }
}

class AddorEditMobileTerminalState extends FState<AddorEditMobileTerminalPage> {
  final controller = Get.find<DeviceController>();
  bool isEdit = false;
  @override
  void initState() {
    var scanData = router.getParams()?['scanData'] ?? '';
    controller.shortCodeController.text = scanData;
    controller.getDeviceInfo(scanData, isFromParam: true).then((value) {
      if (mounted) {
        setState(() {});
      }
    });
    isEdit = router.getParams()?['isEdit'] == 'true';
    super.initState();
  }

  @override
  FWidget build(BuildContext context) {
    return FSafeArea(
      top: false,
      child: FScaffold(
        appBar: _buildEditTerminalAppBar(isEdit),
        backgroundColor: Color.fromRGBO(239, 239, 239, 1),
        body: FSingleChildScrollView(
          child: FObx(
            () => FColumn(
              children: _buildDeviceInfos(isEdit),
            ),
          ),
        ),
      ),
    );
  }

  PreferredSizeWidget _buildEditTerminalAppBar(bool isEdit) {
    return FAppBar.simple(
      title: isEdit ? i18nBook.user.editDevice.t : i18nBook.user.newDevice.t,
      onBackClicked: () => Get.back(),
      actions: [
        FCenter(
          child: FInkWell(
            child: FText(
                isEdit ? i18nBook.common.save.t : i18nBook.common.submit.t),
            onTap: () {
              if (isEdit) {
                controller.updateTerminalInfo();
              } else {
                controller.bindDevice(widget);
              }
            },
          ),
        ),
        FSizedBox(
          width: 20,
        ),
      ],
    );
  }

  ///设备信息集合
  List<FWidget> _buildDeviceInfos(bool isEdit) {
    var deviceInfo = controller.state.deviceInfo;
    final isOrg = controller.state.isOrgDevice;
    final isNew = deviceInfo.isNewDevice;
    final widgets = <FWidget>[
      InputRow(
        title: i18nBook.user.deviceCode.t,
        hintText: i18nBook.common.pleaseEnter.t,
        readOnly: isEdit,
        controller: controller.shortCodeController,
        inputFormatters: [
          FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z0-9]'))
        ],
        maxLength: 6,
        onChanged: (v) {
          if (v.length == 6) {
            deviceInfo.shortCode = v;
            controller.getDeviceInfo(v);
          } else {
            deviceInfo.deviceType = '';
            deviceInfo.deviceModel = '';
            controller.deviceModelController.text = '';
            controller.nameEditingController.text = '';
            controller.deviceNameEditingController.text = '';
            controller.deviceTypeController.text = '';
            controller.orgNameController.text = '';
            controller.state.deviceInfo.organizationName = "";
            controller.state.deviceInfo.description = "";
          }
        },
      ),
      if (isOrg || isNew)
        InputRow(
          title: i18nBook.user.deviceDescription.t,
          hintText: i18nBook.common.pleaseEnter.t,
          maxLength: 200,
          maxLines: 3,
          controller: controller.deviceNameEditingController,
          onChanged: (value) {
            deviceInfo.description = value;
          },
        ),
      InputRow(
        title: i18nBook.profileComplete.organizationIn.t,
        hintText: i18nBook.common.pleaseEnter.t,
        readOnly: true,
        controller: controller.orgNameController,
      ),
      if (isOrg) ...[
        FObx(
          () => SelectSheet(
            title: i18nBook.user.departmentIn.t,
            hintText: i18nBook.common.Select.t,
            source: controller.state.depOptions,
            value: controller.state.deviceInfo.departmentCode,
            onChange: (value) {
              controller.state.deviceInfo.departmentCode = value;
              setState(() {});
            },
          ),
        ),
      ],
      InputRow(
        title: i18nBook.user.deviceType.t,
        readOnly: true,
        hintText: i18nBook.user.autoFillDeviceType.t,
        controller: controller.deviceTypeController,
      ),
      InputRow(
        title: i18nBook.user.deviceModel.t,
        readOnly: true,
        hintText: i18nBook.user.autoFillDeviceModel.t,
        controller: controller.deviceModelController,
      ),
      if (isOrg || isNew) _buildDeviceImage(isEdit),
      if (isOrg) _buildDeviceShareSwitch(),
    ];
    return widgets;
  }

  ///设备封面图
  FWidget _buildDeviceImage(bool isEdit) {
    return FMaterial(
      color: Colors.white,
      child: FColumn(
        children: [
          FContainer(
            padding: EdgeInsets.symmetric(horizontal: 20),
            height: 150,
            child: FRow(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                FContainer(
                  child: FRow(
                    children: [
                      FText(i18nBook.common.image.t),
                    ],
                  ),
                ),
                FObx(() {
                  var deviceInfo = controller.state.deviceInfo;
                  return ImageUploadCard(
                    originImgUrl: deviceInfo.coverImage,
                    height: 101,
                    width: 101,
                    isShowAddIcon: true,
                    onUploaded: (v) {
                      deviceInfo.coverImage = v;
                    },
                    onDeleted: () {
                      deviceInfo.coverImage = '';
                    },
                    hintText: '',
                    localImageUrl: (isEdit &&
                            (controller.state.selectedTerminal.headPicUrl
                                .isNullOrEmpty))
                        ? 'assets/images/mock_terminal.png'
                        : '',
                  );
                }),
              ],
            ),
          ),
          FContainer(
            margin: EdgeInsets.symmetric(horizontal: 20),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: Color.fromRGBO(245, 245, 245, 1),
                ),
              ),
              // color: Colors.white,
            ),
          ),
        ],
      ),
    );
  }

  ///设备是否自动分享
  FWidget _buildDeviceShareSwitch() {
    return FMaterial(
      color: Colors.white,
      child: FColumn(
        children: [
          FContainer(
            padding: EdgeInsets.symmetric(horizontal: 20),
            height: 50,
            child: FRow(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              // crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                FContainer(
                  child: FRow(
                    children: [
                      FText(i18nBook.user.deviceAutoShare.t),
                    ],
                  ),
                ),
                FObx(
                  () => FSwitch(
                    value: controller.state.checked,
                    inactiveThumbColor: FTheme.ins.colorScheme.primary,
                    inactiveTrackColor: Colors.grey.withAlpha(88),
                    activeColor: Colors.white,
                    activeTrackColor: FTheme.ins.colorScheme.primary,
                    onChanged: (v) {
                      controller.state.checked = v;
                    },
                  ),
                ),
              ],
            ),
          ),
          FContainer(
            margin: EdgeInsets.symmetric(horizontal: 20),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: Color.fromRGBO(245, 245, 245, 1),
                ),
              ),
              // color: Colors.white,
            ),
          ),
        ],
      ),
    );
  }
}
