import 'package:application/service/api.dart' as pb;
import 'package:application/widget.dart';
import 'package:common_pub/ui/map_view/map_view.dart';
import 'package:common_pub/ui/map_view/view_map_image.dart';
import 'package:common_pub/ui/map_view/view_map_trace_tail.dart';
import 'package:common_pub/ui/map_view/view_map_touch.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:common_pub/utils.dart';
import 'field_control_controller.dart';

class FieldControlPage extends StatelessWidget {
  const FieldControlPage({super.key});

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

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

  Widget content(
      BuildContext context, MapWatchService map, FieldControlController c) {
    return Row(
      children: [
        Expanded(
            child: Column(
          children: [
            Expanded(
                child: ViewMapStack(plug: map.plugMap, children: [
              ViewPlugLoading(map.plugMap),
              ViewMapImage(map.plugMap),
              _ViewTrace(map: map, traceDuration:30.seconds),
              ViewMapTouch(map.plugMap)
            ])),
            _MsgView(),
          ],
        )),
        _ActiveInfoView()
      ],
    );
  }
}

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

  final MapWatchService map;
  final Duration traceDuration;


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


      for (final act in map.activeList) {
        for (final user in act.userList) {
          if (user.isHide.value) {
            continue;
          }
          final trace = user.trace.lastOrNull;
          final traceTailOnMap = <Offset>[];
          final st = user.gameInfo.gameSaveInfo.startAt.toModel();
          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(map.plugMap, trace,
                info: user.name, color: user.flag.value.color));
          }
        }
      }

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

class _ActiveInfoView extends GetView<FieldControlController> {
  @override
  Widget build(BuildContext context) {
    return Obx(() => Container(
          width: 370,
          height: double.infinity,
          color: Colors.white,
          child: ListView(
            children: controller.activeList
                .map((element) => activeView(element))
                .toList(),
          ),
        ));
  }

  Widget activeView(ActiveInfo info) {
    final children = <Widget>[
      Row(children: [
        Text('${info.name} (${info.userList.length}人)'),
        const Spacer(),
        IconButton(
            onPressed: () {
              info.isHide.value = !info.isHide.value;
            },
            icon: info.isHide.value
                ? const Icon(Icons.arrow_drop_down)
                : const Icon(Icons.arrow_drop_up))
      ]),
    ];

    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: [
              Text('广播'),
              const Spacer(),
              Image.asset(Assets.imagesIcCp, height: 20, width: 20),
              Text(' ${info.cpAllCount}'),
              const Spacer(),
              Text('全部隐藏'),
            ],
          ),
        )
      ]);
      children
          .addAll(info.userList.map((e) => _UserInfoView(data: e)).toList());
    }

    return Container(
      decoration: BoxDecoration(
          color: const Color(0xffe0e0e0),
          borderRadius: BorderRadius.circular(5)),
      margin: const EdgeInsets.fromLTRB(9, 12, 9, 12),
      padding: const EdgeInsets.all(9),
      child: Column(
        children: children,
      ),
    );
  }
}

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

  final UserInfo 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: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        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: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text.rich(TextSpan(
                  text: data.name,
                  children: [TextSpan(text: ' [${data.routeName}]')])),
              const SizedBox(height: 5),
              Row(
                children: [
                  container(null, cpInfo, Colors.blue),
                  container(
                      const Icon(
                        Icons.favorite,
                        size: 13,
                        color: Colors.white,
                      ),
                      ' ${hr == 0 ? '--' : hr}',
                      (data.gameInfo.otherInfo.hasHeartRatePercent()?data.gameInfo.otherInfo.heartRatePercent: 0)
                          .toHRPColor()),
                  container(null, paceInfo, data.pace.color)
                ],
              ),
              const SizedBox(height: 5),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('距离 ${data.nextDistance.toString()}'),
                  Text('时间 ${data.duration.toAppString()}'),
                  Text('里程 ${data.distance.toString()}'),
                ],
              )
            ],
          )),
          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),
                )),
          )
        ],
      ),
    );
  }

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

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

  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: 18,
      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();
  }
}
