import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/services/appletAPI.m.dart';
import 'package:fis_measure/define.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/widgets/scroll/refreshIndicator.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flyinsono/architecture/router/mobile/names.dart';
import 'package:flyinsono/views/wechat_mini_program/wx_public_widgets/search_field.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 WxConsultationPage extends FisView<WxConsultationController> {
  const WxConsultationPage({Key? key}) : super(key: key);

  @override
  FWidget build(BuildContext context) {
    return FisBuilder<WxConsultationController>(
      builder: (_) {
        return WxScreenDirectionLock(
            direction: ScreenDirection.vertical,
            page: WxScaffold(
              title: "预约会诊",
              parentRoute: MobileRouteNames.Wechat.MiniProgramHome,
              body: FColumn(
                // 此处反向构建列表，为了让搜索栏阴影后渲染，否则阴影会被列表项遮挡
                verticalDirection: VerticalDirection.up,
                children: [
                  FExpanded(
                    child: _buildListView(),
                  ),
                  _buildHeadBar(),
                ],
              ),
            ));
      },
    );
  }

  /// 新建按钮
  FWidget _buildAddButton() {
    return FContainer(
      decoration: BoxDecoration(
        border: Border.all(
          color: Color.fromARGB(255, 84, 144, 249),
        ),
        borderRadius: BorderRadius.circular(8),
      ),
      margin: EdgeInsets.only(right: 8, top: 8, bottom: 8),
      height: 44,
      width: 44,
      clipBehavior: Clip.antiAlias,
      child: FMaterial(
        color: Color.fromARGB(255, 84, 144, 249),
        child: FInkWell(
          highlightColor: Color.fromARGB(255, 49, 125, 255),
          onTap: () {
            controller.handleCreateConsultation();
          },
          child: FCenter(
            child: FIcon(
              Icons.add,
              color: Color.fromARGB(255, 241, 241, 241),
            ),
          ),
        ),
      ),
    );
  }

  /// 构建会诊列表卡片
  FWidget _buildConsultationItem(
      {required int index,
      required ConsultationInfo info,
      required VoidCallback onTap}) {
    return FInkWell(
      onTap: onTap,
      child: FContainer(
        margin: EdgeInsets.all(10),
        decoration: BoxDecoration(
          color: Colors.grey[200],
          borderRadius: BorderRadius.circular(8),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.2),
              blurRadius: 10,
              spreadRadius: 0,
              offset: Offset(1, 1), // changes position of shadow
            ),
          ],
        ),
        child: FColumn(
          children: [
            FRow(
              children: [
                FContainer(
                  margin: EdgeInsets.only(left: 10, top: 10),
                  child: FText(
                    '会诊时间',
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey[600],
                    ),
                  ),
                ),
                FContainer(
                  margin: EdgeInsets.only(left: 10, top: 10),
                  child: FText(
                    info.consultationDate.toString().substring(0, 16),
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey[600],
                    ),
                  ),
                ),
                FExpanded(child: FContainer()),
                FContainer(
                  margin: EdgeInsets.only(right: 10, top: 10),
                  child: FText(
                    _getConsultationStatusText(info.state),
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey[600],
                    ),
                  ),
                ),
              ],
            ),
            FRow(
              children: [
                FExpanded(
                  child: FColumn(
                    children: [
                      FRow(
                        children: [
                          FExpanded(
                            child: FColumn(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                FContainer(
                                  margin: EdgeInsets.only(left: 10, top: 8),
                                  child: FText(
                                    info.patientName ?? '',
                                    style: TextStyle(
                                      fontSize: 18,
                                      fontWeight: FontWeight.bold,
                                      color: Color.fromARGB(255, 77, 77, 77),
                                    ),
                                  ),
                                ),
                                FContainer(
                                  margin: EdgeInsets.only(top: 4),
                                  child: FRow(
                                    children: [
                                      FContainer(
                                        margin: EdgeInsets.only(left: 10),
                                        child: FText(
                                          '性别:',
                                          style: TextStyle(
                                            fontSize: 14,
                                            color:
                                                Color.fromARGB(255, 77, 77, 77),
                                          ),
                                        ),
                                      ),
                                      FContainer(
                                        margin: EdgeInsets.only(left: 10),
                                        child: FText(
                                          _getSexText(info.patientSex),
                                          style: TextStyle(
                                            fontSize: 14,
                                            fontWeight: FontWeight.bold,
                                            color:
                                                Color.fromARGB(255, 77, 77, 77),
                                          ),
                                        ),
                                      ),
                                      FContainer(
                                        margin: EdgeInsets.only(left: 14),
                                        child: FText(
                                          '年龄:',
                                          style: TextStyle(
                                            fontSize: 14,
                                            color:
                                                Color.fromARGB(255, 77, 77, 77),
                                          ),
                                        ),
                                      ),
                                      FContainer(
                                        margin: EdgeInsets.only(left: 10),
                                        child: FText(
                                          info.patientAge.toString(),
                                          style: TextStyle(
                                            fontSize: 14,
                                            fontWeight: FontWeight.bold,
                                            color:
                                                Color.fromARGB(255, 77, 77, 77),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                          FRow(
                            children: [
                              FContainer(
                                margin: EdgeInsets.only(right: 5),
                                width: 50,
                                height: 50,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(8),
                                ),
                                child: FCenter(
                                  child: FInkWell(
                                    onTap: () {
                                      HapticFeedback.mediumImpact();
                                      controller.handleOpenImageList(index);
                                      print('点击查看图像列表');
                                    },
                                    child: FIcon(
                                      FIcons.scan_image,
                                      size: 40,
                                      color: Color.fromARGB(255, 77, 77, 77),
                                    ),
                                  ),
                                ),
                              ),
                              FContainer(
                                width: 50,
                                height: 50,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(8),
                                ),
                                child: FCenter(
                                  child: FInkWell(
                                    onTap: () {
                                      HapticFeedback.mediumImpact();
                                      controller.handleOpenReportList(index);
                                      print('点击查看报告列表');
                                    },
                                    child: FIcon(
                                      FIcons.report_a4,
                                      size: 40,
                                      color: Color.fromARGB(255, 77, 77, 77),
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          )
                        ],
                      ),
                      FContainer(
                        margin: EdgeInsets.only(top: 4, bottom: 10),
                        child: FRow(
                          children: [
                            FContainer(
                              margin: EdgeInsets.only(left: 10),
                              child: FText(
                                '申请医院:',
                                style: TextStyle(
                                  fontSize: 14,
                                  color: Color.fromARGB(255, 77, 77, 77),
                                ),
                              ),
                            ),
                            FContainer(
                              margin: EdgeInsets.only(left: 10),
                              child: FText(
                                info.hospitalName ?? '',
                                style: TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.bold,
                                  color: Color.fromARGB(255, 77, 77, 77),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建顶部（搜索+新建）
  FWidget _buildHeadBar() {
    return FContainer(
      height: 60,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            Color.fromARGB(255, 247, 247, 247),
            Color.fromARGB(255, 241, 241, 241),
          ],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.3),
            blurRadius: 5,
            spreadRadius: 1,
            offset: Offset(0, 1), // changes position of shadow
          ),
        ],
      ),
      child: FRow(
        children: [
          FExpanded(
            child: SearchField(
              textEditingController: controller.searchBarTextController,
              onSearch: controller.handleSearch,
            ),
          ),
          _buildAddButton(),
        ],
      ),
    );
  }

  // 卡片列表视图
  FWidget _buildListView() {
    return FRefreshIndicator(
      onRefresh: controller.refreshList,
      child: FObx(
        () => controller.state.consultationList.isEmpty
            ? _buildLoadResult()
            : FListView.builder(
                padding: EdgeInsets.symmetric(vertical: 10),
                controller: controller.listViewScrollController,
                itemCount: controller.state.consultationList.length,
                itemBuilder: (context, index) {
                  /// 是否是已加载的最后一个
                  final isLoadedLast =
                      index == controller.state.consultationList.length - 1;
                  final isLast = index == controller.totalCount - 1;
                  final card = _buildConsultationItem(
                    index: index,
                    onTap: () => controller.handleShowDetail(index),
                    info: controller.state.consultationList[index],
                  );
                  if (!isLoadedLast) {
                    return card;
                  } else {
                    return FColumn(children: [
                      card,
                      FContainer(
                        height: 50,
                        child: FCenter(
                          child: FText(
                            isLast ? "没有更多数据" : i18nBook.common.loading.t,
                            style: TextStyle(
                              fontSize: 14,
                              color: Colors.grey,
                            ),
                          ),
                        ),
                      )
                    ]);
                  }
                },
              ),
      ),
    );
  }

  FWidget _buildLoadResult() {
    return FCenter(child: FText("暂无数据"));
  }

  String _getConsultationStatusText(ConsultationState status) {
    switch (status) {
      case ConsultationState.Unhandled:
        return '未处理';
      case ConsultationState.Withdrawn:
        return '已撤回';
      case ConsultationState.Handled:
        return '已完成';
      case ConsultationState.Started:
        return '已开始';
      case ConsultationState.WaitForReportUpload:
        return '报告待上传';
      case ConsultationState.ReportUploading:
        return '报告上传中';
      case ConsultationState.ReportUploaded:
        return '报告已上传';
      case ConsultationState.ReportUploadFailed:
        return '报告上传失败';
      case ConsultationState.Expired:
        return '已过期';
      case ConsultationState.Qualified:
        return '合格';
      case ConsultationState.UnQualified:
        return '不合格';
      default:
        return '未知';
    }
  }

  String _getSexText(PatientGenderEnum sex) {
    switch (sex) {
      case PatientGenderEnum.Male:
        return '男';
      case PatientGenderEnum.Female:
        return '女';
      case PatientGenderEnum.NotFilled:
        return '未填写';
    }
  }
}
