<template>
  <div class="stats-remove">
    <el-button type="danger" @click="confirmRemove" :disabled="isDisabled">
      {{ buttonText }}
    </el-button>
  </div>
</template>

<script lang="ts" setup>
import { computed, defineProps, defineEmits } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import * as statsApi from '@/api/stats'

const props = defineProps({
  scrapydServerId: {
    type: String,
    default: ''
  },
  project: {
    type: String,
    default: ''
  },
  spider: {
    type: String,
    default: ''
  },
  buttonText: {
    type: String,
    default: '删除选中'
  }
})

const emit = defineEmits(['success'])

// 计算是否禁用按钮
const isDisabled = computed(() => {
  return !props.scrapydServerId && !props.project && !props.spider
})

// 确认删除操作
const confirmRemove = () => {
  ElMessageBox.confirm('确认删除所选的统计数据?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    customClass: 'custom-message-box',
  })
    .then(async () => {
      try {
        interface ParamType {
          scrapydServerId: string;
          project?: string;
          spider?: string;
          [key: string]: string | undefined;
        }
        
        const params: ParamType = {
          scrapydServerId: props.scrapydServerId,
          project: props.project || undefined,
          spider: props.spider || undefined
        }
        
        // 过滤掉空值
        Object.keys(params).forEach((key) => {
          if (!params[key]) {
            delete params[key];
          }
        });
        
        const res = await statsApi.removeStats(params)
        
        if (res.code === 0) {
          ElMessage({
            type: 'success',
            message: '删除成功!'
          })
          emit('success')
        }
      } catch (error) {
        console.error('删除统计数据失败:', error)
      }
    })
    .catch(() => {
      // 取消操作
    })
}
</script>

<style lang="scss" scoped>
.stats-remove {
  margin-left: 10px;
  margin-top: -2px;
  display: inline-block;
}

.el-button:focus {
  outline: none;
}

.custom-message-box .el-button--primary {
  outline: none;
}

.custom-message-box .el-button--default {
  outline: none;
}

.custom-message-box .el-message-box__headerbtn {
  outline: none;
}
</style>
