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:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/pages/remedical/consultation/controller.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/age_text.dart';
import 'package:flyinsono/pages/remedical/create_check/widgets/check_item.dart';
import 'package:fis_jsonrpc/rpc.dart';

//import 'package:universal_html/html.dart';

import 'index.dart';

class CreatecheckPage extends FisView<CreatecheckController> implements FPage {
  final String? patientCode;
  @override
  final String pageName;
  CreatecheckPage(this.patientCode,
      {this.pageName = 'CreatecheckPage', Key? key})
      : super(key: key);
  @override
  FWidget build(BuildContext context) {
    controller.state.patientCode = patientCode;
    return context.fResponsiveVoid(
      mobile: () => _MobileLayout(this),
      desktop: () => _DesktopLayout(this),
    );
  }
}

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

  /// 保存的检查列表
  List selectCheckList = [];

  /// 滚动控制器
  final ScrollController _scrollController = ScrollController();

  final ScrollController _leftScrollController = ScrollController();
  final ScrollController _rightScrollController = ScrollController();
  final ScrollController _baseScrollController = ScrollController();
  _DesktopLayout(this.businessParent, {Key? key}) : super(key: key);
  @override
  FWidget build(BuildContext context) {
    return FContainer(
      decoration: BoxDecoration(
        color: Color.fromRGBO(242, 242, 242, 1),
        borderRadius: BorderRadius.all(
          Radius.circular(8),
        ),
      ),
      margin: EdgeInsets.all(70),
      child: FColumn(
        children: [
          _buildCreateCheckTitle(),
          _buildCreateCheckOrganization(),
          _buildCreateCheckBody(context),
        ],
      ),
    );
  }

  /// 检查的基础信息
  FWidget _buildBasicInformation(BuildContext context) {
    ConsultationController consultationController =
        controller.consultationController;
    return FObx(() {
      CreatecheckState state = controller.state;
      return FColumn(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          _buildBasicInformationItem(
              consultationController.state.patientType ==
                      OrganizationPatientTypeEnum.Person
                  ? i18nBook.common.fullName.t
                  : i18nBook.remedical.petName.t,
              state.patientInfo['name'] ?? i18nBook.remedical.notFill.t),
          _buildBasicInformationFWidgetItem(
            i18nBook.remedical.age.t, // 年龄变更
            AgeText(
              ageUnits: state.patientInfo!['ageUnits'],
              ageDay: state.patientInfo!['ageDay'],
              ageMonth: state.patientInfo!['ageMonth'],
              ageWeek: state.patientInfo!['ageWeek'],
              ageYear: state.patientInfo!['ageYear'],
            ),
          ),
          _buildBasicInformationItem(
            i18nBook.remedical.gender.t,
            controller.getValues(
              state.patientInfo!['gender'] ?? i18nBook.remedical.notFill.t,
            ),
          ),
          FContainer(
            height: 50,
            child: FRow(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                FContainer(
                  /// TODO:[Gavin] 多语言-UI-整合
                  width: i18nBook.isCurrentChinese ? 80 : 130,
                  child: FText(
                    i18nBook.remedical.deliveryDevice.t,
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                _buildEquipmentSelect(),
              ],
            ),
          ),
          FContainer(
            height: 50,
            child: FRow(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                FContainer(
                  /// TODO:[Gavin] 多语言-UI-整合
                  width: i18nBook.isCurrentChinese ? 80 : 130,
                  child: FText(
                    i18nBook.remedical.checkItem.t,
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                FObx(
                  () => _buildCheckItem(
                    controller.state.selectCheckList,
                  ),
                ),
              ],
            ),
          ),
          FContainer(
            child: FObx(
              () => FAlwaysScrollListView(
                scrollController: _baseScrollController,
                child: QuickFWidget(ScrollConfiguration(
                  behavior: ScrollConfiguration.of(context)
                      .copyWith(scrollbars: false),
                  child: FListView.builder(
                    controller: _baseScrollController,
                    shrinkWrap: true,
                    itemCount: controller.state.selectCheckList.length,
                    itemBuilder: (BuildContext context, int index) {
                      return FContainer(
                        margin: EdgeInsets.only(
                          /// TODO:[Gavin] 多语言-UI-整合
                          left: i18nBook.isCurrentChinese ? 80 : 130,
                          bottom: 10,
                        ),
                        padding: EdgeInsets.only(
                          left: 14,
                          right: 5,
                        ),
                        height: 36,
                        width: 400,
                        decoration: BoxDecoration(
                          border: Border.all(
                            color: Color.fromRGBO(
                              230,
                              230,
                              230,
                              1,
                            ),
                          ),
                          borderRadius: BorderRadius.all(
                            Radius.circular(4),
                          ),
                        ),
                        child: FRow(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            FText(
                              controller.getValues(
                                  controller.state.selectCheckList[index]),
                              style: TextStyle(
                                fontSize: 16,
                              ),
                            ),
                            FIconButton(
                              name: "remove:$index",
                              businessParent: this.businessParent,
                              onPressed: () {
                                selectCheckList.remove(
                                  selectCheckList[index],
                                );
                                controller.state.selectCheckList =
                                    selectCheckList.toSet().toList();
                              },
                              icon: FIcon(
                                Icons.close,
                                size: 20,
                              ),
                            )
                          ],
                        ),
                      );
                    },
                  ),
                )),
              ),
            ),
          ),
        ],
      );
    });
  }

  /// 基础信息单元行
  FWidget _buildBasicInformationFWidgetItem(String title, FWidget value) {
    return FContainer(
      height: 50,
      child: FRow(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          FContainer(
            /// TODO:[Gavin] 多语言-UI-整合
            width: i18nBook.isCurrentChinese ? 80 : 130,
            child: FText(
              title,
              style: TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          FContainer(
            child: value,
          ),
        ],
      ),
    );
  }

  /// 基础信息单元行
  FWidget _buildBasicInformationItem(String title, String value) {
    return FContainer(
      height: 50,
      child: FRow(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          FContainer(
            /// TODO:[Gavin] 多语言-UI-整合
            width: i18nBook.isCurrentChinese ? 80 : 130,
            child: FText(
              title,
              style: TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          FContainer(
            child: FText(value),
          ),
        ],
      ),
    );
  }

  ///  检查项目
  FWidget _buildCheckItem(List selectCheck) {
    final state = controller.state;
    final select = FObx(
      () => FSelect<SelectModel, String>(
        source: state.checkHasSelect,
        hintText: i18nBook.remedical.select.t,
        value: null,
        clearable: false,
        height: 36,
        width: 400,
        fontFamily: FTheme.ins.localeSetting.fontFamily,
        optionLabelExtractor: (data) => data.name,
        optionValueExtractor: (data) => data.code,
        onSelectChanged: (value, index) {
          selectCheckList.add(value);
          if (value == 'Obstetrics') {
            state.contents['Obstetrics-GestationalAgeOrigin'] = 'LMP';
          }
          state.selectCheckList = selectCheckList.toSet().toList();
        },
      ),
    );

    return FExpanded(child: select);
  }

  /// 创建检查的主体
  FWidget _buildCreateCheckBody(BuildContext context) {
    return FExpanded(
      child: FContainer(
        margin: EdgeInsets.only(
          left: 15,
          right: 15,
          bottom: 15,
        ),
        color: Colors.white,
        child: FColumn(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            _buildCreateCheckBodyPatientInfo(context),
            FContainer(
              height: 4,
              color: Color.fromRGBO(242, 242, 242, 1),
            ),
            _buildCreateCheckBodybutton(),
          ],
        ),
      ),
    );
  }

  /// 检查主体的按钮
  FWidget _buildCreateCheckBodybutton() {
    return FContainer(
      padding: EdgeInsets.only(top: 15, bottom: 15),
      color: Colors.white,
      child: FRow(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          FElevatedButton(
            name: "save",
            businessParent: this.businessParent,
            onPressed: () {
              controller.createRecordInfo();
            },
            style: ButtonStyle(
              padding: MaterialStateProperty.all(
                EdgeInsets.symmetric(
                  vertical: 15,
                  horizontal: 25,
                ),
              ),
            ),
            child: FText(i18nBook.common.save.t),
          ),
          FSizedBox(
            width: 30,
          ),
          FOutlinedButton(
            name: "back",
            businessParent: this.businessParent,
            onPressed: () async {
              router.back();
            },
            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: FTheme.ins.colorScheme.primary,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 检查主体的病人信息
  FWidget _buildCreateCheckBodyPatientInfo(BuildContext context) {
    return FExpanded(
      child: FRow(
        children: [
          FContainer(
            width: 400,
            margin: EdgeInsets.symmetric(
              horizontal: 30,
              vertical: 20,
            ),
            child: FAlwaysScrollListView(
              scrollController: _leftScrollController,
              child: QuickFWidget(ScrollConfiguration(
                behavior:
                    ScrollConfiguration.of(context).copyWith(scrollbars: false),
                child: FListView(
                  controller: _leftScrollController,
                  children: [
                    _buildBasicInformation(context),
                    FRow(
                      children: [
                        FContainer(
                          /// TODO:[Gavin] 多语言-UI-整合
                          width: i18nBook.isCurrentChinese ? 80 : 130,
                          height: 40,
                          alignment: Alignment.centerLeft,
                          child: FText(
                            i18nBook.remedical.checkDoctor.t,
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        FContainer(
                          child: FText(_generatorDoc()),
                        ),
                      ],
                    ),
                  ],
                ),
              )),
            ),
          ),
          FContainer(
            width: 15,
            color: Color.fromRGBO(242, 242, 242, 1),
          ),
          FExpanded(
            child: FContainer(
              child: FListView(
                controller: _scrollController,
                children: [
                  _buildRightRow(context),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 创建检查的组织部分
  FWidget _buildCreateCheckOrganization() {
    return FContainer(
      color: Colors.white,
      margin: EdgeInsets.only(left: 15, right: 15, bottom: 5, top: 15),
      height: 40,
      child: FRow(
        children: [
          FExpanded(
            child: FRow(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                _buildTabs(
                  i18nBook.remedical.time.t,
                  DateTime.now().toString().substring(0, 16),
                ),
                FObx(
                  () => _buildTabs(
                    i18nBook.organization.department.t,
                    controller.state.organizationName,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 创建检查头部
  FWidget _buildCreateCheckTitle() {
    return FContainer(
      height: 50,
      decoration: BoxDecoration(
        color: FTheme.ins.colorScheme.primary,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(8),
          topRight: Radius.circular(8),
        ),
      ),
      child: FAlign(
        alignment: Alignment.centerLeft,
        child: FContainer(
          margin: EdgeInsets.only(left: 15),
          child: FText(
            i18nBook.remedical.createCheck.t,
            style: TextStyle(
              color: Colors.white,
              fontSize: 18,
            ),
          ),
        ),
      ),
    );
  }

  /// 下发设备
  FWidget _buildEquipmentSelect() {
    final state = controller.state;

    /// 上级机构
    final select = FObx(() => FSelect<SelectModel, String>(
          source: state.deviceOptions,
          fontFamily: FTheme.ins.localeSetting.fontFamily,
          hintText: i18nBook.remedical.selectDeliveryDevice.t,
          value: state.deviceCode,
          clearable: true,
          height: 36,
          width: 400,
          optionLabelExtractor: (data) => data.name,
          optionValueExtractor: (data) => data.code,
          onSelectChanged: (value, index) {
            if (value == null) {
              state.deviceCode = null;
              return;
            }
            state.deviceCode = value;
          },
        ));

    return FExpanded(child: select);
  }

  FWidget _buildRightRow(BuildContext context) {
    final state = controller.state;

    final child = FObx(
      () => FContainer(
        padding: EdgeInsets.all(30),
        child: FColumn(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            FAlwaysScrollListView(
              scrollController: _rightScrollController,
              child: QuickFWidget(ScrollConfiguration(
                behavior:
                    ScrollConfiguration.of(context).copyWith(scrollbars: false),
                child: FListView.builder(
                  controller: _rightScrollController,
                  shrinkWrap: true,
                  itemCount: state.selectCheckList.length,
                  itemBuilder: (BuildContext context, int index) {
                    return FColumn(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        FText(
                          controller
                              .getValues(state.selectCheckList[index])
                              .toString(),
                          style: TextStyle(fontWeight: FontWeight.bold),
                        ),
                        FSizedBox(
                          height: 20,
                        ),
                        FObx(
                          () => CheckItem(
                            selectCheckListItem: state.selectCheckList[index],
                          ),
                        ),
                        FDivider(),
                      ],
                    );
                  },
                ),
              )),
            ),
          ],
        ),
      ),
    );
    return FColumn(
      children: [child],
    );
  }

  FWidget _buildTabs(String name, String value) {
    return FRow(
      children: [
        FSizedBox(
          width: 30,
        ),
        FContainer(
          child: FText(
            name,
            style: TextStyle(
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        FSizedBox(
          width: 30,
        ),
        FContainer(
          child: FText(value),
        ),
      ],
    );
  }

  String _generatorDoc() {
    return ((Store.user.displayName.isEmpty)
        ? i18nBook.homePage.notYet.t
        : Store.user.displayName);
  }
}

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

  const _MobileLayout(this.businessParent, {Key? key}) : super(key: key);
  @override
  FWidget build(BuildContext context) {
    return FContainer();
  }
}
