import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_measure/view/measure/measure_images_bar.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/pages/remedical/translation_delegate_helper.dart';
import 'package:flyinsono/pages/remedical/consultation/controller.dart';
import 'package:get/get.dart';

///检查图像列表
class RecordsImageList extends FStatefulWidget {
  /// 测量图片列表
  final List<RemedicalInfoDTO> remedicalList;

  /// 当前测量的下标
  final int? index;

  /// 当前检查code
  final String? recordCode;

  RecordsImageList({
    required this.remedicalList,
    required this.recordCode,
    this.index = 0,
    Key? key,
  }) : super(key: key);

  @override
  FState<RecordsImageList> createState() => _RecordsImageListState();
}

class _RecordsImageListState extends FState<RecordsImageList> {
  /// 分时诊断的控制器
  final controller = Get.find<ConsultationController>();

  /// 滑动区域的key值
  final GlobalKey globalKey = GlobalKey();

  /// 当前可滑动的范围宽度
  late double width = 0;

  /// 是否滑到最后
  bool _isEnd = false;

  ///当前分辨率下ListView里面的item个数
  int _itemsPerPage = 0;

  /// 计算下标
  int _currentPage = 0;

  /// 滑动控制器
  ScrollController _scrollController = ScrollController();

  /// 左边能否滑动
  bool get isLeftCanScroll => _currentPage <= 0;

  /// 右边能否滑动
  bool get isRightCanScroll => _isEnd;

  /// 首页点击图片事件
  ///
  /// [index] 当前图片组的下标
  ///
  /// [imageScannedIndex] 当前下标组的下标
  void onClickImage(int index, String recordCode) {
    // 打开图片前首先得知道这是在什么检查下面
    controller.openVidMovieDialog(
      widget.remedicalList[index].terminalImages!.imageUrl!,
      index,
      widget.remedicalList[index].remedicalCode!,
      widget.remedicalList[index].recordCode!,
    );
  }

  /// 图片左划事件
  void onLeftMoveImage() async {
    _currentPage--;
    await _scrollController.animateTo(
      (130 * _itemsPerPage * _currentPage).toDouble(),
      duration: const Duration(milliseconds: 300),
      curve: Curves.linear,
    );
  }

  /// 图片右划事件
  void onRightMoveImage() async {
    _currentPage++;
    await _scrollController.animateTo(
      (130 * _itemsPerPage * _currentPage).toDouble(),
      duration: const Duration(milliseconds: 300),
      curve: Curves.linear,
    );
  }

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(
      () async {
        // 如果滑动到最右边
        if (_scrollController.position.pixels ==
            _scrollController.position.maxScrollExtent) {
          setState(() {
            _isEnd = true;
          });
        } else {
          setState(
            () {
              _isEnd = false;
            },
          );
        }
      },
    );
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    WidgetsBinding.instance.addPostFrameCallback(
      (mag) {
        width = globalKey.currentContext!.size!.width;
        //listview 里面存在10个像素的右边距，因此在计算item实际占用宽度时，加10处理。

        var itemsMaxWidth = width + 10;
        _itemsPerPage = itemsMaxWidth ~/ 130;

        setState(
          () {
            _isEnd = width >= widget.remedicalList.length * 130;
          },
        );
      },
    );
  }

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

  @override
  FWidget build(BuildContext context) {
    if (widget.remedicalList.length > 0)
      return FColumn(
        children: [
          const FSizedBox(
            height: 30,
          ),
          FRow(
            children: [
              _buildIconButton(
                Icons.chevron_left_rounded,
                isLeftCanScroll,
                onLeftMoveImage,
              ),
              FExpanded(
                child: FContainer(
                  height: 100,
                  width: 800,
                  child: _buildImageList(),
                ),
              ),
              _buildIconButton(
                Icons.chevron_right_rounded,
                isRightCanScroll,
                onRightMoveImage,
              ),
            ],
          ),
        ],
      );
    else
      return const FSizedBox();
  }

  FWidget _buildImageList() {
    return FContainer(
      key: globalKey,
      child: FListView.builder(
        scrollDirection: Axis.horizontal,
        controller: _scrollController,
        itemCount: widget.remedicalList.length,
        itemBuilder: (BuildContext context, int index) {
          final remedicalItem = widget.remedicalList[index];
          return FStack(
            children: [
              FContainer(
                margin: const EdgeInsets.only(
                  right: 10,
                ),
                width: 120,
                child: FContentImage(
                  remedicalInfo: remedicalItem,
                  isMeasure: true,
                  onDoubleTap: () => onClickImage(
                    index,
                    widget.recordCode!,
                  ),
                  onTap: () => onClickImage(
                    index,
                    widget.recordCode!,
                  ),
                  serialNo: index + 1,
                  locationDescription:
                      translation_delegate_helper.translateLocationDescription(
                    remedicalItem.imageLocation?.quadrant,
                    remedicalItem.imageLocation?.position,
                  ),
                  description: translation_delegate_helper.translateDescription(
                      remedicalItem.application,
                      remedicalItem.applicationCategory),
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  FWidget _buildIconButton(
    IconData icons,
    bool isCanClick,
    Function onTap,
  ) {
    return FContainer(
      child: FInkWell(
        child: FIcon(
          icons,
          size: 50,
          color: isCanClick ? Colors.grey : Colors.black,
        ),
        onTap: () => onTap.call(),
      ),
    );
  }
}
