import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/services/index.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/pages/upload/image_upload_card.dart';
import 'package:flyinsono/pages/user/user_id_auth_apply/selected_skilledarealable.dart';
import 'package:flyinsono/pages/user/user_id_auth_apply/widgets/dialog_header.dart';
import 'package:flyinsono/pages/user/user_id_auth_apply/widgets/image_display_box.dart';
import 'package:flyinsono/pages/user/user_id_auth_apply/widgets/mobile_appbar.dart';
import 'package:flyinsono/pages/user/user_id_auth_apply/widgets/selected_labels.dart';
import 'package:get/get.dart';
import 'index.dart';
import 'widgets/dialog_body.dart';

///申请认证页面
class UserIdAuthApplyPage extends FisView<UserIdAuthApplyController>
    implements FPage {
  UserIdAuthApplyPage({
    Key? key,
  }) : super(key: key);

  @override
  final String pageName = 'UserIdAuthApplyPage';

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

class _MobileLayout extends FisView<UserIdAuthApplyController>
    with _ModifyAlert
    implements FWidget {
  ///父级节点
  final FPage businessParent;
  final ScrollController _scrollController = ScrollController();
  _MobileLayout(this.businessParent);

  @override
  FWidget build(BuildContext context) {
    return FScaffold(
      appBar: MobileAppBar(),
      bottomNavigationBar: FObx(() {
        if (controller.state.editable) {
          if (controller.state.inEditing) {
            return FBottomSubmitButton(
                businessParent: businessParent,
                name: "AuthApply",
                title: i18nBook.common.submit.t,
                onPressed: () {
                  controller.submitFormApply();
                });
          }
          if (controller.state.applyState == ApplyStateEnum.Refused) {
            return FBottomSubmitButton(
              businessParent: businessParent,
              name: "AuthApply",
              title: i18nBook.common.modify.t,
              onPressed: () {
                modifyApply(controller, businessParent);
              },
            );
          }
        }
        return FSizedBox();
      }),
      body: FContainer(
        color: Colors.white,
        padding: EdgeInsets.only(left: 20.sp, right: 20.sp),
        child: FAlwaysScrollListView(
          scrollController: _scrollController,
          child: QuickFWidget(ScrollConfiguration(
            behavior:
                ScrollConfiguration.of(context).copyWith(scrollbars: false),
            child: FListView(
              controller: _scrollController,
              padding: EdgeInsets.symmetric(vertical: 8.sp),
              //  crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _buildIdCardPanel(),
                _buildDoctorPanel(),
                FObx(() {
                  return _buildRoleLable();
                }),
                FObx(() {
                  if (!controller.state.inEditing) {
                    return FColumn(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        FRow(
                          children: [
                            FText(i18nBook.user.verificationStatus.t,
                                style: TextStyle(fontSize: 16.sp)),
                            FSizedBox(width: 24.w),
                            FText(
                              controller.state.applyStateDescription,
                              style: TextStyle(
                                fontSize: 16.sp,
                                color: controller.state.applyPassed
                                    ? Colors.green
                                    : Colors.red,
                              ),
                            ),
                          ],
                        ),
                        FSizedBox(height: 15.sp),
                        if (controller.state.applyState ==
                            ApplyStateEnum.Refused) ...[
                          FRow(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              FText(i18nBook.user.refuseReason.t,
                                  style: TextStyle(fontSize: 16.sp)),
                              FSizedBox(width: 24.w),
                              FExpanded(
                                child: FText(
                                  controller.state.refuseNote,
                                  overflow: TextOverflow.ellipsis,
                                  maxLines: 10,
                                  style: TextStyle(
                                      fontSize: 16.sp, color: Colors.red),
                                ),
                              ),
                            ],
                          ),
                          FSizedBox(height: 15.sp),
                        ],
                      ],
                    );
                  }
                  return FSizedBox();
                }),
              ],
            ),
          )),
        ),
      ),
    );
  }

  ///上传身份证区域
  FWidget _buildIdCardPanel() {
    return FObx(
      () {
        if (!controller.roleInfo.isNeedIdCard) return FSizedBox();
        // 需要上传
        return FColumn(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            FText(i18nBook.user.idCard.t,
                style: TextStyle(fontSize: 16.sp, color: Colors.black)),
            FContainer(
              margin: EdgeInsets.only(top: 5.sp),
              child: FObx(() {
                controller.state.inEditing;
                if (controller.state.inEditing) {
                  return ImageUploadCard(
                    originImgUrl: controller.state.idCardFront,
                    hintText: i18nBook.user.uploadIdCardFrontSide.t,
                    isShowAddIcon: true,
                    onUploaded: (url) {
                      Future.microtask(() {
                        controller.state.idCardFront = url;
                      });
                    },
                    onDeleted: () {
                      controller.state.idCardFront = '';
                    },
                    width: double.infinity,
                    height: 170.w,
                  );
                } else {
                  if (controller.state.idCardFront.isEmpty) return FSizedBox();
                  return ImageDisplayBox(
                    url: controller.state.idCardFront,
                    height: 170.w,
                    width: double.infinity,
                  );
                }
              }),
            ),
            FContainer(
              margin: EdgeInsets.only(top: 5.sp),
              child: FObx(() {
                if (controller.state.inEditing) {
                  return ImageUploadCard(
                    isShowAddIcon: true,
                    originImgUrl: controller.state.idCardBack,
                    hintText: i18nBook.user.uploadIdCardReverseSide.t,
                    onUploaded: (url) {
                      Future.microtask(() {
                        controller.state.idCardBack = url;
                      });
                    },
                    onDeleted: () {
                      controller.state.idCardBack = '';
                    },
                    width: double.infinity,
                    height: 170.w,
                  );
                } else {
                  if (controller.state.idCardBack.isEmpty) return FSizedBox();
                  return ImageDisplayBox(
                    url: controller.state.idCardBack,
                    height: 170.w,
                    width: double.infinity,
                  );
                }
              }),
            ),
            FSizedBox(height: 15.sp),
          ],
        );
      },
    );
  }

  ///上传医师证明区域
  FWidget _buildDoctorPanel() {
    return FObx(
      () {
        if (!controller.roleInfo.isNeedDocCard) return FSizedBox();
        // 需要上传

        return FColumn(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            FText(i18nBook.user.doctorLicense.t,
                style: TextStyle(fontSize: 16.sp)),
            FContainer(
              margin: EdgeInsets.only(top: 5.sp),
              child: FObx(() {
                if (controller.state.inEditing) {
                  return ImageUploadCard(
                    isShowAddIcon: true,
                    originImgUrl: controller.state.doctorCard,
                    hintText: i18nBook.user.uploaddoctorLicense.t,
                    onUploaded: (url) {
                      Future.microtask(() {
                        controller.state.doctorCard = url;
                      });
                    },
                    onDeleted: () {
                      controller.state.doctorCard = '';
                    },
                    width: double.infinity,
                    height: 170.w,
                  );
                } else {
                  if (controller.state.doctorCard.isEmpty) return FSizedBox();
                  return ImageDisplayBox(
                    url: controller.state.doctorCard,
                    height: 170.w,
                    width: double.infinity,
                  );
                }
              }),
            ),
            FSizedBox(height: 15.sp),
          ],
        );
      },
    );
  }

  ///角色标签
  FWidget _buildRoleLable() {
    if (controller.roleInfo.fieldShowType == RoleShowTypeEnum.ISShow) {
      return FColumn(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          FText(i18nBook.user.skilledArea.t, style: TextStyle(fontSize: 16.sp)),
          SelectedLabels(),
          FContainer(
            margin: EdgeInsets.only(top: 5.sp),
            child: FObx(() {
              if (controller.state.applyState == ApplyStateEnum.NotApply ||
                  controller.state.inEditing)
                return FElevatedButton(
                    child: FText(i18nBook.common.add.t),
                    onPressed: () async {
                      await SelectedSkilledAreaLable.open(controller);
                    },
                    businessParent: businessParent,
                    name: i18nBook.common.add.t);
              else
                return FContainer();
            }),
          ),
          FSizedBox(height: 15.sp),
        ],
      );
    }
    return FSizedBox();
  }
}

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

  _DesktopLayout(this.businessParent);
  @override
  FWidget build(BuildContext context) {
    return FDialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
      child: FContainer(
        width: 700,
        child: FColumn(
          mainAxisSize: MainAxisSize.min,
          children: [
            UploadUserIdDialogHeader(),
            UploadUserIdBody(),
            FContainer(
              decoration: BoxDecoration(
                border: Border(
                  top: BorderSide(
                    color: Theme.of(context).dividerColor,
                    width: 0.5,
                  ),
                ),
              ),
            ),
            _buildOperateRow(),
          ],
        ),
      ),
    );
  }

  ///底部操作按钮（提交、关闭）
  FWidget _buildOperateRow() {
    final fontFamily = FTheme.ins.localeSetting.fontFamily;
    return FContainer(
      padding: const EdgeInsets.only(top: 15, bottom: 15),
      child: FObx(
        () => FRow(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (controller.state.editable)
              FElevatedButton(
                name: "submitFormApply",
                businessParent: businessParent,
                onPressed: () {
                  if (controller.state.inEditing) {
                    controller.submitFormApply();
                  } else {
                    modifyApply(controller, businessParent);
                  }
                },
                child: FText(controller.state.inEditing
                    ? i18nBook.common.submit.t
                    : i18nBook.common.modify.t),
                style: ElevatedButton.styleFrom(
                  elevation: 0,
                  textStyle: TextStyle(fontSize: 14, fontFamily: fontFamily),
                  padding: const EdgeInsets.symmetric(
                    vertical: 15,
                    horizontal: 25,
                  ),
                ),
              ),
            const FSizedBox(width: 20),
            FOutlinedButton(
              businessParent: businessParent,
              name: "back",
              onPressed: () {
                router.back();
              },
              child: FText(controller.state.editable
                  ? i18nBook.common.cancel.t
                  : i18nBook.common.close.t),
              style: OutlinedButton.styleFrom(
                foregroundColor: FTheme.ins.colorScheme.primary,
                textStyle: TextStyle(fontSize: 14, fontFamily: fontFamily),
                padding: const EdgeInsets.symmetric(
                  vertical: 15,
                  horizontal: 25,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _ModifyAlert {
  ///修改申请
  void modifyApply(UserIdAuthApplyController controller,
      FInteractiveContainer businessParent) {
    FConfirmAlert.show(
      businessParent: businessParent,
      context: Get.context!,
      title: i18nBook.user.editTip.t,
      subTitle: i18nBook.user.useCurrentSelectedRole.t,
      confrimLabel: i18nBook.common.yes.t,
      cancelLabel: i18nBook.common.no.t,
      onConfirm: () {
        controller.state.inEditing = true;
      },
      onCancel: controller.reselectRole,
    );
  }
}
