<script setup lang="ts">
import { ref } from 'vue'

const props = defineProps({
  type: {
    type: String,
    default: 'default',
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  loading: { // 添加 loading 属性
    type: Boolean,
    default: false,
  },
  onClick: {
    type: Function,
    required: false,
    default: () => Promise<any>,
  },
})

const isLoading = ref(false)

async function handleClick() {
  if (!props.onClick || isLoading.value)
    return

  isLoading.value = true // 进入 loading
  try {
    await props.onClick() // 执行异步操作
  }
  finally {
    isLoading.value = false // 结束 loading
  }
}

const setLoading = (loading: boolean) => {
  isLoading.value = loading
}

defineExpose({
  setLoading,
})
</script>

<template>
  <div class="ft-button" :class="{ 'ft-button-disabled': disabled || isLoading }" @click="handleClick">
    <!-- 添加 loading 判断 -->
    <div v-show="disabled || isLoading" class="my-button-shadow" /> <!-- 添加 loading 判断 -->
    <div
      class="my-button" :class="{
        [`my-button-${type}`]: true,
        'button-disabled': disabled || isLoading, // 添加 loading 判断
      }"
    >
      <el-icon v-if="isLoading" :color="type === 'default' ? '#26509C' : '#fff'">
        <!-- 添加 loading 判断 -->
        <Loading class="rotate-loading" /> <!-- 添加旋转类 -->
      </el-icon>
      <slot />
    </div>
  </div>
</template>

<style scoped lang="scss">
.ft-button {
  position: relative;
  display: inline-block;
  margin-right: 20px;
}
.ft-button-disabled {
  pointer-events: none;
}
.my-button-shadow {
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: 100;
}
.my-button {
  height: var(--el-button-size);
  padding: 0 50px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 40px;
  width: fit-content;
  position: relative;
  .el-icon {
    position: absolute;
    left: 5px;
    svg {
      width: 35px;
    }
  }
}
.button-disabled {
  opacity: 0.5;
}
.my-button-default {
  background: linear-gradient(180deg, #D8E3F8 0%, #FBFCFE 100%);
  color: #26509C;
  border: 1px solid #D8E3F8;
}
.my-button-primary {
  background: linear-gradient(90deg, #0657C0 24%, #096AE0 101%);
  color: #fff;
  border: 1px solid #D8E3F8;
}

.my-button-info {
  background: #335AA5;
  color: #fff;
  border: 1px solid #335AA5;
}

.rotate-loading {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>
