import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.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/mobile/names.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/views/mobile/confirm_application_page/widgets/add_participant.dart';
import 'package:flyinsono/views/mobile/confirm_application_page/widgets/bottom_sheet.dart';
import 'package:flyinsono/views/mobile/confirm_application_page/widgets/select_sheet.dart';
import 'package:flyinsono/views/mobile/confirm_application_page/widgets/time_value.dart';
import 'package:get/get.dart';
import 'package:fis_common/index.dart';
import 'index.dart';

class FConfirmApplicationPagePage
    extends FisView<ConfirmApplicationPageController> implements FPage {
  FConfirmApplicationPagePage({
    Key? key,
    this.pageName = 'ConfirmApplicationPagePage',
  }) : super(key: key);
  BuildContext? _context;

  ///父级节点
  final String pageName;
  @override
  FWidget build(BuildContext context) {
    _context = context;
    return FScaffold(
      backgroundColor: Colors.grey[100],
      appBar: FAppBar(
        backgroundColor: Colors.white,
        title: FText(
          i18nBook.realTimeConsultation.acceptInvitation.t,
          style: TextStyle(
            fontSize: 16,
            color: Colors.black,
            fontWeight: FontWeight.bold,
          ),
        ),
        elevation: 0,
        centerTitle: true,
        leading: _buildLeading(),
        actions: [
          FGestureDetector(
            name: "confirm",
            businessParent: this,
            onTap: () {
              controller.approveApplication();
            },
            child: FCenter(
              child: FRow(
                children: [
                  FText(
                    i18nBook.common.confirm.t,
                    style: TextStyle(
                      color: Colors.black,
                    ),
                  ),
                  FSizedBox(
                    width: 20,
                  )
                ],
              ),
            ),
          ),
        ],
      ),
      body: FSafeArea(
        child: FColumn(children: [
          FExpanded(
            child: FSingleChildScrollView(
              child: FContainer(
                margin: EdgeInsets.only(
                  top: 15,
                ),
                child: _buildMainStructure(),
              ),
            ),
          ),
        ]),
      ),
    );
  }

  //返回键
  FWidget _buildLeading() {
    return FIconButton(
      name: "back",
      businessParent: this,
      icon: FIcon(
        Icons.arrow_back_ios_new,
        size: 20,
        color: Colors.black,
      ),
      onPressed: () {
        router.replace(
          MobileRouteNames.RealTimeRemedical.ConsultationDetail,
          parameters: {
            'consultationCode': controller.state.consultationCode,
          },
        );
      },
    );
  }

  /// 主体结构
  FWidget _buildMainStructure() {
    return FColumn(
      children: [
        _buildConfirmApplicationClickItem(
          i18nBook.realTimeConsultation.startTime.t,
          FObx(
            () => _buildTimeItemValue(
              controller.getDateStringOrNull(
                controller.state.startDateTime,
              ),
            ),
          ),
          () => controller.showDatePickerForDateTime(
            _context!,
            (selectTime) => controller.selectStartTime(selectTime),
            controller.state.startDateTime,
          ),
          true,
        ),
        _buildConfirmApplicationClickItem(
          i18nBook.realTimeConsultation.endTime.t,
          FObx(
            () => _buildTimeItemValue(
              controller.getDateStringOrNull(
                controller.state.endDateTime,
              ),
            ),
          ),
          () => controller.showDatePickerForDateTime(
            _context!,
            (selectTime) => controller.selectEndTime(selectTime),
            controller.state.endDateTime,
          ),
          true,
        ),

        /// 会诊专家
        FObx(
          () => _expertUserNameOrSelect(
            controller.state.consultationDetail.expertUserName,
          ),
        ),

        _buildConfirmApplicationItem(
          i18nBook.realTimeConsultation.assistantPhysician.t,
          FObx(
            () => _buildOrdinaryItemValue(
              controller.state.assistantPhysicianName,
            ),
          ),
          false,
          true,
        ),
        _buildConfirmApplicationClickItem(
          i18nBook.realTimeConsultation.participants.t,
          _buildParticipants(),
          () {
            Get.to(
              () => FAddParticipant(
                hasAssistantPhysicianCode:
                    controller.state.assistantPhysicianCode == '',
              ),
            );
          },
        ),
        _buildConfirmApplicationItem(
          i18nBook.realTimeConsultation.consultationDescription.t,
          FObx(
            () => _buildTextAreaLine(
              controller.state.consultationDescription ?? "",
              _buildTextArea(),
            ),
          ),
          false,
        ),
        _buildConfirmApplicationClickItem(
          i18nBook.realTimeConsultation.reminderTime.t,
          FObx(
            () => _buildItemValue(
              controller.state.currectReminderTimeString,
              controller.state.currectSelectedReminderTimeIndexList,
              controller.state.reminderTimeList,
              (value) {
                {
                  List<ConsultationReminderTimeEnum>
                      _currectSelectedReminderTimeList = [];
                  controller.state.currectSelectedReminderTimeIndexList = value;
                  for (int i in value) {
                    _currectSelectedReminderTimeList.add(
                      controller.state.reminderTimeList[i].value,
                    );
                  }
                  controller.state.currectSelectedReminderTimeList =
                      _currectSelectedReminderTimeList;
                }
                ;
              },
            ),
          ),
        ),
        _buildConfirmApplicationClickItem(
          i18nBook.realTimeConsultation.reminderMehod.t,
          FObx(
            () => _buildItemValue(
              controller.state.currectReminderMethodString,
              controller.state.currectSelectedReminderMethodIndexList,
              controller.state.reminderMethodList,
              (value) {
                {
                  controller.state.currectSelectedReminderMethodIndexList =
                      value;
                  List<ConsultationReminderMode> _reminderMethod = [];
                  for (int i in value) {
                    _reminderMethod.add(
                      controller.state.reminderMethodList[i].value,
                    );
                  }
                  controller.state.currectSelectedReminderMethodList =
                      _reminderMethod;
                }
              },
            ),
          ),
        ),
        _buildConfirmApplicationItem(
          i18nBook.realTimeConsultation.operator.t,
          FObx(
            () => _buildOrdinaryItemValue(
              controller.state.consultationDetail.operateUserName ?? '',
            ),
          ),
          true,
          true,
        ),
      ],
    );
  }

  /// 主管专家下拉列表 这边是单选下拉框
  FWidget _expertUserNameOrSelect(String? expertUserName) {
    if (expertUserName == null || expertUserName.isEmpty) {
      return _buildConfirmApplicationClickItem(
        i18nBook.notification.expertName.t,
        FObx(
          () {
            return _buildItemValue(
              controller.state.expertUserCode,
              [],
              controller.state.expertList,
              (value) => controller.selectExpertUserCode(value),
              false,
            );
          },
        ),
      );
    } else {
      return _buildConfirmApplicationItem(
        i18nBook.notification.expertName.t,
        FObx(() {
          return _buildOrdinaryItemValue(
            controller.state.consultationDetail.expertUserName,
          );
        }),
        true,
        true,
      );
    }
  }

  /// 当前时间值
  FWidget _buildTimeItemValue(String? value) {
    return FRow(
      mainAxisAlignment: MainAxisAlignment.end,
      mainAxisSize: MainAxisSize.max,
      children: [
        FTimeValue(
          hintText: i18nBook.common.Select.t,
          value: value,
          tipTitle: i18nBook.remedical.pleaseSelect.translate(
            [i18nBook.remedical.transferOrganization.t],
          ),
        ),
      ],
    );
  }

  /// 当前普通组件值
  FWidget _buildOrdinaryItemValue(
    String? value,
  ) {
    return FRow(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        FExpanded(
          child: FContainer(
            padding: EdgeInsets.symmetric(vertical: 15),
            child: FText(
              value ?? '',
              textAlign: TextAlign.right,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ),
      ],
    );
  }

  FWidget _buildTextAreaLine(String value, FWidget? textArea) {
    return FRow(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        FExpanded(
          child: FInkWell(
            onTap: () {
              FBottomSheet.showBottomSheet(
                _context!,
                textArea!,
                () {
                  router.back();
                },
              );
            },
            child: FContainer(
              padding: EdgeInsets.symmetric(vertical: 15),
              child: FRow(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  FExpanded(
                    child: FObx(
                      () => FText(
                        controller.state.consultationDescription.isNullOrEmpty
                            ? i18nBook.common.input.translate([
                                /// TODO:[Gavin] 多语言-UI-整合
                                i18nBook.isCurrentChinese
                                    ? i18nBook.realTimeConsultation
                                        .consultationDescription.t
                                    : ""
                              ])
                            : controller.state.consultationDescription!,
                        textAlign: TextAlign.right,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          fontSize: 14,
                          color: Color.fromRGBO(155, 155, 155, 1),
                        ),
                      ),
                    ),
                  ),
                  FIcon(
                    Icons.edit_document,
                    color: Color.fromRGBO(164, 164, 164, 1),
                  )
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 单行值和多选组件
  ///
  /// [value] 当前当行的值或者多行的字符串
  /// [valueList] 多行的值 用来反显
  /// [sourceList] 当前数据源
  /// [valueCallback] 值回调
  /// [isMultiSelect] 是否多选
  FWidget _buildItemValue(
    String? value,
    List<int>? valueList,
    List<FSelectSheetModel> sourceList,
    ValueCallback valueCallback, [
    bool? isMultiSelect = true,
  ]) {
    return FRow(
      children: [
        FExpanded(
          child: FSelectSheet<FSelectSheetModel, String>(
            hintText: i18nBook.common.Select.t,
            source: sourceList,
            value: value,
            valueList: valueList,
            isMultiSelect: isMultiSelect,
            optionLabelExtractor: (data) => data.title,
            optionValueExtractor: (data) => data.value,
            onChange: (value) => valueCallback(value),
          ),
        ),
      ],
    );
  }

  /// 参与人员的组件
  FWidget _buildParticipants() {
    return FContainer(
      padding: EdgeInsets.symmetric(vertical: 15),
      child: FRow(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          FExpanded(
            child: FObx(() {
              return FText(
                controller.state.isParticipantsListStringNullOrEmpty
                    ? i18nBook.common.Select.t
                    : controller.state.participantsListString!,
                style: controller.state.isParticipantsListStringNullOrEmpty
                    ? TextStyle(
                        fontSize: 14,
                        color: Color.fromRGBO(155, 155, 155, 1),
                      )
                    : TextStyle(),
                textAlign: TextAlign.right,
                overflow: TextOverflow.ellipsis,
              );
            }),
          ),
          FIcon(
            Icons.chevron_right,
            color: Color.fromRGBO(164, 164, 164, 1),
          ),
        ],
      ),
    );
  }

  /// 点击的item
  FWidget _buildConfirmApplicationClickItem(
    String title,
    FWidget referralItem, [
    Function? openPicker,
    bool? isRequired = false,
    bool? isNeedOffsetRight = false,
  ]) {
    return FInkWell(
      onTap: () => openPicker?.call() ?? () {},
      child: _buildConfirmApplicationItem(
          title, referralItem, isRequired, isNeedOffsetRight),
    );
  }

  /// 普通展示数据的item
  FWidget _buildConfirmApplicationItem(
    String title,
    FWidget referralItem, [
    bool? isRequired,
    bool? isNeedOffsetRight = false,
  ]) {
    return _buildCommonItem(
      [
        FContainer(
          width: 120,
          child: FRow(
            children: [
              FText(title),
              isRequired ?? false
                  ? FText(
                      '*',
                      style: TextStyle(color: Colors.red),
                    )
                  : FSizedBox(),
            ],
          ),
        ),
        FExpanded(
          child: FRow(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              FExpanded(child: referralItem),
              if (isNeedOffsetRight!)
                FSizedBox(
                  width: 24,
                ),
            ],
          ),
        )
      ],
    );
  }

  /// 当前最常用的item
  FWidget _buildCommonItem(List<FWidget> items) {
    return FContainer(
      margin: EdgeInsets.symmetric(
        horizontal: 15,
      ),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(
            color: Color.fromRGBO(211, 211, 211, 1),
          ),
        ),
      ),
      child: FRow(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: items.toList(),
      ),
    );
  }

  FWidget _buildTextArea() {
    return FContainer(
      margin: EdgeInsets.all(15),
      child: FTextField(
        maxLines: 3,
        maxLength: 100,
        controller: controller.descriptionController,
        onChanged: (val) {
          controller.state.consultationDescription = val;
        },
        decoration: InputDecoration(
          hintStyle: TextStyle(
            fontSize: 14,
            color: Color.fromRGBO(155, 155, 155, 1),
          ),
          hintText: i18nBook.common.input.translate(
              [i18nBook.realTimeConsultation.consultationDescription.t]),
          fillColor: Colors.white.withOpacity(0.5),
          enabledBorder: const OutlineInputBorder(
            borderSide: BorderSide(
              color: Color.fromRGBO(230, 230, 230, 1),
              style: BorderStyle.solid,
            ),
          ),
          focusedBorder: const OutlineInputBorder(
            borderSide: BorderSide(
              width: 0.5,
              style: BorderStyle.solid,
            ),
          ),
          filled: true,
        ),
      ),
    );
  }
}
