import 'package:fis_ui/index.dart';
import 'package:fis_ui/values/spacings.dart';
import 'package:fis_common/index.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/managers/interfaces/ai_manager.dart';
import 'package:flyinsono/managers/server_config_manager.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import '../index.dart';

/// 数据表格
class RecordDataTable extends FisView<ConsultationRecordViewController> {
  RecordDataTable({Key? key}) : super(key: key);
  final tabelScrollController = ScrollController();
  final aiManager = Get.find<IAIManager>();

  @override
  FWidget build(BuildContext context) {
    return FisBuilder<ConsultationRecordViewController>(
        init: ConsultationRecordViewController(),
        id: "record_data_table",
        builder: (_) {
          return FFlex(
            direction: Axis.vertical,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              FExpanded(
                  child: QuickFWidget(ScrollConfiguration(
                behavior:
                    ScrollConfiguration.of(context).copyWith(scrollbars: false),
                child: FTable<ConsultationsRecordData>(
                  autoHeight: false,
                  noDataHintText: i18nBook.common.noData.t,
                  columns: _buildTableColumns(),
                  source: controller.consultationsRecordDataList,
                  loading: controller.isTableLoading,
                  onRowSelected: (value, index, idxs) {},
                  onRowTap: (index) {
                    controller.onTableRowTap(index);
                  },
                  onAllRowsSelected: (value, idxs) => {},
                  scrollController: tabelScrollController,
                ),
              ))),
              _buildTablePagination(),
              FSizedBox(
                height: FSpacings.L,
              )
            ],
          );
        });
  }

  FWidget _buildTablePagination() {
    return FisBuilder<ConsultationRecordViewController>(
      id: "record_table_pagination",
      builder: (_) {
        return FTablePagination(
          currListLength: controller.totalDataCount,
          currPageIndex: controller.pageIndex,
          pageSize: 20,
          onChangePage: (pageIndex, listLength) {
            controller.onChangePage(pageIndex, listLength);
            _tableScrollToTop();
          },
          totalItemNumText: i18nBook.common.ofTerm
              .translate(['${controller.totalDataCount}']),
          previousFivePageText: i18nBook.common.previousFivePageText.t,
          nextFivePageText: i18nBook.common.nextFivePageText.t,
        );
      },
    );
  }

  void _tableScrollToTop() {
    tabelScrollController.animateTo(0,
        duration: Duration(milliseconds: 500), curve: Curves.ease);
  }

  /// 配置表格列
  List<FTableColumn<ConsultationsRecordData>> _buildTableColumns() {
    var textStyle = TextStyle(
      fontSize: 16,
      overflow: TextOverflow.ellipsis,
    );
    return <FTableColumn<ConsultationsRecordData>>[
      FTableColumn<ConsultationsRecordData>(
        headerText: 'ID',
        flex: 2,
        render: (rowData, index) => FCenter(
          child: FText(
            maxLines: 1,
            rowData.devicePatientID.isNullOrEmpty
                ? i18nBook.remedical.notFill.t
                : rowData.devicePatientID!,
            style: const TextStyle(
              fontSize: 16,
            ),
          ),
        ),
      ),
      FTableColumn<ConsultationsRecordData>(
        flex: 2,
        headerText: i18nBook.remedical.patientDisplayName.t,
        render: (rowData, index) => FCenter(
            child: FContainer(
          constraints: BoxConstraints(
            maxHeight: 23.0,
          ),
          child: FText(
              maxLines: 1,
              rowData.patientName.isNullOrEmpty
                  ? i18nBook.remedical.notFill.t
                  : rowData.patientName!,
              style: textStyle),
        )),
      ),
      if (ServerConfigManager.isScreenshot &&
          (CartSystemPlatform.isCartSystemVersion || kDebugMode)) ...[
        FTableColumn<ConsultationsRecordData>(
            headerText: i18nBook.common.from.t,
            flex: 2,
            render: (rowData, index) => FCenter(
                  child: FContainer(
                    constraints: BoxConstraints(
                      maxHeight: 23.0,
                    ),
                    child: FText(
                        maxLines: 1,
                        "${rowData.rootOrganizationName.toString()}-${Store.user.displayName}",
                        style: textStyle),
                  ),
                ),
            minWidth: 350),
      ] else ...[
        FTableColumn<ConsultationsRecordData>(
            headerText: i18nBook.profileComplete.organizationIn.t,
            flex: 2,
            render: (rowData, index) => FCenter(
                  child: FContainer(
                    constraints: BoxConstraints(
                      maxHeight: 23.0,
                    ),
                    child: FText(
                        maxLines: 1,
                        rowData.rootOrganizationName.toString(),
                        style: textStyle),
                  ),
                ),
            minWidth: 250),
        FTableColumn<ConsultationsRecordData>(
          headerText: i18nBook.homePage.organizationDevices.t,
          flex: 2,
          textAlign: TextAlign.center,
          render: (rowData, index) => FCenter(
            child: FContainer(
              constraints: BoxConstraints(
                maxHeight: 23.0,
              ),
              child: FText(
                  maxLines: 1, rowData.deviceName.toString(), style: textStyle),
            ),
          ),
        ),
      ],
      FTableColumn<ConsultationsRecordData>(
        headerText: i18nBook.common.status.t,
        flex: 2,
        textAlign: TextAlign.center,
        render: (rowData, index) => FCenter(
          child: FText(
              maxLines: 1,
              _stateLabel(rowData.recordStatus, rowData.referralType),
              style: textStyle),
        ),
      ),
      FTableColumn<ConsultationsRecordData>(
          headerText: i18nBook.common.AIDiagnosis.t,
          flex: 1,
          textAlign: TextAlign.center,
          render: (rowData, index) {
            var diagnosisInfos = rowData.diagnosisInfos;
            return FCenter(
              child: FWrap(
                // mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: diagnosisInfos
                    .map(
                      (e) => FIcon(
                        aiManager.getAiIconItem(e.diagnosisOrgan),
                        color: aiManager.getAIIconColor(
                            e.conclusion, e.diagnosisOrgan),
                        size: 26,
                      ),
                    )
                    .toList(),
              ),
            );
          }),

      /// TODO 【质控功能暂时屏蔽，后面放开只要解开注释】
      // if (Store.user.hasFeature(FeatureKeys.QualityControl)) ...[
      //   FTableColumn<ConsultationsRecordData>(
      //     headerText: i18nBook.common.qualityControlStatus.t,
      //     flex: 3,
      //     render: (rowData, index) => FCenter(
      //       child: FContainer(
      //           padding: EdgeInsets.symmetric(
      //             vertical: 8,
      //           ),
      //           child: FText(
      //             (rowData.score != null && rowData.score! > 0)
      //                 ? i18nBook.common.qualityControlledScore
      //                     .translate([rowData.score])
      //                 : "",
      //             maxLines: 1,
      //             style: textStyle,
      //           )),
      //     ),
      //   ),
      // ],
      FTableColumn<ConsultationsRecordData>(
        headerText: i18nBook.common.createTime.t,
        flex: 3,
        render: (rowData, index) => FCenter(
          child: FContainer(
              padding: EdgeInsets.symmetric(
                vertical: 8,
              ),
              child: FText(
                maxLines: 1,
                DateFormat("yyy-MM-dd HH:mm:ss").format(
                  rowData.createTime?.toLocal() ?? DateTime.now(),
                ),
                style: textStyle,
              )),
        ),
      ),
    ];
  }

  /// 会诊状态文案
  String _stateLabel(
    RecordStatusEnum? statusEnum,
    ReferralTypeEnum? referralType,
  ) {
    String label = '';
    switch (statusEnum) {
      case RecordStatusEnum.Completed:
        label = i18nBook.remedical.reported4Label.t;
        break;
      case RecordStatusEnum.NotReport:
        label = i18nBook.remedical.scanned4Label.t;
        break;
      case RecordStatusEnum.NotScanned:
        label = i18nBook.remedical.toScan4Label.t;
        break;
      case RecordStatusEnum.Uploaded:
        label = i18nBook.remedical.imageUploaded4Label.t;
        break;
      default:
        label = i18nBook.remedical.notFinished4Label.t;
        break;
    }

    if (referralType == ReferralTypeEnum.ReferralIn) {
      label += '(${i18nBook.remedical.transferiIn.t})';
    } else if (referralType == ReferralTypeEnum.ReferralOut) {
      label += '(${i18nBook.remedical.transferOut.t})';
    }
    return label;
  }
}
