<template>
  <div class="calc">
    <div class="view">
      <input type="text" v-model="text"/>
    </div>
    <div class="btn" @click="typ('+')"><span>+</span></div>
    <div class="btn" @click="typ('-')"><span>-</span></div>
    <div class="btn" @click="typ('x')"><span>×</span></div>
    <div class="btn" @click="typ('÷')"><span>÷</span></div>

    <div class="btn" @click="typ('7')"><span>7</span></div>
    <div class="btn" @click="typ('8')"><span>8</span></div>
    <div class="btn" @click="typ('9')"><span>9</span></div>
    <div class="btn"></div>

    <div class="btn" @click="typ('4')"><span>4</span></div>
    <div class="btn" @click="typ('5')"><span>5</span></div>
    <div class="btn" @click="typ('6')"><span>6</span></div>
    <div class="btn"></div>

    <div class="btn" @click="typ('1')"><span>1</span></div>
    <div class="btn" @click="typ('2')"><span>2</span></div>
    <div class="btn" @click="typ('3')"><span>3</span></div>
    <div class="btn" @click="clear"><span>Clear</span></div>

    <div class="btn" @click="typ('0')"><span>0</span></div>
    <div class="btn"></div>
    <div class="btn" @click="typ('.')"><span>.</span></div>
    <div class="btn" @click="typ('=')"><span>=</span></div>
  </div>
</template>

<script setup name="calc">
import {ref} from "vue"

const text = ref("") // 显示的内容
const result = ref("") // 实际计算的内容
const restart = ref(false) // 是否需要重置标记

const typ = (t) => {
  if (restart.value) clear() // 判断是否需要重置

  text.value = text.value + t

  switch (t) {
    case "x":
      result.value += '*'
      break
    case "÷":
      result.value += '/'
      break
    case "=":
      result.value = eval(result.value)
      text.value = result.value
      restart.value = true // 计算完成后进行标记计算器下次计算需要重置
      break
    default:
      result.value = result.value + t
  }
}

// 重置计算器的值
const clear = function () {
  result.value = ""
  text.value = ""
  restart.value = false // 复位重置标记
}
</script>

<style scoped>
.calc {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  box-sizing: border-box;
}

.view {
  width: 100%;
  height: 100px;
}

.view input {
  width: 100%;
  height: 100%;
}

.btn {
  position: relative;
  width: 25%;
  height: 0;
  /*通过边距形成正方形的Hack*/
  padding-top: 25%;
  border: 1px solid #2c3e50;
  box-sizing: border-box;
  font-size: 30px;
  text-align: center;
  cursor: pointer;
}

/*遍历所有子元素*/
.btn > * {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

</style>
