import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/pages/organization/org_personnel/widgets/org_card_build.dart';
import 'package:flyinsono/pages/organization/org_personnel/widgets/org_structure.dart';

import 'index.dart';

/// 组织架构 选择类
class PublicChoice {
  PublicChoice({
    required this.name,
    required this.code,
    required this.type,
    required this.isHover,
    required this.isActive,
    this.organizationCode,
    this.fitDepartmentCode,
  });

  /// 是否悬浮状态
  bool isHover;

  /// 是否选中状态
  bool isActive;

  /// 组织架构名字
  final String name;

  /// 组织架构编码
  final String code;

  /// 组织架构类型
  final String type;

  /// 当前组织编码
  final String? organizationCode;

  /// 最上级的组织编码
  final String? fitDepartmentCode;
}

/// 用户编辑类
class UserEditInfo {
  UserEditInfo({
    this.organizationCode,
    this.positionCodes,
    this.rankCodes,
    this.userCode,
  });

  /// 用户组织编码
  String? organizationCode;

  /// 岗位身份编码
  String? positionCodes;

  /// 职称编码
  String? rankCodes;

  /// 用户编码
  String? userCode;
}

///组织页面
class OrgPesonnelPage extends FisView<OrgPesonnelController> implements FPage {
  const OrgPesonnelPage({this.pageName = 'OrgPesonnelPage', Key? key})
      : super(key: key);
  @override
  final String pageName;
  @override
  FWidget build(BuildContext context) {
    return context.fResponsiveVoid(
      mobile: () => _MobileLayout(businessParent: this),
      desktop: () => _DesktopLayout(businessParent: this),
    );
  }
}

class _DesktopLayout extends FisView<OrgPesonnelController> implements FWidget {
  _DesktopLayout({required this.businessParent, Key? key}) : super(key: key);

  ///父级节点
  final FPage businessParent;
  @override
  FWidget build(BuildContext context) {
    return FContainer(
      margin: EdgeInsets.all(15),
      color: Colors.white,
      child: FRow(
        children: [
          FContainer(
            width: 450,
            child: FFlex(
              direction: Axis.vertical,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _buildSearchInput(),
                FObx(() {
                  return OrgCard(
                    name: i18nBook.organization.orgStructure.t,
                    type: OrgType.companyPersonnel,
                    icon: FIcon(
                      FIcons.org_structure,
                      color: FTheme.ins.colorScheme.primary,
                    ),
                    mList: controller.state.companyPersonnelList,
                    addCard: () => controller.openOrgStrutureDialog(null),
                    deleteCard: (val) =>
                        controller.deleteUserTab(val, this.businessParent),
                    editCard: (obj) => controller.openOrgStrutureDialog(obj),
                    clickCard: (obj) => controller.orgStructureFiltering(obj),
                  );
                }),
                FSizedBox(
                  height: 15,
                ),
                FObx(() {
                  return OrgCard(
                    name: i18nBook.organization.positionIdentity.t,
                    type: OrgType.position,
                    icon: FIcon(
                      FIcons.post_identity,
                      color: FTheme.ins.colorScheme.primary,
                    ),
                    mList: controller.state.positionList,
                    clickCard: (obj) => controller.postScreening(obj),
                  );
                }),
                FSizedBox(
                  height: 15,
                ),
                FObx(
                  () {
                    return OrgCard(
                      name: i18nBook.organization.workTitle.t,
                      type: OrgType.professional,
                      icon: FIcon(
                        FIcons.org_title,
                        color: FTheme.ins.colorScheme.primary,
                      ),
                      addCard: () => controller.editRankDialog(null),
                      deleteCard: (val) =>
                          controller.deleteProfessional(val, businessParent),
                      clickCard: (obj) => controller.titleScreening(obj),
                      editCard: (obj) => controller.editRankDialog(obj),
                      mList: controller.state.professionalList,
                    );
                  },
                ),
              ],
            ),
          ),
          FContainer(
            width: 10,
            color: Color.fromRGBO(241, 245, 248, 1),
          ),
          _buildOrgTableContent(),
        ],
      ),
    );
  }

  ///表格顶部按钮
  FWidget _buildTopOperateButtons() {
    return FContainer(
      height: 54,
      child: FFlex(
        direction: Axis.horizontal,
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          FElevatedButton(
            name: "makeSureDelete",
            businessParent: businessParent,
            onPressed: () {
              controller.makeSureDelete();
            },
            style: ButtonStyle(
              padding: MaterialStateProperty.all(
                EdgeInsets.symmetric(
                  vertical: 15,
                  horizontal: 25,
                ),
              ),
            ),
            child: FText(i18nBook.common.remove.t),
          ),
          const FSizedBox(width: 15),
        ],
      ),
    );
  }

  ///搜索输入框
  FWidget _buildSearchInput() {
    return FContainer(
      margin: EdgeInsets.all(10),
      color: Colors.white,
      child: FRow(
        children: [
          FExpanded(
            child: FContainer(
              height: 45,
              child: FRow(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  FBorderInput(
                    hintSize: 16,
                    contentSize: 16,
                    maxLength: 20,
                    focusNode: controller.searchFocusNode,
                    borderColor: Color.fromRGBO(234, 234, 234, 1),
                    suffixIcon: FMaterial(
                      color: Colors.transparent,
                      child: FIconButton(
                        businessParent: businessParent,
                        onPressed: () => controller.searchSelect(),
                        name: "searchSelect",
                        icon: FIcon(
                          Icons.search,
                        ),
                      ),
                    ),
                    height: 45,
                    hintText: i18nBook.common.search.t,
                    onChanged: (value) {
                      controller.state.searchText = value;
                    },
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  ///组织表格Header
  List<FTableColumn<UserDTO>> _buildOrgTableHeader() {
    return <FTableColumn<UserDTO>>[
      FTableColumn<UserDTO>(
        headerText: i18nBook.organization.avatar.t,
        render: (_, i) => FCenter(
          child: (_.headImageUrl.toString() == '')
              ? FAvatar(
                  imageProvider: AssetImage("assets/images/avatar_man.png"),
                  size: 30,
                )
              : FAvatar(
                  imageProvider: NetworkImage(_.headImageUrl.toString()),
                  size: 30,
                  errorBuilder: (context, error, stackTrace) {
                    return FImage.asset(
                      'assets/images/avatar_man.png',
                      fit: BoxFit.cover,
                    );
                  },
                ),
        ),
      ),
      FTableColumn<UserDTO>(
        headerText: i18nBook.common.fullName.t,
        render: (rowData, index) => FCenter(
          child: FText(
            rowData.displayName.toString(),
            style: const TextStyle(
              fontSize: 16,
            ),
          ),
        ),
      ),
      FTableColumn<UserDTO>(
        headerText: i18nBook.common.mobileNumber.t,
        render: (rowData, index) => FCenter(
          child: FText(
            rowData.phone.toString(),
            style: const TextStyle(
              fontSize: 16,
            ),
          ),
        ),
      ),
      FTableColumn<UserDTO>(
        headerText: i18nBook.organization.positionIdentity.t,
        render: (rowData, index) => FCenter(
          child: FText(
            rowData.positionName.toString(),
            style: const TextStyle(
              fontSize: 16,
            ),
          ),
        ),
      ),
      FTableColumn<UserDTO>(
        headerText: i18nBook.organization.workTitle.t,
        render: (rowData, index) => FCenter(
          child: FText(
            rowData.rankName.toString(),
            style: const TextStyle(
              fontSize: 16,
            ),
          ),
        ),
      ),
      FTableColumn<UserDTO>(
          headerText: i18nBook.common.operation.t,
          render: (rowData, index) {
            var userCode = rowData.userCode ?? '';
            return FCenter(
              child: FIconButton(
                businessParent: businessParent,
                name: "openUserEditDialog:$userCode",
                icon: FIcon(
                  Icons.edit_rounded,
                  color: Color.fromRGBO(61, 146, 252, 1),
                ),
                onPressed: () => controller.openUserEditDialog(userCode),
              ),
            );
          }),
    ];
  }

  ///表格内容
  FWidget _buildOrgTableContent() {
    final columns = _buildOrgTableHeader();
    return FExpanded(
      child: FContainer(
        margin: EdgeInsets.symmetric(vertical: 10),
        child: FFlex(
          direction: Axis.vertical,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildTopOperateButtons(),
            FExpanded(
              child: FObx(
                () {
                  return FTable<UserDTO>(
                    autoHeight: false,
                    noDataHintText: i18nBook.common.noData.t,
                    columns: columns,
                    source: controller.state.tableDataSource,
                    loading: controller.state.tableLoading,
                    showSelect: true,
                    selecteds: controller.selectedIdxs,
                    onRowSelected: (value, index, idxs) =>
                        controller.getSelectedIdxs(idxs),
                    onAllRowsSelected: (value, idxs) =>
                        controller.getSelectedIdxs(idxs),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _MobileLayout extends FisView<OrgPesonnelController> implements FWidget {
  _MobileLayout({required this.businessParent, Key? key}) : super(key: key);

  ///父级节点
  final FPage businessParent;
  @override
  FWidget build(BuildContext context) {
    return FScaffold(
      body: FContainer(
        child: FObx(
          () => SelectOrgStructure(
            name: controller.state.organizationName,
            list: controller.state.companyPersonnelList,
          ),
        ),
      ),
    );
  }
}
