import 'package:common_pub/common_pub.dart';
import 'package:common_pub/ui/map_view/map_view.dart';
import 'package:common_pub/ui/map_view/view_map_cp.dart';
import 'package:common_pub/ui/map_view/view_map_image.dart';
import 'package:common_pub/ui/map_view/view_map_touch.dart';
import 'package:common_pub/ui/map_view/view_map_trace_tail.dart';
import 'package:common_pub/ui/map_view/view_map_user_point.dart';
import 'package:common_pub/ui/map_view/view_plug_loading.dart';
import 'package:track_common/widget/prelude.dart';

import '../../../service/map_watch.dart';
import 'field_control_controller.dart';

abstract class FieldControlPage extends GetView<FieldControlController> {
  const FieldControlPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
        height: double.infinity,
        width: double.infinity,
        color: const Color(0xffc9c0c0),
        alignment: Alignment.center,
        child: Obx(() {
          final mapWatch = controller.mapWatch;
          return mapWatch != null ? content(context, mapWatch) : noData();
        }));
  }

  Widget noData() {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Image.asset(Assets.imagesIcNoData, package: package, height: 64),
          const SizedBox(height: 25),
          const Text('没有数据, 请选择地图',
              style: TextStyle(color: Color(0xff707070), fontSize: 18.5)),
        ],
      ),
    );
  }

  Widget content(BuildContext context, MapWatch map) {
    final children = <Widget>[
      ViewPlugLoading(map.plugMap),
      ViewMapImage(map.plugMap),
    ];

    final focusUser = controller.focusUser;
    if (focusUser != null) {
      children.add(ViewMapCP(
        // key:UniqueKey(),
        map.plugMap,
        cpWantAndHistoryList: focusUser.cpList,
        isHideRouteBeforeStart: false,
        controller: controller.viewCpController,
      ));
    }

    children.addAll([
      _ViewTrace(map: map, traceDuration: 30.seconds),
      ViewMapTouch(map.plugMap)
    ]);

    return Row(
      children: [
        Expanded(
            child: Column(
          children: [
            _MapView(),
            // Expanded(
            //     child: ViewMapStack(plug: map.plugMap, children: children)),
            _MsgView(),
          ],
        )),
        rightColumn(context)
      ],
    );
  }

  Widget rightColumn(BuildContext context);
}

class _MapView extends GetView<FieldControlController> {
  @override
  Widget build(BuildContext context) {
    return Expanded(
        child: ViewMapStack(
      plug: controller.mapWatch!.plugMap,
      children: [
        Obx(() {
          final map = controller.mapWatch!;
          final children = <Widget>[
            ViewPlugLoading(map.plugMap),
            ViewMapImage(map.plugMap),
          ];

          final focusUser = controller.focusUser;
          if (focusUser != null) {
            children.add(ViewMapCP(
              // key:UniqueKey(),
              map.plugMap,
              cpWantAndHistoryList: focusUser.cpList,
              isHideRouteBeforeStart: false,
              controller: controller.viewCpController,
            ));
          }

          children.addAll([
            _ViewTrace(map: map, traceDuration: 30.seconds),
            ViewMapTouch(map.plugMap)
          ]);
          return SizedBox.expand(
            child: Stack(
              children: children,
            ),
          );
        })
      ],
    ));
  }
}

class _ViewTrace extends GetView<FieldControlController> {
  const _ViewTrace({required this.map, required this.traceDuration});

  final MapWatch map;
  final Duration traceDuration;

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      final children = <Widget>[];

      for (final act in map.eventList) {
        for (final user in act.userList) {
          if (user.isHide.value) {
            continue;
          }
          final trace = user.trace.lastOrNull;
          final traceTailOnMap = <Offset>[];
          final st = user.watchAt;
          for (final one in user.trace) {
            if (DateTime.now().difference(st.add(one.ts)) < traceDuration) {
              traceTailOnMap.add(one.onMap);
            }
          }

          if (trace != null) {
            children.add(ViewMapTraceTail(
              plug: map.plugMap,
              onMapTrace: traceTailOnMap,
              color: user.flag.value.color,
            ));
            children.add(ViewMapUserPoint(
                key: UniqueKey(),
                map.plugMap,
                trace,
                info: user.name,
                color: user.flag.value.color));
          }
        }
      }

      return Stack(alignment: Alignment.topLeft, children: children);
    });
  }
}

class EventInfoView extends GetView<FieldControlController> {
  const EventInfoView({super.key});

  @override
  Widget build(BuildContext context) {
    return Obx(() => Container(
          width: double.infinity,
          height: double.infinity,
          color: Colors.white,
          child: ListView(
            children: controller.eventList
                .map((element) => activeView(element))
                .toList(),
          ),
        ));
  }

  Widget activeView(EventOnMap info) {
    final children = <Widget>[];

    if (!info.isHide.value) {
      children.addAll([
        Container(
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(5)),
          padding: const EdgeInsets.fromLTRB(26, 11, 26, 11),
          child: Row(
            children: [
              const Text('广播'),
              const Spacer(),
              Image.asset(Assets.imagesIcCp,
                  height: 20, width: 20, package: package),
              Text(' ${info.cpAllCount}'),
              const Spacer(),
              const Text('全部隐藏'),
            ],
          ),
        )
      ]);
      children
          .addAll(info.userList.map((e) => _UserInfoView(data: e)).toList());
    }

    return Container(
      margin: EdgeInsets.only(bottom: 12),
      decoration: BoxDecoration(
          color: const Color(0xffe0e0e0),
          borderRadius: BorderRadius.circular(5)),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(5),
                  boxShadow: [
                    BoxShadow(color: const Color(0x4d000000), blurRadius: 6)
                  ]),
              padding: EdgeInsets.only(left: 21, top: 10, bottom: 7, right: 6),
              child: Row(
                children: [
                  Expanded(
                      child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text.rich(
                        TextSpan(
                            text: '${info.name} ',
                            style: TextStyle(
                                fontWeight: FontWeight.w700,
                                fontSize: 14.22,
                                color: Color(0xff333333)),
                            children: [
                              TextSpan(
                                  text: '(${info.userList.length}人)',
                                  style: TextStyle(
                                      fontSize: 11.4,
                                      fontWeight: FontWeight.w500))
                            ]),
                        maxLines: 1,
                      ),
                      const SizedBox(height: 6),
                      Text.rich(TextSpan(
                          text:
                              '比赛时间：${info.ext.startAt} - ${info.ext.endAt}  ',
                          style: TextStyle(
                              fontSize: 9.96,
                              color: Color(0xff818181),
                              fontWeight: FontWeight.w500),
                          children: [
                            TextSpan(
                                text: info.ext.state.toString(),
                                style:
                                    TextStyle(color: info.ext.state.toColor()))
                          ]))
                    ],
                  )),
                  IconButton(
                      onPressed: () {
                        info.isHide.value = !info.isHide.value;
                      },
                      icon: info.isHide.value
                          ? const Icon(Icons.arrow_drop_down)
                          : const Icon(Icons.arrow_drop_up))
                ],
              )),

          Padding(
            padding: EdgeInsets.symmetric(
                horizontal: 6.3, vertical: info.isHide.value ? 0 : 6.3),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: children,
            ),
          )
          //     Row (
          //       children: [
          //          Expanded(child:  Column(
          //
          //             children: [
          //

          //           const SizedBox(
          //             width: 8,
          //           ),

          //         ],

          //       ],
          //     )),
        ],
      ),
    );
  }
}

class _UserInfoView extends GetView<FieldControlController> {
  const _UserInfoView({required this.data});

  final PlayerOnMap data;

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(5)),
      padding: const EdgeInsets.fromLTRB(7, 11, 7, 11),
      margin: const EdgeInsets.only(top: 5),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Obx(() => Container(
                  margin: const EdgeInsets.only(top: 2),
                  decoration: BoxDecoration(
                      color: data.flag.value.color,
                      borderRadius: BorderRadius.circular(4)),
                  width: 7,
                  height: 16)),
              const SizedBox(
                width: 8,
              ),
              Expanded(
                child: Text.rich(TextSpan(
                    text: data.name,
                    children: [TextSpan(text: ' [${data.routeName}]')])),
              ),
              GestureDetector(
                onTap: () {
                  final oldId = controller.focusUserId.value;
                  if (oldId != null) {
                    if (oldId == data.id) {
                      controller.focusUserId.value = null;
                      return;
                    }
                  }
                  controller.focusUserId.value = data.id;
                },
                child: Obx(() => Icon(
                      Icons.route,
                      color: data.id != controller.focusUser?.id
                          ? Colors.grey
                          : const Color(0xffffbb77),
                    )),
              ),
              const SizedBox(width: 8),
              GestureDetector(
                onTap: () {
                  data.isHide.value = !data.isHide.value;
                },
                child: Obx(() => Icon(
                      data.isHide.value
                          ? Icons.visibility_off
                          : Icons.visibility,
                      color: data.isHide.value
                          ? Colors.grey
                          : const Color(0xffffbb77),
                    )),
              )
            ],
          ),
          Container(
            margin: const EdgeInsets.only(left: 14),
            child: Row(
              children: [
                container(null, cpInfo, Colors.blue),
                container(
                    const Icon(
                      Icons.favorite,
                      size: 13,
                      color: Colors.white,
                    ),
                    ' ${hr == 0 ? '--' : hr}',
                    data.heartRatePercent.toHRPColor()),
                container(null, paceInfo, data.pace.color)
              ],
            ),
          ),
          const SizedBox(height: 5),
          Container(
              margin: const EdgeInsets.only(left: 14),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('距离 ${data.nextDistance.toString()}'),
                  Text('时间 ${data.duration.toAppString()}'),
                  Text('里程 ${data.distance.toString()}'),
                ],
              ))
        ],
      ),
    );
  }

  int get hr {
    return data.hrInfo.lastOrNull?.hr ?? 0;
  }

  String get cpInfo {
    final next = data.cpNextWant;
    return next != null ? '${data.nextCPSN}点(${next.areaId})' : '--';
  }

  String get paceInfo {
    Duration;
    return data.pace.toString();
  }

  Widget container(Widget? icon, String text, Color color) {
    final children = <Widget>[];
    if (icon != null) {
      children.add(icon);
    }
    children.add(
        Text(text, style: const TextStyle(color: Colors.white, fontSize: 14)));

    return Container(
      height: 20,
      padding: const EdgeInsets.fromLTRB(10, 0, 12, 0),
      margin: const EdgeInsets.only(right: 6),
      alignment: Alignment.center,
      decoration:
          BoxDecoration(color: color, borderRadius: BorderRadius.circular(9)),
      child: Row(
        children: children,
      ),
    );
  }
}

class _MsgView extends GetView<FieldControlController> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}
