<?php

/**
 * @id 4
 * @name 简易计算器
 * @version 1.0.0
 * @description 功能简单、界面美观的在线计算器，支持加减乘除等基本数学运算，满足日常计算需求。
 * @price 0
 * @type 工具
 * @website
 * @width 290
 * @height 330
 * @thumbnail /img/id4.png
 */
?>
<div class="calculator-container">
    <div class="calculator-display">
        <input type="text" id="calculator-display" value="0" readonly>
    </div>
    <div class="calculator-buttons">
        <button type="button" class="btn btn-clear" onclick="calculator.clear()">C</button>
        <button type="button" class="btn btn-operator" onclick="calculator.backspace()">⌫</button>
        <button type="button" class="btn btn-operator" onclick="calculator.setOperator('/')">÷</button>
        <button type="button" class="btn btn-operator" onclick="calculator.setOperator('*')">×</button>

        <button type="button" class="btn btn-number" onclick="calculator.appendNumber('7')">7</button>
        <button type="button" class="btn btn-number" onclick="calculator.appendNumber('8')">8</button>
        <button type="button" class="btn btn-number" onclick="calculator.appendNumber('9')">9</button>
        <button type="button" class="btn btn-operator" onclick="calculator.setOperator('-')">-</button>

        <button type="button" class="btn btn-number" onclick="calculator.appendNumber('4')">4</button>
        <button type="button" class="btn btn-number" onclick="calculator.appendNumber('5')">5</button>
        <button type="button" class="btn btn-number" onclick="calculator.appendNumber('6')">6</button>
        <button type="button" class="btn btn-operator" onclick="calculator.setOperator('+')">+</button>

        <button type="button" class="btn btn-number" onclick="calculator.appendNumber('1')">1</button>
        <button type="button" class="btn btn-number" onclick="calculator.appendNumber('2')">2</button>
        <button type="button" class="btn btn-number" onclick="calculator.appendNumber('3')">3</button>
        <button type="button" class="btn btn-equals" onclick="calculator.calculate()">=</button>

        <button type="button" class="btn btn-number btn-zero" onclick="calculator.appendNumber('0')">0</button>
        <button type="button" class="btn btn-number" onclick="calculator.appendNumber('.')">.</button>
    </div>
</div>

<style>
    /* 计算器容器样式，限制所有样式只在计算器内部生效 */
    .calculator-container {
        max-width: 250px;
        /* 进一步减小最大宽度 */
        margin: 0 auto;
        font-family: 'Arial', sans-serif;

    }

    .calculator-container .calculator-display {
        margin-bottom: 15px;
    }

    .calculator-container #calculator-display {
        width: 100%;
        height: 40px;
        font-size: 18px;
        text-align: right;
        padding: 6px 8px;
        border: none;
        background-color: #f5f5f5;
        border-radius: 6px;
        box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1);
        color: #333;
        box-sizing: border-box;
    }

    .calculator-container .calculator-buttons {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        grid-gap: 6px;
    }

    .calculator-container .btn {
        height: 40px;
        font-size: 15px;
        border: none;
        border-radius: 6px;
        cursor: pointer;
        transition: all 0.2s ease;
        font-weight: 500;
    }

    .calculator-container .btn:hover {
        transform: translateY(-1px);
        box-shadow: 0 3px 6px rgba(0, 0, 0, 0.15);
    }

    .calculator-container .btn:active {
        transform: translateY(0);
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    }

    .calculator-container .btn-number {
        background-color: #ffffff;
        color: #333;
        border: 1px solid #e0e0e0;
    }

    .calculator-container .btn-number:hover {
        background-color: #f9f9f9;
    }

    .calculator-container .btn-operator {
        background-color: #f5f5f5;
        color: #333;
        border: 1px solid #e0e0e0;
    }

    .calculator-container .btn-operator:hover {
        background-color: #eeeeee;
    }

    .calculator-container .btn-clear {
        background-color: #ff6b6b;
        color: white;
    }

    .calculator-container .btn-clear:hover {
        background-color: #ff5252;
    }

    .calculator-container .btn-equals {
        background-color: #4ecdc4;
        color: white;
        grid-row: span 2;
    }

    .calculator-container .btn-equals:hover {
        background-color: #45b7aa;
    }

    .calculator-container .btn-zero {
        grid-column: span 2;
    }
</style>

<script>
    // 立即执行函数，避免全局变量污染
    (function() {
        // 定义callParentToast函数，使用父页面的提示框
        function callParentToast(message, options = {}) {
            window.parent.postMessage({
                type: 'toast',
                func: 'showToast',
                message: message,
                options: options
            }, window.parent.location.origin);
        }
        // 计算器对象
        var calculator = {
            displayValue: '0',
            firstOperand: null,
            waitingForSecondOperand: false,
            operator: null,
            display: null,
            buttons: [],
            isInitialized: false,

            // 初始化 - 确保每次都能找到最新的DOM元素
            init: function() {
                // 查找显示元素
                this.display = document.getElementById('calculator-display');

                // 查找所有按钮元素
                this.buttons = document.querySelectorAll('.calculator-container button');

                // 只有当找到显示元素时才标记为已初始化
                if (this.display) {
                    this.isInitialized = true;
                    this.updateDisplay();
                } else {
                    this.isInitialized = false;
                }
            },

            // 确保计算器已初始化
            ensureInitialized: function() {
                // 如果未初始化或显示元素不存在，重新初始化
                if (!this.isInitialized || !this.display || this.display.parentNode === null) {
                    this.init();
                }
                return this.isInitialized;
            },

            // 追加数字
            appendNumber: function(number) {
                if (!this.ensureInitialized()) return;

                if (this.waitingForSecondOperand) {
                    this.displayValue = number;
                    this.waitingForSecondOperand = false;
                } else {
                    this.displayValue = this.displayValue === '0' ? number : this.displayValue + number;
                }

                this.updateDisplay();
            },

            // 设置运算符
            setOperator: function(nextOperator) {
                if (!this.ensureInitialized()) return;

                const inputValue = parseFloat(this.displayValue);

                if (this.operator && this.waitingForSecondOperand) {
                    this.operator = nextOperator;
                    return;
                }

                if (this.firstOperand === null) {
                    this.firstOperand = inputValue;
                } else if (this.operator) {
                    const result = this.calculateResult(this.firstOperand, inputValue, this.operator);

                    this.displayValue = String(result);
                    this.firstOperand = result;
                }

                this.waitingForSecondOperand = true;
                this.operator = nextOperator;

                this.updateDisplay();
            },

            // 计算结果
            calculateResult: function(firstOperand, secondOperand, operator) {
                switch (operator) {
                    case '+':
                        return firstOperand + secondOperand;
                    case '-':
                        return firstOperand - secondOperand;
                    case '*':
                        return firstOperand * secondOperand;
                    case '/':
                        if (secondOperand === 0) {
                            // 使用父页面的提示框
                            callParentToast('除数不能为零', {
                                type: 'error'
                            });
                            return firstOperand;
                        }
                        return firstOperand / secondOperand;
                    default:
                        return secondOperand;
                }
            },

            // 执行计算
            calculate: function() {
                if (!this.ensureInitialized()) return;

                const inputValue = parseFloat(this.displayValue);

                if (this.operator && !this.waitingForSecondOperand) {
                    const result = this.calculateResult(this.firstOperand, inputValue, this.operator);

                    this.displayValue = String(result);
                    this.operator = null;
                    this.firstOperand = null;
                    this.waitingForSecondOperand = false;

                    this.updateDisplay();
                }
            },

            // 清除所有
            clear: function() {
                if (!this.ensureInitialized()) return;

                this.displayValue = '0';
                this.firstOperand = null;
                this.waitingForSecondOperand = false;
                this.operator = null;

                this.updateDisplay();
            },

            // 退格
            backspace: function() {
                if (!this.ensureInitialized()) return;

                if (this.waitingForSecondOperand) return;

                if (this.displayValue.length > 1) {
                    this.displayValue = this.displayValue.slice(0, -1);
                } else {
                    this.displayValue = '0';
                }

                this.updateDisplay();
            },

            // 更新显示
            updateDisplay: function() {
                if (this.ensureInitialized()) {
                    this.display.value = this.displayValue;
                }
            }
        };

        // 暴露计算器对象到全局作用域，以便HTML中的onclick事件可以访问
        window.calculator = calculator;

        // 立即尝试初始化
        calculator.init();

        // 为所有按钮添加点击事件监听（作为备份，确保事件能正确触发）
        setTimeout(function() {
            if (calculator.buttons.length > 0) {
                calculator.buttons.forEach(function(button) {
                    button.addEventListener('click', function() {
                        // 点击按钮时再次确保初始化
                        calculator.ensureInitialized();
                    });
                });
            }
        }, 100);
    })();
</script>