import {
  MyButtons,
  MyColumns,
  MyPageContainer,
  MyProTableProps,
  MyTableActions,
  MyToolBarActions,
} from '@/common';
import { Apis } from '@/gen/Apis';
import { OrganizationsTypeEnum } from '@/gen/Enums';
import { ProTable } from '@ant-design/pro-components';
import { Space } from 'antd';
import { useRef, useState } from 'react';
import NextOrganizationChange from './modals/NextOrganizationChange';
import OrganizationChange from './modals/OrganizationChange';
import OrganizationCreate from './modals/OrganizationCreate';
import OrganizationUpdate from './modals/OrganizationUpdate';

const collectExpandKeys = (data: any[], depth = 0): React.Key[] => {
  if (!data || depth >= 2) return [];
  let keys: React.Key[] = [];
  data.forEach((item: any) => {
    if (item.children && item.children.length > 0) {
      keys.push(item.id);
      keys.push(...collectExpandKeys(item.children, depth + 1));
    }
  });
  return keys;
};

export default function Index({ title = '组织管理' }) {
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const hasExpanded = useRef(false);

  return (
    <MyPageContainer
      title={title}
      enableTabs={true}
      tabKey="company-organizations"
      tabLabel={title}
    >
      <ProTable
        {...MyProTableProps.props}
        pagination={false}
        request={async (params, sort) => {
          const result = await MyProTableProps.request(
            params,
            sort,
            Apis.Company.Organizations.TreeList,
          );
          if (result.data && !hasExpanded.current) {
            setExpandedKeys(collectExpandKeys(result.data));
            hasExpanded.current = true;
          }
          return result;
        }}
        headerTitle="组织列表"
        options={false}
        expandable={{
          expandedRowKeys: expandedKeys,
          onExpandedRowsChange: (keys: readonly React.Key[]) =>
            setExpandedKeys([...keys]),
          childrenColumnName: 'children',
        }}
        toolBarRender={(action) => [
          <MyToolBarActions
            key="toolbar"
            actions={{
              add: (
                <OrganizationCreate
                  key="Create"
                  reload={action?.reload}
                  title="组织"
                />
              ),
            }}
          />,
        ]}
        columns={[
          {
            title: '组织名称',
            dataIndex: 'name',
            width: 300,
          },
          MyColumns.EnumTag({
            title: '类型',
            dataIndex: 'type',
            valueEnum: OrganizationsTypeEnum,
            search: false,
            width: 120,
          }),
          MyColumns.Option({
            fixed: 'right',
            width: 280,
            render: (_, item: any, index, action) => (
              <Space key={index}>
                <MyTableActions
                  actions={{
                    update: (
                      <OrganizationUpdate
                        item={item}
                        reload={action?.reload}
                        title="组织"
                      />
                    ),
                    change: (
                      <OrganizationChange
                        item={{ ...item, companies_id: item?.companies_id }}
                        reload={action?.reload}
                        title="组织"
                      />
                    ),
                    next: (
                      <NextOrganizationChange
                        item={{ ...item, companies_id: item?.companies_id }}
                        reload={action?.reload}
                        title="下级组织"
                      />
                    ),
                    delete: (
                      <MyButtons.Delete
                        onConfirm={() =>
                          Apis.Company.Organizations.Delete({
                            id: item.id,
                          }).then(() => action?.reload())
                        }
                      />
                    ),
                  }}
                />
              </Space>
            ),
          }),
        ]}
      />
    </MyPageContainer>
  );
}
