Example 7 A convex $n$-sided polygon $A_{1} A_{2} \cdots A_{n}$ is inscribed in a unit circle. Find the maximum value of the sum of the squares of all its sides and diagonals, and determine when this maximum value is achieved.

---

The above text has been translated into English while preserving the original text's line breaks and format.
Given that the center of the circle $O$ is the origin, and the complex number corresponding to $A_{k}$ is $a_{k}(1 \leqslant k \leqslant n)$, it is evident that the sum of the squares of all sides and all diagonals can be expressed as $\frac{1}{2} \sum_{1 \leqslant s}\left|a_{s}-a_{t}\right|^{2}$.
By
$$
\begin{array}{l}
\qquad\left|a_{s}-a_{t}\right|^{2}=\left(a_{s}-a_{t}\right)\left(\bar{a}_{s}-\bar{a}_{t}\right)=2-a_{t} \bar{a}_{t}-\bar{a}_{t} a_{s}, \\
\text { hence }(*)=\frac{1}{2} \sum_{1 \leqslant s, 1 \leqslant n}\left(2-a_{t} \bar{a}_{s}-\bar{a}_{t} a_{s}\right) \\
=n^{2}-\frac{1}{2} \sum_{1 \leqslant s, 1 \leqslant a}\left(a_{t} \bar{a}_{s}+\bar{a}_{t} a_{s}\right)=n^{2}-\left|a_{1}+a_{2}+\cdots+a_{n}\right|^{2} \leqslant n^{2} .
\end{array}
$$

And the equality holds when $a_{1}+a_{2}+\cdots+a_{n}=0$. At this point, the circumcenter $O$ of the polygon coincides with the centroid $G$.