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:flutter_screenutil/flutter_screenutil.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/pages/components/area_select_tree.dart';
import 'package:flyinsono/pages/element_static.dart';
import 'package:flyinsono/pages/main/home/widgets/dialog_page.dart';
import 'package:flyinsono/pages/main/profile_complete/widgets/row_separator.dart';
import 'package:get/get.dart';
import 'package:fis_theme/theme.dart';
import 'index.dart';

part './widgets/profile_complete_desktop.dart';

const double _itemHeight = 38;
const double _itemOffsetLeft = 6;
const double _contentWidth = 440;
const double _dialogWidth = 750;

///个人信息完善页面
class ProfileCompletePage extends FisView<ProfileCompleteController>
    implements FPage {
  ProfileCompletePage({this.pageName = 'ProfileCompletePage', Key? key})
      : super(key: key);
  @override
  final String pageName;

  @override
  FWidget build(BuildContext context) {
    return context.fResponsive(
      mobile: (_) => _MobileLayout(this),
      desktop: (_) => _DesktopLayout(this),
    );
  }
}

///个人信息完善移动端布局
class _MobileLayout extends FisView<ProfileCompleteController>
    implements FWidget {
  final FPage businessParent;
  _MobileLayout(this.businessParent);
  @override
  FWidget build(BuildContext context) {
    final body = _buildBody(context);
    return FScaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: Colors.white,
      appBar: FAppBar(
        title: FText(
          i18nBook.profileComplete.furtherCompleteProfiles.t,
          style: TextStyle(color: Colors.black, fontSize: 24.sp),
        ),
        actions: [
          FIconButton(
            businessParent: this.businessParent,
            name: "Close",
            icon: FIcon(
              Icons.close_rounded,
              color: Colors.black,
            ),
            onPressed: () => controller.onPageClose(),
            alignment: Alignment.centerRight,
          ),
        ],
        backgroundColor: Colors.white,
        elevation: 0,
        centerTitle: true,
      ),
      body: body,
      bottomNavigationBar: FBottomSubmitButton(
        businessParent: this.businessParent,
        title: i18nBook.common.confirm.t,
        onPressed: () => controller.onSubmit(),
      ),
    );
  }

  FWidget _buildBody(BuildContext context) {
    return FListView(
      controller: controller.innerScrollController,
      padding: EdgeInsets.symmetric(
        vertical: 20.sp,
        horizontal: 5.sp,
      ),
      children: [
        FSizedBox(height: 10.sp),
        // 工作信息
        _buildJobInfo(context),
        FSizedBox(height: 8.sp),
        // 基本信息
        _buildBaseInfo(context),
        FObx(
          () {
            return FSizedBox(
              height: controller.keyboardHeight + 200,
            );
          },
        ),
      ],
    );
  }

  FWidget _buildBaseInfo(BuildContext context) {
    return FContainer(
      alignment: Alignment.topLeft,
      padding: EdgeInsets.only(left: 15.sp, right: 20.sp),
      child: FObx(
        () {
          return FColumn(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildRegionTitle(i18nBook.profileComplete.basicInformation.t),
              FSizedBox(height: 10.sp),
              _buildItemRow(
                i18nBook.common.fullName.t,
                FRimlessInput(
                  controller: controller.nameInputController,
                  height: _itemHeight.sp,
                  hintText: i18nBook.profileComplete.realFullNamePlaceHolder.t,
                  maxLength: 20,
                  focusNode: controller.nameFocusNode,
                  onChanged: (val) => controller.state.name = val,
                ),
                context,
                must: true,
                extendSize: 5,
              ),
              RowSeparator(),
              _buildItemRow(
                  i18nBook.common.mobileNumber.t,
                  FRimlessInput(
                    controller: controller.mobileInputController,
                    height: _itemHeight.sp,
                    hintText: i18nBook.profileComplete.phoneNumberPlaceHolder.t,
                    maxLength: 30,
                    focusNode: controller.mobileFocusNode,
                    onChanged: (val) => controller.state.mobile = val,
                    inputFormatters: [
                      PageInputFormatters.number,
                    ],
                  ),
                  context),
              RowSeparator(),
              if (controller.state.isChinaArea) ...[
                _buildItemRow(
                    i18nBook.common.email.t,
                    FRimlessInput(
                      controller: controller.emailInputController,
                      height: _itemHeight.sp,
                      hintText: i18nBook.profileComplete.emailPlaceHolder.t,
                      maxLength: 50,
                      focusNode: controller.emailFocusNode,
                      onChanged: (val) => controller.state.email = val,
                      inputFormatters: [
                        PageInputFormatters.multipleAccount,
                      ],
                    ),
                    context),
                RowSeparator(),
              ],
            ],
          );
        },
      ),
      margin: EdgeInsets.only(right: 5),
    );
  }

  FWidget _buildJobInfo(BuildContext context) {
    return FContainer(
      padding: EdgeInsets.only(left: 15.sp, right: 20.sp),
      child: FColumn(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          _buildRegionTitle(
            i18nBook.profileComplete.jobInformation.t,
          ),
          FSizedBox(height: 10.sp),
          _buildItemRow(
            i18nBook.profileComplete.areaLocated.t,
            FFlexible(
              child: _buildRegionPickerField(context),
            ),
            context,
          ),
          RowSeparator(),
          _buildItemRow(
            i18nBook.profileComplete.organizationIn.t,
            _buildHospitalInput(),
            context,
            must: true,
          ),
          RowSeparator(),
          _buildItemRow(
            i18nBook.profileComplete.departmentOn.t,
            _buildDepartmentSelect(),
            context,
          ),
          RowSeparator(),
        ],
      ),
      margin: EdgeInsets.only(right: 5),
    );
  }

  FWidget _buildRegionPickerField(BuildContext context) {
    return FGestureDetector(
      businessParent: this.businessParent,
      name: "RegionPicker",
      onTap: () {
        AreaSelectTree.showPicker(
          context,
          selectedCode: controller.state.cityCode,
          onConfirm: (codes, names, isChina) {
            final showName = names.join(' - ');
            controller.state.areaDisplayName = showName;
            controller.state.isChinaArea = isChina;
            controller.state.cityCode = codes.last;
          },
        );
      },
      child: FContainer(
        padding: EdgeInsets.only(left: 5.sp),
        child: FRow(
          children: [
            FExpanded(
              child: FObx(
                () {
                  var txtStyle = TextStyle(fontSize: 13.sp);
                  String txt = controller.state.areaDisplayName;
                  if (txt.isEmpty) {
                    txt = i18nBook.isCurrentChinese
                        ? i18nBook.profileComplete.selectAreaTip.t
                        : "Select region";
                    txtStyle = txtStyle.copyWith(
                      color: Colors.grey,
                    );
                  }
                  return FText(
                    txt,
                    style: txtStyle,
                  );
                },
              ),
            ),
            FFlexible(
              child: FIcon(
                Icons.location_on,
              ),
              flex: 0,
            ),
          ],
        ),
      ),
    );
  }

  FWidget _buildHospitalInput() {
    return FExpanded(
      child: FObx(
        () {
          controller.hospitalFullNameInputController.value = TextEditingValue(
              text: controller.state.hospitalName,
              selection: TextSelection.fromPosition(TextPosition(
                  affinity: TextAffinity.downstream,
                  offset: controller.state.hospitalName.length)));
          return FSuggesionInput<HospitalModel>(
            inputFieldConfiguration: FSuggesionInputFieldConfiguration(
              decoration: FRimlessInput.buildDecoration(
                height: _itemHeight.sp,
                hintText:
                    i18nBook.profileComplete.organizationFullNameInputTip.t,
              ),
              focusNode: controller.hospitalFocusNode,
              maxLength: 100,
              controller: controller.hospitalFullNameInputController,
              onChanged: (val) {
                if (controller.state.hospitalName != val) {
                  controller.state.pageIndex = 1;
                  controller.state.hospitalName = val;
                  controller.setHospitalName();
                }
              },
            ),
            optionItemBuilder: (_, data) {
              return FListTile(
                title: FText(
                  data.title.isEmpty ? i18nBook.college.loadMore.t : data.title,
                  style: const TextStyle(
                    color: Colors.grey,
                    fontSize: FInput.hintSize,
                  ),
                ),
              );
            },
            optionItemsFetcher: (pattern) async {
              if (pattern.isEmpty) {
                return [];
              }
              await controller.fetchHospital(pattern);
              return controller.state.hospitalDtoList.map(
                (e) => HospitalModel(
                  title: e.organizationName ?? '',
                ),
              );
            },
            onLoadMore: (pattern) async {
              controller.state.pageIndex++;
              var hospitals = await controller.fetchHospital(pattern, true);
              return hospitals.map(
                (e) => HospitalModel(title: e.organizationName ?? ''),
              );
            },
            onOptionSelected: (data) async {
              if (data.title.isEmpty) {
                controller.state.pageIndex++;
                await controller.fetchHospital(
                    controller.state.hospitalName, true);
                FocusScope.of(Get.context!)
                    .requestFocus(controller.hospitalFocusNode);
                return;
              }
              if (controller.state.hospitalName != data.title) {
                controller.state.hospitalName = data.title;
                controller.setHospitalName();
              }
            },
            noItemsFoundText: i18nBook.user.getOrganizationFailed.t,
          );
        },
      ),
    );
  }

  FWidget _buildDepartmentSelect() {
    final state = controller.state;
    final selectWidget = FObx(
      () {
        return FSelect<DepartmentModel, String>(
          source: state.departmentOptions,
          value: state.departmentSelection,
          fontFamily: FTheme.ins.localeSetting.fontFamily,
          optionValueExtractor: (value) {
            return value.code;
          },
          optionLabelExtractor: (value) {
            return value.title;
          },
          onSelectChanged: (value, index) {
            state.departmentSelection = value;
          },
          hintText: i18nBook.profileComplete.departmentOn.t,
          fontSize: 14,
        );
      },
    );
    return FExpanded(
      child: FContainer(
        padding: kIsMobile
            ? EdgeInsets.only(left: 5.sp)
            : EdgeInsets.only(left: 12.sp),
        child: selectWidget,
      ),
    );
  }

  FWidget _buildItemRow(
    String label,
    FWidget itemWidget,
    BuildContext context, {
    bool must = false,
    Key? key,
    double? extendSize,
  }) {
    final labelStyle =
        TextStyle(fontSize: 15.sp, color: Color.fromRGBO(90, 90, 90, 1));
    FWidget txt;
    double padding;
    double margin;
    if (must) {
      txt = FText.rich(
        TextSpan(
          children: [
            TextSpan(text: label),
            TextSpan(text: ' *', style: labelStyle.copyWith(color: Colors.red)),
          ],
          style: labelStyle,
        ),
      );
      padding = 5;
      margin = extendSize == null ? 5 : (5 + extendSize);
    } else {
      txt = FText(
        label,
        style: TextStyle(
          fontSize: 15.sp,
          color: Colors.grey,
        ),
      );
      padding = 10;
      margin = 10;
    }
    return FContainer(
      key: key,
      margin: EdgeInsets.only(bottom: 0.sp, top: 2.sp),
      child: FRow(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          FContainer(
            margin: EdgeInsets.only(right: margin.sp, left: 10.sp),
            padding: EdgeInsets.only(right: padding.sp),
            width: 80.sp,
            height: _itemHeight.sp,
            alignment: Alignment.centerLeft,
            child: txt,
          ),
          itemWidget,
        ],
      ),
    );
  }

  FWidget _buildRegionTitle(String title) {
    FWidget text = FText(
      title,
      style: TextStyle(
        fontSize: 16.sp,
        color: Colors.black,
      ),
    );
    return FContainer(
      margin: EdgeInsets.only(left: 7.sp),
      child: text,
    );
  }
}
