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/style/style_params.dart';
import 'package:account_center/style/style_widget.dart';
import 'package:account_center/style/widget/my_app_bar.dart';
import 'package:account_center/widget/no_data.dart';
import 'package:flutter/material.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';

import 'organization_structure_logic.dart';

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

  OrganizationStructurePage({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<OrganizationStructureLogic>(
        tag: Get.arguments.hashCode.toString(),
        builder: (s) {
          return MyScaffold(
            appBar: MyAppBar(state.title),
            body: Column(
              children: [
                Visibility(
                  visible: state.parents.isNotEmpty,
                  child: StructureTopBar(state.parents),
                ),
                Expanded(
                  child: RefreshIndicator(
                    onRefresh: () async {
                      logic.requestData();
                    },
                    child: ListView(
                      padding: EdgeInsets.symmetric(horizontal: 10),
                      children: [
                        ..._buildDepartment(),
                        ..._buildPositions(),
                      ]..addIf(
                          state.departments.isEmpty && state.positions.isEmpty,
                          NoData()),
                    ),
                  ),
                ),
                Visibility(
                    visible: !logic.departmentManagerRoot,
                    child: _buildBottomButton()),
              ],
            ),
          );
        });
  }

  bool _canCreateDepartment() {
    return hasMenuPermission(logic.fromMyDepartment
        ? 'btn_new_department_my'
        : 'btn_new_department_');
  }

  bool _canCreatePosition() {
    return hasMenuPermission(
        logic.fromMyDepartment ? 'btn_new_position_my' : 'btn_new_position_');
  }

  Widget _buildBottomButton() {
    return state.isRoot
        ? Visibility(
            visible: _canCreateDepartment(),
            child: StyleWidget.bottomButtonRow([
              Expanded(
                child: StyleWidget.textButton('新建部门', logic.createDepartment),
              ),
              _bottomBarSplitLine(),
              Expanded(
                child: StyleWidget.textButton('添加人员', logic.createDepartment),
              ),
            ]),
          )
        : StyleWidget.bottomButtonRow(
            []
              ..addIf(
                _canCreatePosition(),
                _textButton(
                  '添加人员',
                  () {
                    logic.newPosition();
                  },
                ),
              )
              ..addAllIf(
                _canCreateDepartment(),
                [
                  _bottomBarSplitLine(),
                  _textButton(
                    '新建子部门',
                    () {
                      logic.createDepartment();
                    },
                  ),
                ],
              )
              ..addAllIf(
                true,
                [_bottomBarSplitLine(), _textButton('更多', logic.more)],
              ),
          );
  }

  Widget _textButton(String title, void Function() onTab) {
    return Expanded(
      flex: 1,
      child: Center(
        child: TextButton(
          onPressed: onTab,
          child: Text(
            title,
            style: TextStyle(color: StyleParams.themeColor),
          ),
        ),
      ),
    );
  }

  Container _bottomBarSplitLine() {
    return Container(
      color: Color(0xffE1E1E2),
      width: 0.5,
      height: 24,
    );
  }

  /// 部门item
  List<Widget> _buildDepartment() {
    List<Widget> departmentItems = [];
    for (var element in state.departments) {
      departmentItems.add(SizedBox(
        height: 10,
      ));
      departmentItems.add(_makeItem(element, true));
    }
    return departmentItems;
  }

  GestureTapWidget _makeItem(element, bool isDepart) {
    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: [
                // AssetImageWidget(
                //   imgFileName: isDepart ? 'ic_department' : 'ic_position',
                //   height: 40,
                //   width: 40,
                // ),
                ImageLoad.svgTagIcon(isDepart ? 'bumen' : 'zhiwei'),
                hGap15,
                Text(
                  element['departmentName'] +
                      "（" +
                      (element['empNum']?.toString() ?? '0') +
                      '）',
                  style: RTextStyle.mainContentStyle,
                ),
              ]..addIf(
                  element['adminPosition'] == 1,
                  Container(
                    color: Color(0x0f1F59EF),
                    padding: EdgeInsets.symmetric(horizontal: 5, vertical: 3),
                    child: Text(
                      '管理员',
                      style: TextStyle(
                          fontSize: 10, color: StyleParams.themeColor),
                    ),
                  )),
            ),
            Icon(
              size: 20,
              Icons.arrow_forward_ios,
              color: Colors.grey[400],
            )
          ],
        ),
      ),
    );
  }

  /// 职位item
  List<Widget> _buildPositions() {
    List<Widget> departmentItems = [];
    if (state.positions.isNotEmpty) {
      departmentItems.add(Container(
        margin: EdgeInsets.only(left: 20, top: 15),
        child: Text(
          '职位',
          style: TextStyle(fontSize: 17, color: RColors.mainContentColor),
        ),
      ));
    }
    for (var element in state.positions) {
      departmentItems.add(SizedBox(
        height: 10,
      ));
      departmentItems.add(_makeItem(element, false));
    }
    return departmentItems;
  }
}
