import { MyBetaModalFormProps, MyButtons } from '@/common';
import { Apis } from '@/gen/Apis';
import { ProCard } from '@ant-design/pro-components';
import { message, Space, Tree, TreeProps } from 'antd';
import { DataNode } from 'antd/es/tree';
import { useEffect, useState } from 'react';

export default function Index(props: MyBetaModalFormProps) {
  const [treeData, setTreeData] = useState<DataNode[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  const processTree = (item: any): DataNode => {
    return {
      ...item,
      key: item.id,
      title: item.id + '_' + item.name,
      children: item.children?.map(processTree),
    };
  };

  // 提取所有叶子节点的 key，用于过滤 checkedKeys
  const getLeafKeys = (nodes: DataNode[]): React.Key[] => {
    const keys: React.Key[] = [];
    const traverse = (node: DataNode) => {
      if (!node.children || node.children.length === 0) {
        keys.push(node.key);
      } else {
        node.children.forEach(traverse);
      }
    };
    nodes.forEach(traverse);
    return keys;
  };

  const getPermissions = (data: DataNode[]) => {
    //获取已经配置的，菜单
    Apis.Company.CompanyPermissions.GetPermissions({
      companies_id: props?.item?.id || 0,
    }).then((res: any) => {
      const leafKeys = getLeafKeys(data);
      const leafKeySet = new Set(leafKeys.map(String));
      const ids = res?.data?.permissions_ids || [];
      // 只保留叶子节点的 key，避免父节点 key 导致 Tree 全选
      const filteredKeys = ids.filter((id: React.Key) =>
        leafKeySet.has(String(id)),
      );
      setCheckedKeys(filteredKeys);
    });
  };

  const getPermissionTree = () => {
    //获取机构可配置菜单
    Apis.Company.CompanyPermissions.PermissionTree().then((res: any) => {
      const data = res.data?.map(processTree);
      setTreeData(data);
      getPermissions(data);
    });
  };

  useEffect(() => {
    getPermissionTree();
  }, []);

  const onCheck: TreeProps['onCheck'] = (checkedKeysValue) => {
    setCheckedKeys(checkedKeysValue as React.Key[]);
  };

  return (treeData?.length ?? 0) > 0 ? (
    <ProCard
      extra={[
        <MyButtons.Default
          title="保存"
          size="middle"
          type="primary"
          key="save"
          onClick={() => {
            Apis.Company.CompanyPermissions.SetPermissions({
              companies_id: props?.item?.id || 0,
              permissions_ids: checkedKeys || [],
            }).then(() => {
              message.success('保存成功');
            });
          }}
        />,
      ]}
    >
      <Space direction="vertical">
        <Tree
          checkable
          defaultExpandAll
          treeData={treeData}
          onCheck={onCheck}
          checkedKeys={checkedKeys || []}
          {...props}
        />
      </Space>
    </ProCard>
  ) : (
    <></>
  );
}
