#!/usr/bin/env python3
import sys
import re
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont

class Calculator(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("计算器")
        self.setFixedSize(380, 580)
        self.setStyleSheet(self.get_material_style())
        
        self.expression = ""
        self.init_ui()
    
    def init_ui(self):
        central = QWidget()
        self.setCentralWidget(central)
        layout = QVBoxLayout(central)
        layout.setSpacing(8)
        
        # 显示区
        self.display = QLineEdit()
        self.display.setReadOnly(True)
        self.display.setAlignment(Qt.AlignRight)
        self.display.setFont(QFont("Roboto", 40))
        self.display.setStyleSheet("background: transparent; border: none; padding: 20px 10px;")
        layout.addWidget(self.display)
        
        # 按钮网格
        grid = QGridLayout()
        grid.setSpacing(8)
        
        buttons = [
            ('C', 0, 0), ('±', 0, 1), ('%', 0, 2), ('÷', 0, 3),
            ('7', 1, 0), ('8', 1, 1), ('9', 1, 2), ('×', 1, 3),
            ('4', 2, 0), ('5', 2, 1), ('6', 2, 2), ('-', 2, 3),
            ('1', 3, 0), ('2', 3, 1), ('3', 3, 2), ('+', 3, 3),
            ('0', 4, 0, 1, 2), ('.', 4, 2), ('=', 4, 3),
        ]
        
        for b in buttons:
            text = b[0]
            row, col = b[1], b[2]
            rowspan = b[3] if len(b) > 3 else 1
            colspan = b[4] if len(b) > 4 else 1
            
            btn = QPushButton(text)
            btn.setFixedSize(160 if text == '0' else 70, 70)
            btn.setFont(QFont("Roboto", 22))
            
            # 样式分类
            if text in ['÷', '×', '-', '+', '=']:
                btn.setProperty("class", "operator")
            elif text == 'C':
                btn.setProperty("class", "function")
            else:
                btn.setProperty("class", "number")
            
            btn.clicked.connect(lambda checked, t=text: self.handle_click(t))
            grid.addWidget(btn, row, col, rowspan, colspan)
        
        layout.addLayout(grid)
    
    def get_material_style(self):
        return """
        QWidget {
            background: #1E1E1E;
        }
        QLineEdit {
            color: white;
        }
        QPushButton {
            border: none;
            border-radius: 35px;
            font-weight: 500;
        }
        QPushButton[class="number"] {
            background: #2D2D2D;
            color: white;
        }
        QPushButton[class="number"]:hover {
            background: #3D3D3D;
        }
        QPushButton[class="number"]:pressed {
            background: #1D1D1D;
        }
        QPushButton[class="operator"] {
            background: #FF6D00;
            color: white;
        }
        QPushButton[class="operator"]:hover {
            background: #FF9100;
        }
        QPushButton[class="operator"]:pressed {
            background: #DD5500;
        }
        QPushButton[class="function"] {
            background: #3D3D3D;
            color: white;
        }
        QPushButton[class="function"]:hover {
            background: #4D4D4D;
        }
        """
    
    def handle_click(self, text):
        if text == 'C':
            self.expression = ""
            self.display.setText("")
        elif text == '=':
            try:
                # 安全计算
                expr = self.expression.replace('×', '*').replace('÷', '/')
                if re.match(r'^[\d+\-*/().%\s]+$', expr):
                    result = eval(expr)
                    self.display.setText(str(result))
                    self.expression = str(result)
                else:
                    self.display.setText("Error")
            except:
                self.display.setText("Error")
        elif text == '±':
            if self.expression and self.expression[0] == '-':
                self.expression = self.expression[1:]
            else:
                self.expression = '-' + self.expression
            self.display.setText(self.expression)
        else:
            self.expression += text
            self.display.setText(self.expression)

def main():
    app = QApplication(sys.argv)
    app.setStyle("Fusion")
    win = Calculator()
    win.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()