import 'package:fis_jsonrpc/services/appletAPI.m.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/views/wechat_mini_program/wx_public_widgets/wx_scaffold.dart';
import 'package:flyinsono/views/wechat_mini_program/wx_public_widgets/wx_screen_direction_lock.dart';

import 'index.dart';

class WxConsultationCreatePage extends FisView<WxConsultationCreateController> {
  const WxConsultationCreatePage({Key? key}) : super(key: key);
  // 主视图
  Widget _buildView(BuildContext context) {
    return Form(
      key: controller.formKey,
      child: ListView(
        padding: EdgeInsets.all(16),
        children: <Widget>[
          _buildTextDividingLine("患者信息"),
          KeepAliveTextField(
            labelText: '病人名称',
            validator: controller.validateName,
            onSaved: (value) => controller.patientName = value,
          ),
          Container(
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey),
              borderRadius: BorderRadius.circular(5),
            ),
            padding: EdgeInsets.symmetric(horizontal: 10, vertical: 15),
            margin: EdgeInsets.only(bottom: 10),
            child: InkWell(
              onTap: () async {
                final DateTime? picked = await showDatePicker(
                  context: context,
                  initialDate: controller.birthday,
                  firstDate: DateTime(1900),
                  lastDate: DateTime(2100),
                );
                if (picked != null && picked != controller.birthday)
                  controller.birthday = picked;
              },
              child: Row(
                children: <Widget>[
                  Text(
                    '出生日期',
                  ),
                  Expanded(child: Container()),
                  Text(controller.birthday.toString().substring(0, 10)),
                  FSizedBox(width: 10),
                  Icon(Icons.date_range),
                ],
              ),
            ),
          ),
          KeepAliveTextField(
            labelText: '年龄',
            validator: controller.validateAge,
            onSaved: (value) => controller.patientAge = value,
            keyboardType: TextInputType.number,
          ),
          Container(
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey),
              borderRadius: BorderRadius.circular(5),
            ),
            padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
            margin: EdgeInsets.only(bottom: 10),
            child: Row(
              children: <Widget>[
                Text('性别'),
                Expanded(child: Container()),
                Radio(
                  value: 0,
                  groupValue: controller.patientSex,
                  onChanged: (value) => controller.patientSex = value as int,
                ),
                Text('男'),
                Radio(
                  value: 1,
                  groupValue: controller.patientSex,
                  onChanged: (value) => controller.patientSex = value as int,
                ),
                Text('女'),
              ],
            ),
          ),
          KeepAliveTextField(
            labelText: '手机号码',
            validator: controller.validateContactInfo,
            onSaved: (value) => controller.contactInfo = value,
            keyboardType: TextInputType.phone,
          ),
          KeepAliveTextField(
            labelText: '病人ID',
            validator: controller.validatePatientID,
            onSaved: (value) => controller.patientID = value,
          ),
          KeepAliveTextField(
            labelText: '既往病史',
            validator: controller.validateHistory,
            maxLines: 3,
            maxLength: 200,
            buildCounter: _buildCounter,
            onSaved: (value) => controller.history = value,
          ),
          KeepAliveTextField(
            labelText: '初步诊断',
            validator: controller.validatePrimaryDiagnosis,
            maxLines: 3,
            maxLength: 200,
            buildCounter: _buildCounter,
            onSaved: (value) => controller.primaryDiagnosis = value,
          ),
          _buildTextDividingLine("会诊信息"),
          DropdownButtonFormField<OrganBaseInfo>(
            decoration: InputDecoration(
              labelText: '会诊医院',
              border: OutlineInputBorder(),
            ),
            value: controller.hospital,
            items: controller.hospitalList
                .map((e) => DropdownMenuItem<OrganBaseInfo>(
                      child: Text(e.name ?? ''),
                      value: e,
                    ))
                .toList(),
            // onChanged: (value) => controller.hospital = value,
            onChanged: controller.updateHospital,
            validator: controller.validateHospitalId,
          ),
          SizedBox(height: 10),
          DropdownButtonFormField<DoctorInfo>(
            decoration: InputDecoration(
              labelText: '会诊专家',
              border: OutlineInputBorder(),
            ),
            value: controller.expert,
            items: controller.expertList
                .map((e) => DropdownMenuItem<DoctorInfo>(
                      child: Text(e.displayName ?? ''),
                      value: e,
                    ))
                .toList(),
            onChanged: (value) => controller.expert = value,
            validator: controller.validateExpertId,
          ),
          SizedBox(height: 10),
          KeepAliveTextField(
            labelText: '扫查医生',
            validator: controller.validateScanDoctorName,
            onSaved: (value) => controller.scanDoctorName = value,
          ),
          DropdownButtonFormField<String>(
            decoration: InputDecoration(
              labelText: '检查部位',
              border: OutlineInputBorder(),
            ),
            value: controller.inspectionItems,
            items: controller.inspectionItemsList
                .map((e) => DropdownMenuItem<String>(
                      child: Text(e),
                      value: e,
                    ))
                .toList(),
            onChanged: (value) => controller.inspectionItems = value as String,
            validator: controller.validateInspectItems,
          ),
          SizedBox(height: 10),
          DropdownButtonFormField<TerminalInfo>(
            decoration: InputDecoration(
              labelText: '设备型号',
              border: OutlineInputBorder(),
            ),
            value: controller.deviceModel,
            items: controller.deviceModelList
                .map((e) => DropdownMenuItem<TerminalInfo>(
                      child: Text(e.model ?? ''),
                      value: e,
                    ))
                .toList(),
            onChanged: (value) => controller.deviceModel = value,
            validator: controller.validateDeviceModel,
          ),
          SizedBox(height: 10),
          Container(
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey),
              borderRadius: BorderRadius.circular(5),
            ),
            padding: EdgeInsets.symmetric(horizontal: 10, vertical: 15),
            child: InkWell(
              onTap: () async {
                final DateTime? picked = await showDatePicker(
                  context: context,
                  initialDate: controller.consultationDate,
                  firstDate: DateTime(1900),
                  lastDate: DateTime(2100),
                );
                if (picked != null && picked != controller.consultationDate)
                  controller.consultationDate = picked;
              },
              child: Row(
                children: <Widget>[
                  Text(
                    '会诊日期',
                  ),
                  Expanded(child: Container()),
                  Text(controller.consultationDate.toString().substring(0, 10)),
                  FSizedBox(width: 10),
                  Icon(Icons.date_range),
                ],
              ),
            ),
          ),
          SizedBox(height: 20),
        ],
      ),
    );
  }

  Widget _buildTextDividingLine(String title) {
    return Container(
      margin: EdgeInsets.only(top: 0, bottom: 15),
      child: Row(
        children: [
          Container(
            height: 1,
            width: 16,
            color: Color.fromARGB(255, 136, 136, 136),
          ),
          Container(
            margin: EdgeInsets.symmetric(horizontal: 8),
            child: FText(
              title,
              style: TextStyle(
                fontSize: 14,
                // fontWeight: FontWeight.bold,
                color: Color.fromARGB(255, 136, 136, 136),
              ),
            ),
          ),
          Expanded(
            child: FContainer(
              height: 1,
              width: 8,
              color: Color.fromARGB(255, 136, 136, 136),
            ),
          ),
        ],
      ),
    );
  }

  @override
  FWidget build(BuildContext context) {
    return FisBuilder<WxConsultationCreateController>(
      builder: (_) {
        return WxScreenDirectionLock(
            direction: ScreenDirection.vertical,
            page: WxScaffold(
              body: Column(
                children: [
                  Expanded(child: _buildView(context)),
                  Container(
                    padding: EdgeInsets.all(10),
                    color: Color.fromARGB(255, 247, 247, 247),
                    child: InkWell(
                      onTap: () {
                        controller.handleSubmit();
                      },
                      child: Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(5),
                            color: Colors.blue,
                          ),
                          padding: EdgeInsets.all(10),
                          child: Center(
                              child: Text(
                            '提交',
                            style: TextStyle(color: Colors.white),
                          ))),
                    ),
                  ),
                ],
              ),
              title: "创建会诊",
              parentRoute: MobileRouteNames.Wechat.MiniProgramConsultation,
            ));
      },
    );
  }

  /// 字数统计
  Widget _buildCounter(BuildContext context,
      {int? currentLength, int? maxLength, bool? isFocused}) {
    if (currentLength == null || maxLength == null) {
      return Text('');
    }
    return Text(
      '$currentLength/$maxLength',
      style: TextStyle(fontSize: 10),
    );
  }
}

/// 重写不会被销毁的 TextField 控件
class KeepAliveTextField extends StatefulWidget {
  final String labelText;
  final String? Function(String?)? validator;
  final void Function(String?)? onSaved;
  final TextInputType? keyboardType;
  final int? maxLength;
  final int? maxLines;
  final Widget? Function(BuildContext,
      {required int currentLength,
      required bool isFocused,
      required int? maxLength})? buildCounter;
  KeepAliveTextField({
    Key? key,
    required this.labelText,
    this.validator,
    this.onSaved,
    this.keyboardType,
    this.maxLength,
    this.maxLines = 1,
    this.buildCounter,
  }) : super(key: key);
  @override
  _KeepAliveTextFieldState createState() => _KeepAliveTextFieldState();
}

class _KeepAliveTextFieldState extends State<KeepAliveTextField>
    with AutomaticKeepAliveClientMixin<KeepAliveTextField> {
  // 创建 TextEditingController实例并在dispose时释放资源
  TextEditingController _textEditingController = TextEditingController();

  @override
  void dispose() {
    _textEditingController.dispose();
    super.dispose();
  }

  // 实现 wantKeepAlive 方法并返回true，这样就能让子项保持活动状态
  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context); // 确保将调用super.build(context)

    return Container(
      margin: EdgeInsets.only(bottom: 10),
      child: TextFormField(
        controller: _textEditingController,
        decoration: InputDecoration(
          labelText: widget.labelText,
          border: OutlineInputBorder(),
        ),
        validator: widget.validator,
        onSaved: widget.onSaved,
        keyboardType: widget.keyboardType,
        maxLines: widget.maxLines,
        maxLength: widget.maxLength,
        buildCounter: widget.buildCounter,
      ),
    );
  }
}
