// 假设树节点的数据结构
interface TreeNode {
    IsLeaf: boolean;
    Node: { Code: string };
    Parent?: TreeNode;
    Children?: TreeNode[];
    IsSelected?: boolean;
    IsExpanded?: boolean;
}

export class TreeViewForTrade {
    private treeData: TreeNode[];
    private expandedNode?: TreeNode;

    constructor(treeData: TreeNode[]) {
        this.treeData = treeData;
    }

    private checkedChange(originalSource: TreeNode) {
        // 找到父节点
        const parent = this.findParent(originalSource);
        if (parent) {
            const children = parent.Children || [];
            children.forEach(child => {
                if (child !== originalSource) {
                    this.setItemExpanded(child, false);
                }
            });
        }
    }

    private findParent(node: TreeNode): TreeNode | undefined {
        const find = (children: TreeNode[]): TreeNode | undefined => {
            for (const child of children) {
                if (child.Children?.includes(node)) {
                    return child;
                }
                if (child.Children) {
                    const result = find(child.Children);
                    if (result) {
                        return result;
                    }
                }
            }
            return undefined;
        };
        return find(this.treeData);
    }

    private setItemExpanded(item: TreeNode | undefined, value: boolean) {
        if (!item) return;
        item.IsExpanded = value;
        item.IsSelected = value;
        if (item.Children) {
            item.Children.forEach(child => {
                this.setItemExpanded(child, value);
            });
        }
    }

    public setSelectedItem(code: string): boolean {
        let result = false;

        const action = (item: TreeNode) => {
            if (item.IsLeaf) {
                if (item.Node.Code === code) {
                    result = true;
                    item.IsSelected = true;
                    item.IsExpanded = true;

                    let node: TreeNode | undefined = item;
                    while (node?.Parent) {
                        node.Parent.IsExpanded = true;
                        node = node.Parent;
                    }
                }
                return;
            }

            if (item.Children) {
                item.Children.forEach(child => action(child));
            }
        };

        this.treeData.forEach(c => action(c));

        return result;
    }
}