import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_measure/view/measure/measure_images_bar.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:fis_ui/values/paddings.dart';
import 'package:fis_ui/values/spacings.dart';
import 'package:fis_ui/widgets/layout/button_group.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/pages/remedical/consultation/controller.dart';
import 'package:flyinsono/pages/remedical/translation_delegate_helper.dart';
import 'package:get/get.dart';

/// 扫查图像
class ScannedPicture extends FStatefulWidget implements FInteractiveContainer {
  @override
  final String pageName;
  ScannedPicture({this.pageName = 'ScannedPicture'});
  @override
  FState<ScannedPicture> createState() => _ScannedPictureState();
}

class _ScannedPictureState extends FState<ScannedPicture> {
  late int _index;

  final controller = Get.find<ConsultationController>();
  late CarotidScanTypeEnum carotidVAS = CarotidScanTypeEnum.CarotidLeft;
  get isLeftCarotidVAS => carotidVAS == CarotidScanTypeEnum.CarotidLeft;
  final ScrollController _scrollController = ScrollController();
  @override
  FWidget build(BuildContext context) {
    final state = controller.state;
    return FObx(
      () => state.imageScanned.length == 0
          ? _buildNoDataTip()
          : FColumn(
              children: [
                _buildImages(),
                _buildDivider(),
                _buildOperateButtons(),
              ],
            ),
    );
  }

  ///操作按钮
  FWidget _buildOperateButtonItem(
      String title, bool isResetGray, Function onPressed) {
    return FOutlinedButton(
      name: title,
      onPressed: isResetGray ? null : () => onPressed(),
      style: ButtonStyle(
        padding: MaterialStatePropertyAll(EdgeInsets.all(0)),
        backgroundColor: MaterialStateProperty.all(
          isResetGray ? Colors.grey : Colors.white,
        ),
      ),
      businessParent: widget,
      child: FText(
        title,
        style: TextStyle(
          color: isResetGray ? Colors.white : Colors.black,
        ),
      ),
    );
  }

  FWidget _imageWrap(List<FWidget> wrapList, [String? title]) {
    if (wrapList.length == 0)
      return FCenter(
        child: FContainer(
          child: FText(title ?? ''),
        ),
      );
    return FWrap(
      spacing: 8.0, // 主轴(水平)方向间距
      runSpacing: 8.0, // 纵轴（垂直）方向间距
      direction: Axis.horizontal,
      alignment: WrapAlignment.start,
      children: wrapList,
    );
  }

  /// 三种图片列表封装
  FWidget _buildStreamingImage(
    List<RemedicalInfoDTO>? imageList,
  ) {
    void selectImage(int imageIndex) {
      controller.openVidMovieDialog(
        imageList![imageIndex].terminalImages!.imageUrl!,
        imageIndex,
        imageList[imageIndex].remedicalCode!,
        imageList[imageIndex].recordCode!,
      );
    }

    /// 设置图片翻译
    String setDescription(int imageIndex) {
      return translation_delegate_helper.translateDescription(
        imageList![imageIndex].application ?? '',
        imageList[imageIndex].applicationCategory ?? '',
      );
    }

    /// 设置图像定位信息
    String setLocationDescription(int imageIndex) {
      return translation_delegate_helper.translateLocationDescription(
        imageList![imageIndex].imageLocation?.quadrant,
        imageList[imageIndex].imageLocation?.position,
      );
    }

    /// 图片布局
    return _imageWrap(
      List<FWidget>.generate(
        imageList?.length ?? 0,
        (index) {
          final image = FContentImage(
            remedicalInfo: imageList![index],
            onDoubleTap: () => selectImage(index),
            onTap: () => selectImage(index),
            serialNo: _index + 1,
            description: setDescription(index),
            locationDescription: setLocationDescription(index),
          );
          _index++;
          return image;
        },
      ),
    );
  }

  FWidget _buildInkWell(
    CarotidScanTypeEnum carotidScanType,
  ) {
    final isChooseLeftCarotid = carotidVAS == carotidScanType;
    final isLeftCarotid = carotidScanType == CarotidScanTypeEnum.CarotidLeft;
    return FInkWell(
      onTap: () {
        carotidVAS = carotidScanType;
        setState(() {});
      },
      child: FContainer(
        decoration: BoxDecoration(
          border: Border.all(
            width: 0.5,
            color: Colors.grey,
          ),
          color: isChooseLeftCarotid
              ? FTheme.ins.colorScheme.primary
              : Colors.transparent,
          borderRadius: isLeftCarotid
              ? BorderRadius.only(
                  topLeft: Radius.circular(4),
                  bottomLeft: Radius.circular(4),
                )
              : BorderRadius.only(
                  topRight: Radius.circular(4),
                  bottomRight: Radius.circular(4),
                ),
        ),
        padding: EdgeInsets.symmetric(
          horizontal: 20,
          vertical: 5,
        ),
        child: FText(
          isLeftCarotid
              ? i18nBook.remedical.leftNeck.t
              : i18nBook.remedical.rightNeck.t,
          style: TextStyle(
            color: isChooseLeftCarotid ? Colors.white : Colors.black,
          ),
        ),
      ),
    );
  }

  /// 左右颈动脉
  FWidget _buildCarotidTabs(RemedicalItemList remedicalItem) {
    bool hasLeftImage =
        _checkCarotidList(remedicalItem, CarotidScanTypeEnum.CarotidLeft);
    bool hasRightImage =
        _checkCarotidList(remedicalItem, CarotidScanTypeEnum.CarotidRight);
    return FContainer(
      margin: EdgeInsets.only(bottom: 5),
      child: FRow(
        children: [
          hasLeftImage
              ? _buildInkWell(
                  CarotidScanTypeEnum.CarotidLeft,
                )
              : FContainer(),
          hasRightImage
              ? _buildInkWell(
                  CarotidScanTypeEnum.CarotidRight,
                )
              : FContainer(),
        ],
      ),
    );
  }

  FWidget _buildImageItem(
      RemedicalItemList remedicalItem, BuildContext context) {
    List<RemedicalInfoDTO>? remedicalList = remedicalItem.remedicalList
        ?.where((element) => element.carotidResult != null)
        .toList();

    /// 是否是颈动脉
    bool isCarotid = (remedicalItem.application ?? '').contains('Carotid');

    /// 是否显示颈动脉
    bool isShowCarotid =
        isCarotid && remedicalList != null && remedicalList.length != 0;

    /// 是否是未标识的颈动脉
    bool isUnidentifiedCarotidArtery = remedicalItem.remedicalList
            ?.where((element) => element.carotidResult == null)
            .length !=
        0;

    /// 有颈动脉AI结果的图片列表
    List<RemedicalInfoDTO> carotidResultList = remedicalItem.remedicalList
            ?.where(
              (element) =>
                  element.carotidResult != null &&
                  element.carotidResult?.carotidScanType == carotidVAS,
            )
            .toList() ??
        [];

    /// 无颈动脉AI结果的图片列表 未标识的颈动脉
    List<RemedicalInfoDTO> noCarotidResultList = remedicalItem.remedicalList
            ?.where((element) => element.carotidResult == null)
            .toList() ??
        [];

    return FContainer(
      margin: EdgeInsets.symmetric(vertical: 15, horizontal: 30),
      child: FColumn(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          FContainer(
            height: 25,
            child: FText(
              translation_delegate_helper.translateDescription(
                  remedicalItem.application, remedicalItem.applicationCategory),
            ),
          ),
          if (isShowCarotid) ...[
            _buildCarotidTabs(remedicalItem),

            /// 有颈动脉结果的图像
            _buildStreamingImage(carotidResultList),

            /// 未标识的颈动脉图像
            if (isUnidentifiedCarotidArtery)
              FContainer(
                margin: EdgeInsets.symmetric(vertical: 5),
                child: FText(
                  i18nBook.remedical.imageUnidentifiedCarotidArtery.t,
                ),
              ),

            _buildStreamingImage(noCarotidResultList),
          ] else

            /// 非颈动脉的图像
            _buildStreamingImage(remedicalItem.remedicalList),
        ],
      ),
    );
  }

  ///无数据视图
  FWidget _buildNoDataTip() {
    return FContainer(
      margin: EdgeInsets.only(top: 80),
      child: FColumn(
        children: [
          FCenter(
            child: FImage.asset(
              "assets/images/no_data.png",
              width: 300,
              height: 300,
              fit: BoxFit.cover,
            ),
          ),
          FText(i18nBook.common.noneDataTip.t),
        ],
      ),
    );
  }

  ///图像展示
  FWidget _buildImages() {
    final state = controller.state;

    return FExpanded(
      child: FObx(
        () {
          _index = 0;
          return FSingleChildScrollView(
            child: FColumn(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                FContainer(
                  margin: EdgeInsets.only(
                    left: 30,
                    top: 15,
                  ),
                  child: FText(
                    state.imageScanned[state.imageScannedIndex].scanDate
                        .toString(),
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                FAlwaysScrollListView(
                  scrollController: _scrollController,
                  child: QuickFWidget(ScrollConfiguration(
                    behavior: ScrollConfiguration.of(context)
                        .copyWith(scrollbars: false),
                    child: FListView.builder(
                      controller: _scrollController,
                      shrinkWrap: true,
                      itemCount: state.imageScanned[state.imageScannedIndex]
                          .remedicalItemList?.length,
                      itemBuilder: (BuildContext context, int index) {
                        return _buildImageItem(
                          state.imageScanned[state.imageScannedIndex]
                              .remedicalItemList![index],
                          context,
                        );
                      },
                    ),
                  )),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  ///分割线
  _buildDivider() {
    return FContainer(
      child: FDivider(
        color: Color.fromRGBO(216, 216, 216, 1),
        thickness: 0.5,
      ),
    );
  }

  ///操作按钮
  FWidget _buildOperateButtons() {
    final state = controller.state;
    return FObx(
      () => FContainer(
        margin: EdgeInsets.only(bottom: 10),
        child: FButtonGroup(
          buttonPadding: FPaddings.MINI_BUTTON,
          spacing: FSpacings.MINI_BUTTON,
          children: [
            _buildOperateButtonItem(
              i18nBook.remedical.previousPage.t,
              state.imageScannedIndex == 0,
              () {
                controller.scanningImageController.lastPage();
              },
            ),
            _buildOperateButtonItem(
              i18nBook.remedical.nextPage.t,
              state.imageScannedIndex + 1 == state.imageScanned.length,
              () {
                controller.scanningImageController.nextPage();
              },
            ),
            _buildOperateButtonItem(
              i18nBook.remedical.check.t,
              false,
              () {
                controller.inspectionRecordsController.openCheckDialog(
                  state.imageScanned[state.imageScannedIndex].recordCode,
                );
              },
            ),
            _buildOperateButtonItem(
              i18nBook.common.report.t,
              false,
              () {
                controller.inspectionRecordsController.openReportDialog(
                  state.imageScanned[state.imageScannedIndex].recordCode,
                );
                print(i18nBook.remedical.associateReport.t);
              },
            ),
            _buildOperateButtonItem(
              i18nBook.common.refresh.t,
              false,
              () {
                controller.scanningImageController.getRemedicalListPagesAsync();
              },
            ),
          ],
        ),
      ),
    );
  }

  bool _checkCarotidList(
      RemedicalItemList remedicalItem, CarotidScanTypeEnum scanTypeEnum) {
    return (remedicalItem.remedicalList
                ?.where(
                  (element) =>
                      element.carotidResult != null &&
                      element.carotidResult?.carotidScanType == scanTypeEnum,
                )
                .toList() ??
            [])
        .isNotEmpty;
  }
}
