part of '../view.dart';

///个人信息桌面端布局
class _DesktopLayout extends FisView<ProfileCompleteController>
    implements FWidget {
  final FPage businessParent;
  _DesktopLayout(this.businessParent);
  @override
  FWidget build(BuildContext context) {
    final profileCompleteBody = _buildBody(context);
    final paddingHorizontal = (_dialogWidth - _contentWidth) / 2 - 20;
    final profileCompleteMain = FScrollbar(
      controller: controller.innerScrollController,
      isAlwaysShown: true,
      child: FSingleChildScrollView(
        controller: controller.innerScrollController,
        child: FCenter(
          child: FContainer(
            padding: EdgeInsets.symmetric(
              vertical: 50.sp,
              horizontal: paddingHorizontal.sp,
            ),
            child: profileCompleteBody,
          ),
        ),
      ),
    );

    final size = MediaQuery.of(context).size;
    final minHeight = 400.sp;

    FWidget result = FObx(
      () {
        final bodyHeight = controller.state.isChinaArea ? 680.sp : 640.sp;
        double marignVertical = (size.height - bodyHeight) / 2;
        if (marignVertical < 0) marignVertical = 0;

        return FContainer(
          margin: EdgeInsets.symmetric(
            vertical: marignVertical,
            horizontal: (size.width - _dialogWidth.sp) / 2,
          ),
          constraints: BoxConstraints(
            minHeight: minHeight,
            maxHeight: bodyHeight,
          ),
          width: _dialogWidth.sp,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(8.0),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(.4),
                offset: const Offset(0.0, 6.0),
                blurRadius: 6,
                spreadRadius: 0,
              ),
            ],
          ),
          child: profileCompleteMain,
        );
      },
    );

    // 超小高度就用外滚动
    if (size.height < minHeight) {
      result = FSingleChildScrollView(
        child: result,
      );
    }
    return FOverlayContainer(
      child: result,
    );
  }

  FWidget _buildBody(BuildContext context) {
    return FColumn(
      mainAxisSize: MainAxisSize.min,
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        FCenter(
          child: FText(
            i18nBook.profileComplete.furtherCompleteProfiles.t,
            style: TextStyle(
              fontSize: 24.sp,
              color: Colors.black,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        FSizedBox(height: 5.sp),
        FCenter(
          child: FText(
            i18nBook.profileComplete.furtherCompleteProfilesToFindYou.t,
            style: TextStyle(
              fontSize: 13.sp,
              color: Color(
                0xff9e9e9e,
              ),
            ),
          ),
        ),
        // 工作信息
        _buildJobInfo(),
        FSizedBox(height: 8.sp),
        // 基本信息
        _buildBaseInfo(),
        FSizedBox(height: 38.sp),
        _buildOperateRow(),
      ],
    );
  }

  FWidget _buildBaseInfo() {
    return FContainer(
      alignment: Alignment.topLeft,
      padding: EdgeInsets.symmetric(vertical: 26.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,
                ),
                must: true,
              ),
              RowSeparator(),
              if (controller.state.isChinaArea) ...[
                _buildItemRow(
                  i18nBook.common.mobileNumber.t,
                  FRimlessInput(
                    controller: controller.mobileInputController,
                    height: _itemHeight.sp,
                    hintText: i18nBook.profileComplete.phoneNumberPlaceHolder.t,
                    maxLength: 20,
                    focusNode: controller.mobileFocusNode,
                    onChanged: (val) => controller.state.mobile = val,
                    inputFormatters: [
                      PageInputFormatters.number,
                    ],
                  ),
                ),
                RowSeparator(),
              ],
              _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,
                  ],
                ),
              ),
              RowSeparator(),
            ],
          );
        },
      ),
    );
  }

  FWidget _buildJobInfo() {
    return FContainer(
      child: FColumn(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          _buildRegionTitle(i18nBook.profileComplete.jobInformation.t),
          FSizedBox(height: 10.sp),
          _buildItemRow(
            i18nBook.profileComplete.areaLocated.t,
            AreaSelectTree(
              onIsChinaAreaChanged: (val) => controller.state.isChinaArea = val,
              onCityChanged: (val) => controller.state.cityCode = val,
              onProvinceChanged: (val) => controller.state.cityCode = val,
              onCountryChanged: (val) => controller.state.countryCode = val,
            ),
          ),
          RowSeparator(),
          _buildItemRow(
            i18nBook.profileComplete.organizationIn.t,
            FSuggesionInputWidget(),
            must: true,
          ),
          RowSeparator(),
          _buildItemRow(
            i18nBook.profileComplete.departmentOn.t,
            _buildDepartmentSelect(),
          ),
          RowSeparator(),
        ],
      ),
      margin: EdgeInsets.only(
        right: 5,
      ),
    );
    //});
  }

  FWidget _buildDepartmentSelect() {
    final state = controller.state;
    final selectWidget = FObx(() {
      // TODO: melon - 定制下拉框 or 扩展FSelect组件
      return FSelect<DepartmentModel, String>(
        source: state.departmentOptions,
        fontFamily: FTheme.ins.localeSetting.fontFamily,
        value: state.departmentSelection,
        optionValueExtractor: (value) {
          return value.code;
        },
        optionLabelExtractor: (value) {
          return value.title;
        },
        onSelectChanged: (value, index) {
          state.departmentSelection = value;
        },
        hintText: i18nBook.profileComplete.departmentPlaceHolder.t,
        fontSize: 13,
        decoration: BoxDecoration(
          border: Border.all(
            color: Colors.transparent,
          ),
        ),
      );
    });
    return FExpanded(
      child: FContainer(
        padding: kIsMobile
            ? EdgeInsets.only(
                left: 20.sp,
              )
            : EdgeInsets.only(
                left: 12.sp,
              ),
        child: selectWidget,
      ),
    );
  }

  FWidget _buildItemRow(String label, FWidget itemWidget,
      {bool must = false, Key? key}) {
    final labelStyle = TextStyle(
      fontSize: 14.sp,
      color: Color(
        0xff888888,
      ),
    );
    FWidget txtLabel;
    if (must) {
      txtLabel = FText.rich(TextSpan(
        children: [
          TextSpan(text: label),
          TextSpan(
            text: ' *',
            style: labelStyle.copyWith(
              color: Colors.red,
            ),
          ),
        ],
        style: labelStyle,
      ));
    } else {
      txtLabel = FText(
        label,
        style: labelStyle,
      );
    }
    return FContainer(
      key: key,
      margin: EdgeInsets.only(
        bottom: 2.sp,
        top: 12.sp,
      ),
      child: FRow(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          FContainer(
            margin: EdgeInsets.symmetric(
              horizontal: _itemOffsetLeft.sp,
            ),
            width: 80.sp,
            height: _itemHeight.sp,
            alignment: Alignment.centerLeft,
            child: txtLabel,
          ),
          itemWidget,
        ],
      ),
    );
  }

  FWidget _buildRegionTitle(String title) {
    return FText(
      title,
      style: TextStyle(
        fontSize: 18.sp,
        color: Color.fromRGBO(
          90,
          90,
          90,
          1,
        ),
        fontWeight: FontWeight.bold,
      ),
    );
  }

  FWidget _buildOperateRow() {
    return FRow(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        FPrimaryButton(
          text: i18nBook.common.confirm.t,
          onPressed: controller.onSubmit,
        ),
        const FSizedBox(
          width: 40,
        ),
        FSecondaryButton(
          text: i18nBook.common.close.t,
          onPressed: controller.onPageClose,
        ),
      ],
    );
  }
}

class FSuggesionInputWidget extends FStatefulWidget implements FPage {
  @override
  FState<FStatefulWidget> createState() {
    return FSuggesionInputWidgetState();
  }

  @override
  String get pageName => 'FSuggesionInputWidget';
}

class FSuggesionInputWidgetState extends FState<FSuggesionInputWidget> {
  final controller = Get.find<ProfileCompleteController>();
  @override
  void initState() {
    super.initState();
  }

  void dispose() {
    super.dispose();
  }

  @override
  FWidget build(BuildContext context) {
    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 (val.isNotEmpty) {
                  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 [];
              }
              controller.state.pageIndex = 1;
              await controller.fetchHospital(pattern);
              var result = controller.state.hospitalDtoList.map(
                (e) => HospitalModel(
                  title: e.organizationName ?? '',
                ),
              );
              return result;
            },
            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);
                setState(() {});
                FocusScope.of(context)
                    .requestFocus(controller.hospitalFocusNode);
                return;
              }
              if (controller.state.hospitalName != data.title) {
                controller.state.hospitalName = data.title;
                controller.setHospitalName();
              }
            },
            noItemsFoundText: i18nBook.user.getOrganizationFailed.t,
          );
        },
      ),
    );
  }
}
