import 'dart:collection';

import 'package:app_business/service/api.dart';
import 'package:track_common/widget.dart';

class SettingsController extends GetxController {
  final rules = HashMap<int, Rule>().obs;

  @override
  void onInit() {
    final id = Get.arguments as int;
    Get.find<ApiService>()
        .stub
        .toActivityRulesQuery(IdRequest()..id = Int64(id))
        .then((p0) {
      rules.update((val) {
        for (final (i, e) in p0.list.indexed) {
          val![e.arrId] = Rule()
            ..id = e.arrId
            ..idx = i
            ..name = e.arName
            ..isAppLock = e.isLock
            ..isAllowEditAppLock = e.toIsLockEdit
            ..isLockAll = e.toLock
            ..value = e.arType == 1
                ? (RuleValueBool()..value = e.arValue == 'true')
                : (RuleValueArrStr()
                  ..value = e.arValue
                  ..options = e.arValueSelectList
                      .map((e) => RuleValueArrStrOption()
                        ..value = e.arValueSelect
                        ..show = e.arStrSelect)
                      .toList());
        }
      });
    });

    super.onInit();
  }
}

class DialogSettings extends GetView<SettingsController> {
  const DialogSettings({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
        init: SettingsController(),
        builder: (ctx) {
          return AlertDialog(
            surfaceTintColor: Colors.white,
            title: const Center(child: Text('规则设置')),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Obx(() => _list(context)),
                Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 45),
                    child: AppButton.confirm(
                        width: double.infinity,
                        height: 38,
                        child: const Text('确认'),
                        onPressed: () {
                          final r = controller.rules.value.values;
                          Get.back(result: r);
                        }))
              ],
            ),
          );
        });
  }

  Widget _list(BuildContext context) {
    final l = controller.rules.value.values.toList();
    l.sort((a, b) => a.idx.compareTo(b.idx));

    return SizedBox(
        height: context.height * 0.6,
        width: 470,
        child: ListView(
          children: l.map((data) => _RuleElem(data)).toList(),
        ));
  }
}

class _RuleElem extends GetView<SettingsController> {
  const _RuleElem(this.data);

  final Rule data;
  @override
  Widget build(BuildContext context) {
    final value = data.value;
    Widget? option;

    if (value is RuleValueBool) {
      option = Switch(
          value: value.value,
          activeColor: Colors.blue,
          onChanged: data.isLockAll
              ? null
              : (b) {
                  value.value = b;
                  controller.rules.update((val) {
                    val![data.id] = data;
                  });
                });
    }

    if (value is RuleValueArrStr) {
      option = Row(
        mainAxisSize: MainAxisSize.min,
        children: value.options
            .map((e) => _Radio(
                value: e.value,
                show: e.show,
                groupValue: value.value,
                onChanged: data.isLockAll
                    ? null
                    : (v) {
                        if (v != null) {
                          value.value = v;
                          controller.rules.update((val) {
                            val![data.id] = data;
                          });
                        }
                      }))
            .toList(),
      );
    }

    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        SizedBox(width: 110, child: Text(data.name, textAlign: TextAlign.end)),
        const SizedBox(width: 22),
        IconButton(
            onPressed: !data.isAllowEditAppLock || data.isLockAll
                ? null
                : () {
                    controller.rules.update((val) {
                      val![data.id]!.isAppLock = !val[data.id]!.isAppLock;
                    });
                  },
            icon: Icon(
              data.isAppLock ? Icons.lock_outline : Icons.lock_open_outlined,
              color: data.isAppLock ? Colors.deepOrange : Colors.amber,
            )),
        const SizedBox(width: 12),
        option!,
      ],
    );
  }
}

class _Radio extends StatelessWidget {
  const _Radio(
      {required this.value,
      required this.show,
      required this.groupValue,
      required this.onChanged});
  final String value;
  final String show;
  final String groupValue;
  final void Function(String?)? onChanged;

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Radio(
            activeColor: Colors.blue,
            value: value,
            groupValue: groupValue,
            onChanged: onChanged),
        Text(show),
      ],
    );
  }
}
