import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/values/font_sizes.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/utils/common_util.dart';
import 'package:flyinsono/managers/server_config_manager.dart';
import 'package:flyinsono/pages/organization/org_info/state.dart';
import 'package:flyinsono/pages/user/user_profile/widgets/user_info_dialog.dart';
import 'package:get/get.dart';
import 'index.dart';
import 'package:fis_theme/theme.dart';

const double _itemHeight = 38;

///用户信息页面
class UserProfilePage extends FisView<UserProfileController> implements FPage {
  const UserProfilePage({Key? key}) : super(key: key);
  @override
  final String pageName = 'UserProfilePage';
  // 内容页
  @override
  FWidget build(BuildContext context) {
    return context.fResponsiveVoid(
      mobile: () => _MobileLayout(this),
      desktop: () => _DesktopLayout(this),
    );
  }
}

class _MobileLayout extends FisView<UserProfileController> implements FWidget {
  ///父级节点
  final FPage businessParent;
  final ScrollController _scrollController = ScrollController();
  _MobileLayout(this.businessParent);
  @override
  FWidget build(BuildContext context) {
    return FScaffold(
      appBar: FAppBar(
        title: FText(
          i18nBook.user.completeAccountInfo4Mobile.t,
          style: TextStyle(fontSize: 16, color: Colors.white),
        ),
        elevation: 0,
        centerTitle: true,
        leading: FIconButton(
          businessParent: businessParent,
          name: "back",
          icon: FIcon(
            Icons.arrow_back_ios_new,
            size: 20,
          ),
          onPressed: () {
            _onBack();
          },
        ),
        actions: [
          FTextButton(
            businessParent: businessParent,
            name: "save",
            child: FText(
              i18nBook.common.save.t,
              style: TextStyle(color: Colors.white, fontSize: 16),
            ),
            onPressed: () {
              controller.submit();
            },
          ),
        ],
      ),
      body: FContainer(
        color: Color.fromARGB(255, 236, 236, 236),
        child: FContainer(
          child: FObx(() {
            return FAlwaysScrollListView(
              scrollController: _scrollController,
              child: QuickFWidget(ScrollConfiguration(
                behavior:
                    ScrollConfiguration.of(context).copyWith(scrollbars: false),
                child: FListView(
                  controller: _scrollController,
                  children: [
                    SelectRow(
                      title: i18nBook.common.fullName.t,
                      hintText: '',
                      value: controller.state.fullName,
                      onClick: () {
                        controller.openSelectName();
                      },
                    ),
                    FSizedBox(height: 2.sp),
                    SelectRow(
                      title: i18nBook.common.mobileNumber.t,
                      hintText: '',
                      value: controller.state.phone,
                      onClick: () {
                        controller.openChangePhoneorEmail(true);
                      },
                    ),
                    FSizedBox(height: 2.sp),
                    SelectRow(
                      title: i18nBook.common.email.t,
                      hintText: '',
                      value: controller.state.email,
                      onClick: () {
                        controller.openChangePhoneorEmail(false);
                      },
                    ),
                    FSizedBox(height: 7.sp),
                    SelectRow(
                      title: i18nBook.auth.hospitalCode.t,
                      hintText: '',
                      value: controller.state.orgShortCode,
                      onClick: () {
                        controller.openSelectOrg();
                      },
                    ),
                    FSizedBox(height: 2.sp),
                    FContainer(
                      color: Colors.white,
                      padding: EdgeInsets.only(left: 20, right: 40),
                      margin: EdgeInsets.only(bottom: 1),
                      height: 50,
                      child: FRow(
                        children: [
                          FText(i18nBook.organization.orgName.t),
                          FExpanded(child: FSizedBox()),
                          FObx(
                            () => FText(controller.state.orgName),
                          ),
                        ],
                      ),
                    ),
                    FSizedBox(height: 2.sp),
                    SelectRow(
                      title: i18nBook.profileComplete.departmentOn.t,
                      hintText: '',
                      value: controller.state.department,
                      onClick: () {
                        controller.openSelectDep();
                      },
                    ),
                  ],
                ),
              )),
            );
          }),
        ),
      ),
    );
  }

  ///返回
  void _onBack() {
    var userInfoCache = controller.userInfoCache;
    var state = controller.state;
    if (userInfoCache.fullName != state.fullName ||
        userInfoCache.email != state.email ||
        userInfoCache.phone != state.phone ||
        userInfoCache.departmentShortCode != state.depShortCode) {
      FConfirmAlert.show(
        context: Get.context!,
        title: i18nBook.user.currentHasChangedInfoNotSave.t,
        subTitle: i18nBook.user.continueToFinishConfirm.t,
        confrimLabel: i18nBook.common.yes.t,
        cancelLabel: i18nBook.common.no.t,
        onCancel: router.back,
        businessParent: this.businessParent,
      );
    } else {
      router.back();
    }
  }
}

class _DesktopLayout extends FisView<UserProfileController> implements FWidget {
  ///父级节点
  final FPage businessParent;
  final ScrollController _scrollController = ScrollController();
  _DesktopLayout(this.businessParent);
  @override
  FWidget build(BuildContext context) {
    final child = FContainer(
      color: Colors.white,
      padding: EdgeInsets.symmetric(vertical: 36, horizontal: 50),
      child: FCenter(
        child: FContainer(
          child: FAlwaysScrollListView(
            scrollController: _scrollController,
            child: QuickFWidget(ScrollConfiguration(
              behavior:
                  ScrollConfiguration.of(context).copyWith(scrollbars: false),
              child: FListView(
                shrinkWrap: true,
                controller: _scrollController,
                children: [
                  _centerWidget(
                    FContainer(
                      child: FText(
                        i18nBook.homePage.organizationInfo.t,
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 18,
                        ),
                      ),
                    ),
                  ),
                  FSizedBox(height: 20),
                  _centerWidget(
                    _buildItemRow(
                      i18nBook.auth.hospitalCode.t,
                      FBorderInput(
                          hintSize: 16,
                          contentSize: 16,
                          maxLength: 20,
                          height: _itemHeight.sp,
                          controller: controller.orgShortCodeController,
                          hintText: i18nBook.auth.pleaseSetHospitalCode.t,
                          borderColor: Color.fromRGBO(230, 230, 230, 1),
                          onChanged: (value) {
                            controller.state.orgShortCode = value;
                            if (controller.state.orgShortCode.length == 6) {
                              controller.setDepartment();
                            } else {
                              controller.state.depOptions = [];
                              controller.state.depShortCode = '';
                            }
                          }),
                    ),
                  ),
                  FSizedBox(height: 15),
                  _buildItemRow(
                    i18nBook.organization.orgName.t,
                    FExpanded(
                      child: FObx(
                        () => FText(controller.state.orgName.isEmpty
                            ? '  ${i18nBook.realTimeConsultation.noAssistant.t}'
                            : "  ${controller.state.orgName}"),
                      ),
                    ),
                  ),
                  FSizedBox(height: 15),
                  _centerWidget(
                    _buildItemRow(
                      i18nBook.profileComplete.departmentOn.t,
                      _BuildDepartmentSelect(),
                    ),
                  ),
                  FSizedBox(height: 20),
                  _centerWidget(FContainer(
                    child: FText(
                      i18nBook.profileComplete.basicInformation.t,
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 18,
                      ),
                    ),
                  )),
                  FSizedBox(height: 20),
                  _centerWidget(
                    _buildItemRow(
                      i18nBook.common.fullName.t,
                      FBorderInput(
                        hintSize: 16,
                        contentSize: 16,
                        maxLength: 20,
                        height: _itemHeight.sp,
                        inputFormatters: [
                          FilteringTextInputFormatter.deny(
                            RegExp(
                              CommonUtil.BLANK_SPACE,
                            ),
                          )
                        ],
                        hintText: i18nBook.user.InputName.t,
                        borderColor: Color.fromRGBO(230, 230, 230, 1),
                        onChanged: (value) => controller.state.fullName = value,
                        controller: controller.nameController,
                      ),
                    ),
                  ),
                  FSizedBox(height: 15),
                  if (ServerConfigManager.isSMSOn) ...[
                    _centerWidget(
                      _buildItemRow(
                        i18nBook.common.mobileNumber.t,
                        FBorderInput(
                          hintSize: FFontSizes.H6,
                          contentSize: FFontSizes.H6,
                          maxLength: 20,
                          height: _itemHeight.sp,
                          hintText:
                              i18nBook.profileComplete.phoneNumberPlaceHolder.t,
                          borderColor: Color.fromRGBO(230, 230, 230, 1),
                          onChanged: (value) =>
                              controller.state.phone = value.toString(),
                          controller: controller.phoneController,
                        ),
                      ),
                    ),
                  ],
                  FSizedBox(height: 15),
                  _centerWidget(
                    _buildItemRow(
                      i18nBook.common.email.t,
                      FBorderInput(
                        hintSize: 16,
                        contentSize: 16,
                        maxLength: 20,
                        borderColor: Color.fromRGBO(230, 230, 230, 1),
                        height: _itemHeight.sp,
                        hintText: i18nBook.user.InputEmail.t,
                        onChanged: (value) => controller.state.email = value,
                        controller: controller.emailController,
                      ),
                    ),
                  ),
                ],
              ),
            )),
          ),
        ),
      ),
    );
    return UserInfoDialog(
      child: child,
    );
  }

  FWidget _centerWidget(FWidget widget) {
    return FCenter(
      child: FContainer(
        alignment: Alignment.centerLeft,
        child: widget,
      ),
    );
  }

  FWidget _buildItemRow(String title, FWidget widget,
      {bool isRequired = false}) {
    final labelStyle = TextStyle(fontSize: 16);
    return FFlex(
      direction: Axis.horizontal,
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        FFlexible(
          child: FContainer(
            width: 130.sp,
            alignment: Alignment.centerLeft,
            child: FText.rich(
              TextSpan(children: [
                TextSpan(text: title, style: labelStyle),
                if (isRequired) ...[
                  TextSpan(
                    text: ' *',
                    style: labelStyle.copyWith(color: Colors.red),
                  )
                ] else ...[
                  TextSpan(text: '')
                ]
              ]),
            ),
          ),
          flex: 0,
        ),
        widget,
      ],
    );
  }
}

///部门选择框，选择医院下的部门
class _BuildDepartmentSelect extends FisView<UserProfileController> {
  @override
  FWidget build(BuildContext context) {
    final select = FObx(() {
      return FSelect<OrgModel, String>(
        source: controller.state.depOptions,
        hintText: i18nBook.remedical.pleaseSelect.translate(
          [i18nBook.organization.selectValueDepartment.t],
        ),
        fontFamily: FTheme.ins.localeSetting.fontFamily,
        value: controller.state.depOptions
                .any((e) => e.code == controller.state.depShortCode)
            ? controller.state.depShortCode
            : null,
        clearable: true,
        height: 36,
        optionLabelExtractor: (data) => data.name,
        optionValueExtractor: (data) => data.code,
        onSelectChanged: (value, index) {
          controller.state.depShortCode = value ?? '';
        },
      );
    });

    return FExpanded(
      child: select,
    );
  }
}
