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/states/states.dart';
import 'package:flyinsono/pages/remedical/consultation/controller.dart';
import 'package:get/get.dart';

///关联病人界面
class AssociatPatient extends FisView<ConsultationController> implements FPage {
  /// 未登记的病人code
  final String? patientCode;
  @override
  final String pageName;
  AssociatPatient(
    this.patientCode, {
    this.pageName = 'AssociatPatient',
    Key? key,
  }) : super(key: key);

  @override
  FWidget build(BuildContext context) {
    return FSimpleDialog(
        title: _buildAssocicatedPatientTitle(),
        children: [
          _buildPatientSearchArea(),
        ],
        okString: i18nBook.common.confirm.t,
        cancelString: i18nBook.common.cancel.t,
        onCancel: () => controller.closeSetVaildPatient(),
        bottomButton: _buildPatientPageOperations());
  }

  FWidget _buildAssocicatedPatientTitle() {
    return FText(
      i18nBook.remedical.associatePatient.t,
      style: TextStyle(
        color: Colors.white,
        fontSize: 18,
      ),
    );
  }

  FWidget _buildPatientSearchArea() {
    return FContainer(
      width: 400,
      height: 500,
      child: FContainer(
        child: FColumn(
          children: [
            FContainer(
              margin: EdgeInsets.symmetric(horizontal: 15, vertical: 8),
              color: Colors.white,
              child: FRow(
                children: [
                  FExpanded(
                    child: FContainer(
                      height: 38,
                      child: FRow(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          _buildPatientSearchInput(),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
            PatientTobeAssociatedSelector(
              patientCode,
            ),
          ],
        ),
        //
      ),
    );
  }

  FWidget _buildPatientSearchInput() {
    return FBorderInput(
      hintSize: 16,
      contentSize: 16,
      focusNode: controller.searchPatientFocusNode,
      maxLength: 20,
      borderColor: Color.fromRGBO(234, 234, 234, 1),
      suffixIcon: FMaterial(
        color: Colors.transparent,
        child: FIconButton(
          businessParent: this,
          name: "search",
          onPressed: () =>
              controller.patientInfoController.getAssociatPatients(this),
          icon: FIcon(
            Icons.search,
          ),
        ),
      ),
      height: 38,
      hintText: i18nBook.remedical.patientNamePlaceholder.t,
      onChanged: (value) => controller.state.patientName = value,
    );
  }

  FWidget _buildPatientPageOperations() {
    return FContainer(
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(vertical: 15),
      child: FFlex(
        direction: Axis.horizontal,
        mainAxisSize: MainAxisSize.min,
        children: [
          FElevatedButton(
            businessParent: this,
            name: "confirm",
            onPressed: () => controller.patientInfoController.setVaildPatient(
              controller.state.setValidPatientRequest,
            ),
            style: ButtonStyle(
              padding: MaterialStateProperty.all(
                EdgeInsets.symmetric(
                  vertical: 15,
                  horizontal: 25,
                ),
              ),
            ),
            child: FText(i18nBook.common.confirm.t),
          ),
          FSizedBox(
            width: 20,
          ),
          FOutlinedButton(
            name: "cancel",
            businessParent: this,
            onPressed: () {
              controller.closeSetVaildPatient();
            },
            style: ButtonStyle(
              backgroundColor: MaterialStateProperty.all(
                Colors.white,
              ),
              padding: MaterialStateProperty.all(
                EdgeInsets.symmetric(vertical: 15, horizontal: 25),
              ),
            ),
            child: FText(
              i18nBook.common.cancel.t,
              style: TextStyle(
                color: Color.fromRGBO(61, 146, 252, 1),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

///待关联病人选择器
class PatientTobeAssociatedSelector extends FStatefulWidget {
  PatientTobeAssociatedSelector(this.patientCode, {Key? key})
      : super(
          key: key,
        );
  final String? patientCode;

  @override
  FState<PatientTobeAssociatedSelector> createState() =>
      _PatientTobeAssociatedSelectorState();
}

class _PatientTobeAssociatedSelectorState
    extends FState<PatientTobeAssociatedSelector> {
  int? selectIndex;
  final controller = Get.find<ConsultationController>();
  final ScrollController _scrollController = ScrollController();
  SetValidPatientRequest setValidPatientRequest = SetValidPatientRequest();
  @override
  FWidget build(BuildContext context) {
    return FObx(
      () => FContainer(
          height: 400,
          child: controller.state.associatPatientInfos.length == 0
              ? _buildNoneDataPlaceHodler()
              : _buildPatientList()),
    );
  }

  FWidget _buildNoneDataPlaceHodler() {
    return FCenter(
      child: FText(i18nBook.remedical.patientNameToAssociatePlaceholder.t),
    );
  }

  FWidget _buildPatientList() {
    return FAlwaysScrollListView(
      scrollController: _scrollController,
      child: QuickFWidget(ScrollConfiguration(
        behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
        child: FListView.builder(
          shrinkWrap: true,
          controller: _scrollController,
          itemCount: controller.state.associatPatientInfos.length,
          itemBuilder: (BuildContext context, int index) {
            return FMaterial(
              color: Colors.white,
              child: FInkWell(
                  onTap: () {
                    setState(
                      () {
                        selectIndex = index;
                        setValidPatientRequest.token = Store.user.token;
                        setValidPatientRequest.newPatientCode = controller
                            .state.associatPatientInfos[index]['patientCode'];
                        setValidPatientRequest.oldPatientCode =
                            widget.patientCode;
                        controller.state.setValidPatientRequest =
                            setValidPatientRequest;
                      },
                    );
                  },
                  child: _buildPatientItem(index)),
            );
          },
        ),
      )),
    );
  }

  FWidget _buildPatientItem(int index) {
    return FContainer(
      margin: EdgeInsets.symmetric(horizontal: 10),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(
            color: Color.fromRGBO(235, 235, 235, 1),
            width: 1,
          ),
        ),
      ),
      padding: EdgeInsets.all(10),
      child: FRow(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          FExpanded(
            child: FRow(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                FRow(
                  children: [
                    FSizedBox(
                      width: 15,
                    ),
                    FCircleAvatar(
                      radius: 25,
                      backgroundImage: _buildUserAvatarProvider(index),
                    ),
                    FSizedBox(
                      width: 20,
                    ),
                    _buildPatientTemplate(index),
                  ],
                ),
                FContainer(
                  width: 20,
                  height: 20,
                  decoration: BoxDecoration(
                    border: Border.all(
                      color: Color.fromRGBO(141, 141, 141, 1),
                      width: 0.5,
                    ),
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: _itemSelectedTemplate(index),
                ),
              ],
            ),
          ),
          FSizedBox(
            width: 15,
          ),
        ],
      ),
    );
  }

  _buildUserAvatarProvider(int index) {
    ImageProvider child;
    String headImgUrl =
        controller.state.associatPatientInfos[index]['headImgUrl'];
    headImgUrl.isEmpty
        ? child = AssetImage("assets/images/avatar_man.png")
        : child = NetworkImage(headImgUrl);
    return child;
  }

  _buildPatientTemplate(int index) {
    return FColumn(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        FText(
          '${controller.state.associatPatientInfos[index]['name']}',
          style: TextStyle(
            fontWeight: FontWeight.bold,
          ),
        ),
        FSizedBox(
          height: 8,
        ),
        FText('${controller.state.associatPatientInfos[index]['phone']}'),
      ],
    );
  }

  FWidget _itemSelectedTemplate(int index) {
    return selectIndex == index
        ? FContainer(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(20),
              color: Theme.of(context).primaryColor,
            ),
            child: FCenter(
              child: FContainer(
                child: FIcon(
                  Icons.check,
                  size: 15,
                  color: Colors.white,
                ),
              ),
            ),
          ) as FWidget
        : const FText('');
  }
}
