import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../../common/api/x_organization_assemble_control.dart';
import '../../../../common/models/index.dart';
import '../../../../common/routers/index.dart';
import '../../../../common/style/index.dart';
import '../../../../common/utils/o2_api_manager.dart';
import 'index.dart';
import 'widgets/widgets.dart';

class ContactPickerPage extends GetView<ContactPickerController> {
  const ContactPickerPage({Key? key}) : super(key: key);

  static Future<dynamic> startPicker(List<ContactPickMode> modes,
      {List<String>? topUnitList,
      String? unitType,
      int? maxNumber = 0,
      bool? multiple = false,
      List<String>? dutyList,
      List<String>? initDeptList,
      List<String>? initIdList,
      List<String>? initGroupList,
      List<String>? initUserList}) async {
    final args = ContactPickerArguments(
        pickerModes: modes,
        topUnitList: topUnitList,
        unitType: unitType,
        maxNumber: maxNumber,
        multiple: multiple,
        dutyList: dutyList,
        initDeptList: initDeptList,
        initIdList: initIdList,
        initGroupList: initGroupList,
        initUserList: initUserList);
    return await Get.toNamed(O2OARoutes.homeContactPicker, arguments: args);
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ContactPickerController>(
      builder: (_) {
        return Obx(() {
          if (controller.state.tabs.isEmpty) {
            return const CircularProgressIndicator();
          } else {
            if (controller.state.tabs.length == 1) {
              return singlePicker(context);
            }
            return multiplePickers(context);
          }
        });
      },
    );
  }

  Widget pickerContentView(ContactPickMode m) {
    switch (m) {
      case ContactPickMode.departmentPicker:
        return OrgPickerPage(initData: controller.pickerArguments!);
      case ContactPickMode.identityPicker:
        return PersonOrIdentityPickerPage(
            mode: m, initData: controller.pickerArguments!);
      case ContactPickMode.groupPicker:
        return GroupPickerPage(initData: controller.pickerArguments!);
      case ContactPickMode.personPicker:
        return PersonOrIdentityPickerPage(
            mode: m, initData: controller.pickerArguments!);
    }
  }

  Widget singlePicker(BuildContext context) {
    return Obx(() {
      final num = controller.state.identityPickedList.length +
          controller.state.personPickedList.length +
          controller.state.unitPickedList.length +
          controller.state.groupPickedList.length;
      final chooseTitle = '${'contact_picker_btn_title_choose'.tr}($num)';
      return Scaffold(
        appBar: AppBar(
          title: Text(controller.tabTitle(controller.state.tabs[0]),
              style: AppTheme.whitePrimaryTextStyle),
          actions: [
            TextButton(
                onPressed: controller.choose,
                child: Text(chooseTitle, style: AppTheme.whitePrimaryTextStyle))
          ],
        ),
        backgroundColor: Theme.of(context).scaffoldBackgroundColor,
        body: SafeArea(
            child: Column(children: [
          Expanded(
            flex: 1,
            child: pickerContentView(controller.state.tabs[0]),
          ),
          _choosedBarView(context),
        ])),
      );
    });
  }

  Widget multiplePickers(BuildContext context) {
    return Obx(() {
      final num = controller.state.identityPickedList.length +
          controller.state.personPickedList.length +
          controller.state.unitPickedList.length +
          controller.state.groupPickedList.length;
      final chooseTitle = '${'contact_picker_btn_title_choose'.tr}($num)';
      return DefaultTabController(
          length: controller.state.tabs.length,
          child: Scaffold(
            appBar: AppBar(
              title: Text('contact_picker_title'.tr),
              actions: [
                TextButton(
                    onPressed: controller.choose,
                    child: Text(chooseTitle,
                        style: AppTheme.whitePrimaryTextStyle))
              ],
              bottom: TabBar(
                  //生成Tab菜单
                  tabs: controller.state.tabs
                      .map((e) => Tab(
                          child: Text(controller.tabTitle(e),
                              style: AppTheme.whitePrimaryTextStyle)))
                      .toList()),
            ),
            backgroundColor: Theme.of(context).scaffoldBackgroundColor,
            body: SafeArea(
                child: Column(children: [
              Expanded(
                flex: 1,
                child: TabBarView(
                  children: controller.state.tabs.map((m) {
                    return pickerContentView(m);
                  }).toList(),
                ),
              ),
              _choosedBarView(context),
            ])),
          ));
    });
  }

  String _choosedBarMessage(int num) {
    final buffer = StringBuffer('contact_picker_choosed'.tr);

    List<Map<String, dynamic>> listItems = [
      {
        'list': controller.state.personPickedList,
        'key': 'contact_picker_choosed_person_num'
      },
      {
        'list': controller.state.unitPickedList,
        'key': 'contact_picker_choosed_unit_num'
      },
      {
        'list': controller.state.groupPickedList,
        'key': 'contact_picker_choosed_group_num'
      },
      {
        'list': controller.state.identityPickedList,
        'key': 'contact_picker_choosed_identity_num'
      },
    ];

    for (final item in listItems) {
      if (item['list'].length > 0) {
        final num = '${item['list'].length}';
        buffer.write(' ${'${item['key']}'.trArgs([num])} ');
      }
    }

    return buffer.toString();
  }

  Widget _choosedBarView(BuildContext context) {
    return GestureDetector(
        child: Container(
          color: Theme.of(context).colorScheme.background,
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 0),
          child: Column(children: [
            const Divider(height: 1, color: AppColor.borderColor),
            const SizedBox(height: 16),
            Row(children: [
              Expanded(
                  flex: 1,
                  child: Obx(() {
                    final num = controller.state.identityPickedList.length +
                        controller.state.personPickedList.length +
                        controller.state.unitPickedList.length +
                        controller.state.groupPickedList.length;
                    return Text(_choosedBarMessage(num),
                        style: Theme.of(context).textTheme.bodySmall,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis);
                  })),
              const SizedBox(width: 10),
              Icon(
                Icons.arrow_drop_up,
                color: Theme.of(context).colorScheme.primary,
                size: 28,
              ),
              const SizedBox(width: 5)
            ]),
            const SizedBox(height: 16),
          ]),
        ),
        onTap: () => openChoosedList(context));
  }

  /// 打开已选列表
  void openChoosedList(BuildContext context) {
    final num = controller.state.identityPickedList.length +
        controller.state.personPickedList.length +
        controller.state.unitPickedList.length +
        controller.state.groupPickedList.length;
    if (num == 0) {
      return;
    }

    showModalBottomSheet(
        context: context,
        builder: (context) => StatefulBuilder(builder: (context, setState) {
              return SafeArea(
                  child: Column(
                children: [
                  Expanded(
                    flex: 1,
                    child: ListView(
                      children: [
                        if (controller.state.unitPickedList.length > 0)
                          ..._choosedUnitList(context, setState), const SizedBox(height: 10),
                        if (controller.state.personPickedList.length > 0)
                          ..._choosedPersonList(context, setState), const SizedBox(height: 10),
                        if (controller.state.groupPickedList.length > 0)
                          ..._choosedGroupList(context, setState), const SizedBox(height: 10),
                        if (controller.state.identityPickedList.length > 0)
                          ..._choosedIdentityList(context, setState)
                      ],
                    ),
                  ),
                  Container(
                    color: Theme.of(context).colorScheme.background,
                    height: 4,
                  ),
                  ListTile(
                    onTap: () => Navigator.pop(context),
                    title: Align(
                      alignment: Alignment.center,
                      child: Text('cancel'.tr,
                          style: Theme.of(context).textTheme.bodyLarge),
                    ),
                  )
                ],
              ));
            }));
  }

  List<Widget> _choosedUnitList(BuildContext context, StateSetter setState) {
    return controller.state.unitPickedList.map((element) {
      var orgName = element.name ?? '';
      var oneName = orgName;
      if (orgName.length > 1) {
        oneName = oneName.substring(0, 1);
      }
      return ListTile(
        leading: SizedBox(
          width: 32,
          height: 32,
          child: CircleAvatar(
            radius: 32,
            backgroundColor: Theme.of(context).colorScheme.primary,
            child: Text(oneName, style: const TextStyle(color: Colors.white)),
          ),
        ),
        title: Text(orgName),
        trailing: TextButton(
            onPressed: (() {
              setState(() {
                controller.removeUnit(element);
              });
            }),
            child: Text('contact_picker_choosed_remove'.tr)),
      );
    }).toList();
  }

  List<Widget> _choosedPersonList(BuildContext context, StateSetter setState) {
    return controller.state.personPickedList.map((element) {
      String? personIcon =
          OrganizationControlService.to.iconUrl(element.person!);
      return ListTile(
        leading: SizedBox(
          width: 32,
          height: 32,
          child: CircleAvatar(
            radius: 32,
            backgroundColor: Colors.white,
            backgroundImage: NetworkImage(personIcon, headers: {
              O2ApiManager.instance.tokenName:
                  O2ApiManager.instance.o2User?.token ?? ''
            }),
          ),
        ),
        title: Text(element.name ?? ''),
        trailing: TextButton(
            onPressed: (() {
              setState(() {
                controller.removePerson(element);
              });
            }),
            child: Text('contact_picker_choosed_remove'.tr)),
      );
    }).toList();
  }

  List<Widget> _choosedIdentityList(
      BuildContext context, StateSetter setState) {
    return controller.state.identityPickedList.map((element) {
      String? personIcon =
          OrganizationControlService.to.iconUrl(element.person!);
      return ListTile(
        leading: SizedBox(
          width: 32,
          height: 32,
          child: CircleAvatar(
            radius: 32,
            backgroundColor: Colors.white,
            backgroundImage: NetworkImage(personIcon, headers: {
              O2ApiManager.instance.tokenName:
                  O2ApiManager.instance.o2User?.token ?? ''
            }),
          ),
        ),
        title: Text(element.name ?? ''),
        trailing: TextButton(
            onPressed: (() {
              setState(() {
                controller.removeIdentity(element);
              });
            }),
            child: Text('contact_picker_choosed_remove'.tr)),
      );
    }).toList();
  }

  List<Widget> _choosedGroupList(BuildContext context, StateSetter setState) {
    return controller.state.groupPickedList.map((element) {
      var orgName = element.name ?? '';
      var oneName = orgName;
      if (orgName.length > 1) {
        oneName = oneName.substring(0, 1);
      }
      return ListTile(
        leading: SizedBox(
          width: 32,
          height: 32,
          child: CircleAvatar(
            radius: 32,
            backgroundColor: Theme.of(context).colorScheme.primary,
            child: Text(oneName, style: const TextStyle(color: Colors.white)),
          ),
        ),
        title: Text(orgName),
        trailing: TextButton(
            onPressed: (() {
              setState(() {
                controller.removeGroup(element);
              });
            }),
            child: Text('contact_picker_choosed_remove'.tr)),
      );
    }).toList();
  }
}
