<template>
  <div id="validcode">
    <div class="code" @click="resetCode()">
      <span v-for="i in list" :key="i.code" :style="getStyle(i)">{{ i.code }}</span>
    </div>
  </div>
</template>
<script setup lang="ts">
import type { Ref } from 'vue'
import { ref, onMounted } from 'vue'
const emit = defineEmits(['toCode'])
const list: Ref<any> = ref([])
onMounted(() => {
  // 创建验证码
  createCode()
})
// 创建验证码
const createCode = () => {
  const len = 4
  const codeList = []
  const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz0123456789'
  const charsLen = chars.length
  for (let i = 0; i < len; i++) {
    const rgb = [Math.round(Math.random() * 220), Math.round(Math.random() * 240), Math.round(Math.random() * 200)]
    codeList.push({
      code: chars.charAt(Math.floor(Math.random() * charsLen)),
      color: `rgb(${rgb})`,
      fontSize: `1${[Math.floor(Math.random() * 10)]}px`,
      padding: `${[Math.floor(Math.random() * 10)]}px`,
      transform: `rotate(${Math.floor(Math.random() * 90) - Math.floor(Math.random() * 90)}deg)`
    })
  }
  list.value = codeList
  const codeInfo = codeList.map((item) => item.code).join('')
  emit('toCode', codeInfo)
}
// 验证码样式
const getStyle = (e: any) => {
  return `color: ${e.color}; font-size: ${e.fontSize}; padding: ${e.padding}; transform: ${e.transform}`
}
// 重构验证码
const resetCode = () => {
  createCode()
}
</script>
<style scoped lang="scss">
.code {
  width: 100px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  border-radius: 5px;
  border: 1px solid #dcdfe6;
}
</style>
