import 'package:fis_measure/index.dart';
import 'package:fis_measure/interfaces/process/items/measure_terms.dart';
import 'package:fis_measure/interfaces/process/player/play_controller.dart';
import 'package:fis_measure/interfaces/process/workspace/application.dart';
import 'package:fis_measure/interfaces/process/workspace/exam_info.dart';
import 'package:fis_measure/interfaces/process/workspace/measure_controller.dart';
import 'package:fis_measure/process/workspace/measure_controller.dart';
import 'package:fis_measure/view/main/desktop.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class MeasureTestPage extends StatefulWidget {
  const MeasureTestPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _MeasureTestPageState();
}

class _MeasureTestPageState extends State<MeasureTestPage> {
  static const C_LINEAR_TISSUE =
      "http://192.168.6.117:9303/Flyinsono-BJ-1300984704.VCS.AP-BeiJing/151394487066498fbb8f1e34ca0c7083.VID";
  static const C_CONVEX_TISSUE =
      "http://192.168.6.117:9001/Flyinsono-BJ-1300984704.VCS.AP-BeiJing/default.VID";
  final controller = Get.put<IMeasureController>(MeasureController(
    "12345",
    imagesFetchFunc: (code) async {
      return <ExamImageInfo>[
        ExamImageInfo(C_LINEAR_TISSUE, C_LINEAR_TISSUE),
        ExamImageInfo(C_CONVEX_TISSUE, C_CONVEX_TISSUE)
      ];
    },
  ));

  bool loaded = false;

  @override
  void initState() {
    controller.load().then((value) {
      // 加载指定图像
      controller.examInfo.selectedImageIndex = 0;
    });

    super.initState();

    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      controller.imageLoaded.addListener(onImageLoaded);
    });
  }

  @override
  void dispose() {
    controller.imageLoaded.removeListener(onImageLoaded);
    controller.dispose();
    Get.delete<IMeasureController>();
    super.dispose();
  }

  void onImageLoaded(Object sender, ExamImageInfo? e) {
    if (e != null) {
      setState(() {
        loaded = true;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    Widget body;
    if (!loaded) {
      const loadingWidget = Center(child: CircularProgressIndicator());
      body = Row(
        children: const [
          SizedBox(
            width: 300,
            child: loadingWidget,
          ),
          VerticalDivider(),
          Expanded(child: loadingWidget),
        ],
      );
    } else {
      body = Row(
        children: const [
          _MeasureLeftBoard(),
          VerticalDivider(),
          Expanded(
            child: _MeasureRightBoard(),
          ),
        ],
      );
    }
    return Scaffold(
      appBar: AppBar(),
      body: body,
    );
  }
}

class _MeasureRightBoard extends StatefulWidget {
  const _MeasureRightBoard({Key? key}) : super(key: key);
  @override
  State<StatefulWidget> createState() => _MeasureRightBoardState();
}

class _MeasureRightBoardState extends State<_MeasureRightBoard> {
  final playerController = Get.find<IPlayerController>();

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(8).copyWith(left: 0),
      child: Column(
        children: [
          const Expanded(
            child: MeasureMainView(),
          ),
          const Divider(),
          SizedBox(
            height: 140,
            child: VidPlayerControlBoard(
              playerController as VidPlayerController,
            ),
          ),
        ],
      ),
    );
  }
}

class _MeasureLeftBoard extends StatefulWidget {
  const _MeasureLeftBoard({Key? key}) : super(key: key);
  @override
  State<StatefulWidget> createState() => _MeasureLeftBoardState();
}

class _MeasureLeftBoardState extends State<_MeasureLeftBoard> {
  // ignore: non_constant_identifier_names
  static final C_SUPPORTED_ITEMS = <String>[
    MeasureTerms.Distance,
    MeasureTerms.Perimeter,
    MeasureTerms.Area,
  ];

  final scrollController = ScrollController();
  final application = Get.find<IApplication>();

  int activeIndex = 0;

  @override
  void initState() {
    application.canMeasureChanged.addListener(_onCanMeasureChanged);
    super.initState();
  }

  @override
  dispose() {
    application.canMeasureChanged.removeListener(_onCanMeasureChanged);
    super.dispose();
  }

  _onCanMeasureChanged(Object sender, bool e) {
    if (e && mounted) {
      changeItem(0);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 300,
      padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 12),
      child: Scrollbar(
        controller: scrollController,
        isAlwaysShown: true,
        child: ListView.separated(
          controller: scrollController,
          itemCount: C_SUPPORTED_ITEMS.length,
          itemBuilder: (BuildContext context, int index) {
            final name = C_SUPPORTED_ITEMS[index];
            final active = index == activeIndex;
            return active
                ? ElevatedButton(
                    onPressed: () => changeItem(index),
                    child: Text(name),
                    style: ElevatedButton.styleFrom(
                      fixedSize: const Size.fromHeight(50),
                    ),
                  )
                : OutlinedButton(
                    onPressed: () => changeItem(index),
                    child: Text(name),
                    style: OutlinedButton.styleFrom(
                      fixedSize: const Size.fromHeight(50),
                    ),
                  );
          },
          separatorBuilder: (BuildContext context, int index) {
            return const SizedBox(height: 8);
          },
        ),
      ),
    );
  }

  void changeItem(int index) {
    setState(() {
      activeIndex = index;
    });
    final name = C_SUPPORTED_ITEMS[index];
    print(name);
    application.switchItemByName(name);
  }
}
