<template>
  <div class="loading-wrapper">
    <div class="loading-content">
      <div :class="{ 'loading-text': true }" v-if="!fail">{{ text }}</div>
      <div class="progress-bar" v-if="!fail">
        <div
          class="progress-fill"
          :style="{
            width: progress + '%',
            backgroundColor: '#036EB8'
          }"
        ></div>
      </div>
      <div class="loading-tip" v-if="!fail && props.tip">{{ props.tip }}</div>
      <div class="loading-wrapper-error" v-if="fail">
        <div class="error-icon">
          <img :src="EmptyIcon" />
        </div>
        <div class="error-tip">暂无数据</div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import EmptyIcon from '@/assets/images/icon_none.png';

const props = defineProps({
  text: {
    type: String,
    default: 'AI数据生成中...'
  },
  autoFinish: {
    type: Boolean,
    default: false // true 时直接满进度
  },
  fail: {
    type: Boolean,
    default: false // true 时失败，进度条停止 & 变红
  },
  tip: {
    type: String
  }
});

const progress = ref(0);
let timer: any = null;

// 进度逻辑
const startProgress = () => {
  if (props.autoFinish) {
    progress.value = 100;
    return;
  }

  timer = setInterval(() => {
    if (!props.fail && progress.value < 100) {
      progress.value += 1;
    } else {
      clearInterval(timer);
    }
  }, 1000); // 每秒 +1%
};

onMounted(() => {
  startProgress();
});

onUnmounted(() => {
  clearInterval(timer);
});

// 监听 autoFinish 变化，支持动态切换
watch(
  () => props.autoFinish,
  (val) => {
    if (val) {
      progress.value = 100;
      clearInterval(timer);
    }
  }
);

// 监听 fail
watch(
  () => props.fail,
  (val) => {
    if (val) {
      clearInterval(timer); // 停止进度
    } else {
      // 从失败恢复时重新启动
      if (progress.value < 100) startProgress();
    }
  }
);
</script>

<style lang="scss" scoped>
.loading-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-wrapper-error {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .error-icon {
    width: 216px;
    height: 216px;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .error-tip {
    font-size: 16px;
    font-weight: bold;
    color: var(--promotion--color-primary);
  }
}

.loading-content {
  text-align: center;
}

.loading-text {
  font-weight: bold;
  font-size: 20px;
  color: #282e30;
  margin-bottom: 20px;

  &.fail {
    color: red;
  }
}

.progress-bar {
  width: 350px;
  height: 10px;
  background-color: #e7e9ec;
  border-radius: 5px;
  overflow: hidden;
  margin: 0 auto;
}

.loading-tip {
  margin-top: 10px;
  font-weight: 400;
  font-size: 14px;
  color: rgba(40,46,48,0.6);
}

.progress-fill {
  height: 100%;
  background-color: var(--promotion--color-primary);
  transition: width 0.3s ease;
}
</style>
