import 'package:account_center/common/product_menu_control.dart';
import 'package:account_center/common/res/colors.dart';
import 'package:account_center/common/res/text_style.dart';
import 'package:account_center/common/utils/image_load.dart';
import 'package:account_center/page/account_company/company_auth/widget/common/gesture_tap.dart';
import 'package:account_center/page/enterprise/organization_structure/widget/structure_top_bar.dart';
import 'package:account_center/routes/route_config.dart';
import 'package:account_center/style/widget/bottom_buttons.dart';
import 'package:account_center/style/widget/demartment_manager_tag.dart';
import 'package:account_center/style/widget/my_app_bar.dart';
import 'package:account_center/widget/no_data.dart';
import 'package:account_center/widget/search_bar.dart' as search_bar;
import 'package:flutter/material.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';

import 'member_manage_main_logic.dart';

class MemberManageMainPage extends StatelessWidget {
  final logic =
      Get.find<MemberManageMainLogic>(tag: Get.arguments.hashCode.toString());

  MemberManageMainPage({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MemberManageMainLogic>(
        tag: Get.arguments.hashCode.toString(),
        builder: (logic) {
          return Scaffold(
            appBar: MyAppBar('人员管理'),
            body: Column(
              children: [
                GestureTapWidget(
                  onTap: () {
                    Get.toNamed(RouteConfig.staffManagerMainPage);
                  },
                  child: Container(
                    color: Colors.white,
                    child: search_bar.MySearchBar(
                      enable: false,
                    ),
                  ),
                ),
                SizedBox(
                  height: 10,
                ),
                StructureTopBar(logic.parents),
                Expanded(
                  child: RefreshIndicator(
                    onRefresh: () async {
                      logic.refreshData();
                    },
                    child: ListView(
                      padding: EdgeInsets.symmetric(horizontal: 10),
                      children: [
                        ..._buildDepartment(),
                        ..._buildUser(),
                      ]
                        ..addIf(
                          logic.noDepartmentUserCount > 0,
                          _noDepartmentUser(),
                        )
                        ..add(SizedBox(
                          height: 10,
                        ))
                        ..addIf(
                            logic.departments.isEmpty && logic.users.isEmpty,
                            NoData()),
                    ),
                  ),
                ),
              ],
            ),
            bottomNavigationBar: _buildBottomButton(),
          );
        });
  }

  List<Widget> _buildDepartment() {
    List<Widget> departmentItems = [];
    for (var element in logic.departments) {
      departmentItems.add(SizedBox(
        height: 10,
      ));
      departmentItems.add(_makeDepartItem(element));
    }
    return departmentItems;
  }

  List<Widget> _buildUser() {
    List<Widget> departmentItems = [];
    for (var element in logic.users) {
      departmentItems.add(SizedBox(
        height: 10,
      ));
      departmentItems.add(_makeUserItem(element));
    }
    return departmentItems;
  }

  GestureTapWidget _makeDepartItem(element) {
    return GestureTapWidget(
      onTap: () => logic.clickDepartment(element),
      child: Container(
        padding: EdgeInsets.all(20),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                ImageLoad.svgTagIcon('bumen'),
                hGap15,
                Text(
                  element['departmentName'] +
                      "（" +
                      (element['empNum']?.toString() ?? '0') +
                      '）',
                  style: RTextStyle.mainContentStyle,
                ),
              ],
            ),
            Icon(
              size: 20,
              Icons.arrow_forward_ios,
              color: Colors.grey[400],
            )
          ],
        ),
      ),
    );
  }

  Widget _noDepartmentUser() {
    return GestureTapWidget(
      onTap: logic.toNoDepartmentUserList,
      child: Container(
        padding: EdgeInsets.all(20),
        margin: EdgeInsets.only(top: 10),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                hGap15,
                Text(
                  '未分配部门（${logic.noDepartmentUserCount.toString()}）',
                  style: RTextStyle.mainContentStyle,
                ),
              ],
            ),
            Icon(
              size: 20,
              Icons.arrow_forward_ios,
              color: Colors.grey[400],
            )
          ],
        ),
      ),
    );
  }

  GestureTapWidget _makeUserItem(staff) {
    return GestureTapWidget(
      onTap: () => logic.toUserDetail(staff),
      child: Container(
        padding: EdgeInsets.all(20),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            SizedBox(
              height: 42,
              width: 42,
              child: ImageLoad.user(staff['headImg'],
                  fit: BoxFit.cover, type: ImageTransformerType.circle),
            ),
            hGap15,
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Flexible(
                        child: Text(
                          staff['userName'] ?? '',
                          style: RTextStyle.mainContentStyle,
                        ),
                      ),
                      SizedBox(width: 5),
                      Visibility(
                        visible: staff['userType'] == 2,
                        child: DepartmentManagerTag(title: '负责人'),
                      )
                    ],
                  ),
                  vGap4,
                  Text(
                    staff['userMobile'] ?? '',
                    style: TextStyle(
                      color: RColors.hintColor,
                      fontSize: 12,
                    ),
                  ),
                ],
              ),
            ),
            Icon(
              size: 20,
              Icons.arrow_forward_ios,
              color: Colors.grey[400],
            )
          ],
        ),
      ),
    );
  }

  Widget _buildBottomButton() {
    return logic.isRoot ? _rootBottom() : _normalBottom();
  }

  Widget _normalBottom() {
    List<ButtonItem> items = []
      ..addIf(
        hasMenuPermission('btn_add_member'),
        ButtonItem(title: '添加人员', onClick: logic.addPeople),
      )
      ..addIf(
        hasMenuPermission('btn_new_department'),
        ButtonItem(title: '新建子部门', onClick: logic.createDepartment),
      )
      ..addIf(
        hasMenuPermission('btn_batch_change_department'),
        ButtonItem(title: '批量变更部门', onClick: logic.changeDepartment),
      )
      ..addIf(
        hasMenuPermission('btn_view_department'),
        ButtonItem(
            title: '查看部门',
            onClick: () {
              logic.viewDepartment();
            }),
      );
    return BottomButtons(items: items);
  }

  BottomButtons _rootBottom() {
    return BottomButtons(
      items: []
        ..addIf(
          hasMenuPermission('btn_add_member'),
          ButtonItem(title: '添加人员', onClick: logic.addPeople),
        )
        ..addIf(
          hasMenuPermission('btn_new_department'),
          ButtonItem(title: '新建部门', onClick: logic.createDepartment),
        ),
    );
  }
}
