import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/pages/remedical/consultation/controller.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/muti_select.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

/// 日历选择器
FCalendarDatePicker _calendarDatePicker(
    DatePickerMode mode, BuildContext context, String key) {
  final controller = Get.find<ConsultationController>();
  return FCalendarDatePicker(
    initialDate: key == '_startKey'
        ? controller.state.startDateTime
        : controller.state.endDateTime, // 初始化选中日期
    firstDate: DateTime(2000, 9, 10), // 开始日期
    lastDate: DateTime(2222, 9, 10), // 结束日期
    initialCalendarMode: mode, // 日期选择样式
    // 选中日期改变回调函数
    onDateChanged: (dateTime) {
      switch (key) {
        case '_startKey':
          controller.state.startDateTime = dateTime;
          break;
        case '_endKey':
          controller.state.endDateTime = dateTime;
          break;
      }
      Navigator.of(context).pop();
    },
    // 月份改变回调函数
    onDisplayedMonthChanged: (dateTime) {},
    // 筛选日期可不可点回调函数
    selectableDayPredicate: (dayTime) {
      if (dayTime == DateTime(2020, 10, 15) ||
          dayTime == DateTime(2020, 10, 16) ||
          dayTime == DateTime(2020, 10, 17)) {
        return false;
      }
      return true;
    },
  );
}

/// 产品列表对话框
class ProductListDialog extends Dialog implements FPage {
  final List productList;
  final VoidCallback callback;
  final List? position;
  final String? globalKey;
  @override
  final String pageName;

  ProductListDialog({
    Key? key,

    /// 创建的俩个输入框
    required this.productList,

    /// 数据回调
    required this.callback,

    /// 弹框出现位置
    this.position,

    /// 当前key
    this.globalKey,
    this.pageName = 'ProductListDialog',
  }) : super(key: key);
  @override
  FWidget build(BuildContext context) {
    return FMaterial(
      type: MaterialType.transparency,
      child: _buildProductListView(context, globalKey),
    );
  }

  FWidget _buildProductListView(context, globalKey) => FSafeArea(
        child: FGestureDetector(
          name: "back",
          businessParent: this,
          child: FStack(
            children: [
              FContainer(
                width: MediaQuery.of(context).size.width,
                height: MediaQuery.of(context).size.height,
                color: Colors.transparent, // 它的颜色为透明色
              ),
              FPositioned(
                top: position![1],
                left: position![0],
                child: FContainer(
                  constraints: BoxConstraints(
                    maxWidth: 310,
                    maxHeight: 400,
                  ),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    boxShadow: [
                      BoxShadow(
                        blurRadius: 5,
                        color: Color(0xffeeeeee),
                      )
                    ],
                    borderRadius: BorderRadius.circular(5),
                  ),
                  child: _calendarDatePicker(
                    DatePickerMode.day,
                    context,
                    globalKey,
                  ),
                ),
              ),
            ],
          ),
          onTap: () {
            Navigator.of(context).pop();
          },
        ),
      );
}

class PreparationDiaLog extends FisView<ConsultationController>
    implements FPage {
  PreparationDiaLog({
    Key? key,
    this.pageName = 'PreparationDiaLog',
  }) : super(key: key);
  final GlobalKey _startKey = GlobalKey();
  final GlobalKey _endKey = GlobalKey();
  @override
  final String pageName;
  final controller = Get.find<ConsultationController>();

  FWidget title(String name, String value, double textWidth) {
    return FRow(
      children: [
        FContainer(
          width: 40,
          child: FText(
            '$name',
            style: TextStyle(
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        FContainer(
          width: textWidth,
          child: FText('$value'),
        ),
      ],
    );
  }

  _findRenderObject(GlobalKey key) {
    RenderBox? renderBox = key.currentContext!.findRenderObject() as RenderBox;
    // offset.dx , offset.dy 就是控件的左上角坐标
    renderBox.localToGlobal(Offset.zero);
    var offset = renderBox.localToGlobal(Offset.zero);
    return [offset.dx, offset.dy + 38];
  }

  FWidget _buildUIContent(BuildContext context) {
    return FContainer(
      padding: EdgeInsets.symmetric(horizontal: 15),
      child: FColumn(
        children: [
          FSizedBox(
            height: 15,
          ),
          FContainer(
            margin: EdgeInsets.all(8),
            color: Colors.white,
            child: FRow(
              children: [
                FExpanded(
                  child: FContainer(
                    child: FRow(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        FText(i18nBook.common.createTime.t),
                        FSizedBox(
                          width: 20,
                        ),
                        FObx(
                          () => FBorderInput(
                            key: _startKey,
                            hintSize: 16,
                            contentSize: 16,
                            maxLength: 20,
                            borderColor: Color.fromRGBO(234, 234, 234, 1),
                            controller: TextEditingController(
                              text: DateFormat('yyyy-MM-dd')
                                  .format(
                                    Get.put(
                                      ConsultationController(),
                                    ).state.startDateTime,
                                  )
                                  .toString(),
                            ),
                            suffixIcon: FMaterial(
                              color: Colors.transparent,
                              child: FIconButton(
                                name: "startTimePosition",
                                businessParent: this,
                                onPressed: () {
                                  var startTimePosition = _findRenderObject(
                                    _startKey,
                                  );
                                  showDialog(
                                    context: context,
                                    barrierDismissible: false,
                                    builder: (BuildContext context) {
                                      return ProductListDialog(
                                        productList: [],
                                        position: startTimePosition,
                                        globalKey: '_startKey',
                                        callback: () {},
                                      );
                                    },
                                  );
                                },
                                icon: FIcon(
                                  Icons.date_range_rounded,
                                ),
                              ),
                            ),
                            height: 38,
                            hintText: i18nBook.remedical.selectInitTime.t,
                          ),
                        ),
                        FSizedBox(
                          width: 20,
                        ),
                        FContainer(
                          width: 16,
                          height: 2,
                          color: Color.fromRGBO(234, 234, 234, 1),
                        ),
                        FSizedBox(
                          width: 20,
                        ),
                        FObx(
                          () => FBorderInput(
                            key: _endKey,
                            hintSize: 16,
                            contentSize: 16,
                            maxLength: 20,
                            borderColor: Color.fromRGBO(234, 234, 234, 1),
                            controller: TextEditingController(
                              text: DateFormat('yyyy-MM-dd')
                                  .format(
                                    Get.put(
                                      ConsultationController(),
                                    ).state.endDateTime,
                                  )
                                  .toString(),
                            ),
                            suffixIcon: FMaterial(
                              color: Colors.transparent,
                              child: FIconButton(
                                businessParent: this,
                                name: "endTimePosition",
                                onPressed: () {
                                  var endTimePosition =
                                      _findRenderObject(_endKey);
                                  showDialog(
                                    context: context,
                                    barrierDismissible: false,
                                    builder: (BuildContext context) {
                                      return ProductListDialog(
                                        productList: [],
                                        globalKey: '_endKey',
                                        position: endTimePosition,
                                        callback: () {},
                                      );
                                    },
                                  );
                                },
                                icon: FIcon(
                                  Icons.date_range_rounded,
                                ),
                              ),
                            ),
                            height: 38,
                            hintText: i18nBook.remedical.selectEndTime.t,
                            onChanged: (value) {},
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
          _buildCheckinStatusUI(),
          _buildSelectFilter(
            name: i18nBook.user.OrganizationLocated.t,
            selectSource: controller.state.organizationLocatedList,
            value: controller.state.selectedOrganizationLocated,
            onSelectChanged: (value) async {
              // print(object)
              // controller.state.selectedOrganizationLocated = value;
              await controller.patientInfoController
                  .getPersonDeviceDropdownPageAsync();
              controller.state.selectedpersonDevice = [];
            },
          ),
          FObx(
            () => _buildSelectFilter(
              name: i18nBook.homePage.organizationDevices.t,
              selectSource: controller.state.personDeviceList,
              value: controller.state.selectedpersonDevice,
              onSelectChanged: (value) {
                // controller.state.selectedpersonDevice = value;
              },
            ),
          ),
          FSizedBox(
            height: 15,
          ),
        ],
      ),
    );
  }

  void onMakeSure() async {
    if (controller.state.endDateTime.isBefore(controller.state.startDateTime)) {
      PromptBox.toast(i18nBook.remedical.errorScanData.t);
    } else {
      await controller.patientInfoController.getPatients(true);
      controller.state.patientCode = controller.state.patientInfo.patientCode;
      if (controller.state.patientCode != '') {
        controller.patientInfoController.getPatientInfo();
        controller.scanningImageController.getRemedicalListPagesAsync();
        controller.inspectionRecordsController
            .getCheckLists(controller.state.patientCode);
      }
      Get.back();
    }
  }

  @override
  FWidget build(BuildContext context) {
    return FSimpleDialog(
      title: FText(
        i18nBook.common.filter.t,
        style: TextStyle(
          color: Colors.white,
          fontSize: 18,
        ),
      ),
      okString: i18nBook.common.confirm.t,
      cancelString: i18nBook.common.cancel.t,
      insetPadding: EdgeInsets.symmetric(vertical: 150),
      children: [
        FContainer(
          width: 600,
          child: _buildUIContent(context),
        ),
      ],
      bottomButton: FContainer(
        alignment: Alignment.center,
        padding: EdgeInsets.symmetric(vertical: 15),
        child: FFlex(
          direction: Axis.horizontal,
          mainAxisSize: MainAxisSize.min,
          children: [
            FElevatedButton(
              name: "submit",
              businessParent: this,
              onPressed: () => onMakeSure(),
              style: ButtonStyle(
                padding: MaterialStateProperty.all(
                  EdgeInsets.symmetric(
                    vertical: 15,
                    horizontal: 25,
                  ),
                ),
              ),
              child: FText(i18nBook.common.confirm4Btn.t),
            ),
            FSizedBox(
              width: 20,
            ),
            FOutlinedButton(
              name: "back",
              businessParent: this,
              onPressed: () => Get.back(),
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(
                  Colors.white,
                ),
                padding: MaterialStateProperty.all(
                  EdgeInsets.symmetric(vertical: 15, horizontal: 25),
                ),
              ),
              child: FText(
                i18nBook.common.cancel4Btn.t,
                style: TextStyle(
                  color: Color.fromRGBO(61, 146, 252, 1),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  List<FWidget> _buildIsValidFRadio(int currentRadio, String currentRadioName) {
    return [
      FRadio(
        value: currentRadio,
        groupValue: controller.state.isValid,
        onChanged: (v) {
          controller.state.isValid = v;
        },
      ),
      FGestureDetector(
        businessParent: this,
        name: currentRadioName,
        onTap: () {
          controller.state.isValid = currentRadio;
        },
        child: FMouseRegion(
          cursor: SystemMouseCursors.click,
          child: FText(currentRadioName),
        ),
      ),
      FSizedBox(
        width: 10,
      )
    ];
  }

  FWidget _buildSelectFilter({
    required String name,
    required List<FMutiSelectModel> selectSource,
    required ValueCallback onSelectChanged,
    List<String>? value,
  }) {
    return FContainer(
      margin: EdgeInsets.all(8),
      color: Colors.white,
      child: FContainer(
        child: FRow(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            FText(name),
            FSizedBox(
              width: 20,
            ),
            FExpanded(
              child: FMutiSelect<FMutiSelectModel, String>(
                source: selectSource,
                hintText: i18nBook.remedical.pleaseSelect.translate(
                  [name],
                ),
                value: value,
                clearable: false,
                height: 36,
                optionLabelExtractor: (data) => data.name,
                optionValueExtractor: (data) => data.code,
                onSelectChanged: (value, index) {
                  onSelectChanged.call(value);
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  FWidget _buildCheckinStatusUI() {
    if (controller.state.patientTab == 1) {
      return FContainer();
    }
    return FContainer(
      margin: EdgeInsets.all(8),
      color: Colors.white,
      child: FContainer(
        child: FRow(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            FText(i18nBook.remedical.registerStatus.t),
            FSizedBox(
              width: 20,
            ),
            FObx(
              () => FRow(
                ///包裹子布局
                mainAxisSize: MainAxisSize.min,
                children: [
                  ..._buildIsValidFRadio(0, i18nBook.common.all.t).toList(),
                  ..._buildIsValidFRadio(1, i18nBook.remedical.notRegistered.t)
                      .toList(),
                  ..._buildIsValidFRadio(2, i18nBook.remedical.registered.t)
                      .toList(),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
