<template>
  <div class="stats-tool">
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="服务器" size="default">
        <select-scrapyd-server v-model:value="serverValue" @change="handleServerChange" />
      </el-form-item>

      <el-form-item size="default" label="项目">
        <el-select v-model="projectValue" placeholder="请选择项目" clearable @change="handleProjectChange"
          style="width: 180px" size="default">
          <el-option v-for="item in projectOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="爬虫" size="default">
        <el-select v-model="spiderValue" placeholder="请选择爬虫" clearable size="default" @change="handleSpiderChange"
          style="width: 180px">
          <el-option v-for="item in spiderOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button type="danger" @click="confirmClear">清空数据</el-button>
        <stats-remove :scrapyd-server-id="serverValue" :project="projectValue" :spider="spiderValue" button-text="批量删除"
          @success="handleRemoveSuccess" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, defineProps, defineEmits, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import SelectScrapydServer from '@/components/SelectScrapydServer.vue'
import StatsRemove from './StatsRemove.vue'
import * as projectApi from '@/api/project'
import * as statsApi from '@/api/stats'

const props = defineProps({
  scrapydServerId: {
    type: String,
    default: ''
  },
  project: {
    type: String,
    default: ''
  },
  spider: {
    type: String,
    default: ''
  }
})

const emit = defineEmits([
  'update:scrapyd-server-id',
  'update:project',
  'update:spider',
  'project-change',
  'spider-change',
  'success'
])

interface OptionItem {
  label: string
  value: string
}

const serverValue = ref(props.scrapydServerId)
const projectValue = ref(props.project)
const spiderValue = ref(props.spider)

const projectOptions = ref<OptionItem[]>([])
const spiderOptions = ref<OptionItem[]>([])

// 获取项目列表
const getProjects = async () => {
  if (!serverValue.value) return

  try {
    const res = await projectApi.listProjects({
      scrapydServerId: serverValue.value
    })

    if (res.code === 0) {
      projectOptions.value = (res.data || []).map((item: string) => ({
        label: item,
        value: item
      }))
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
  }
}

// 获取爬虫列表
const getSpiders = async () => {
  if (!serverValue.value || !projectValue.value) return

  try {
    const res = await projectApi.listSpiders({
      scrapydServerId: serverValue.value,
      project: projectValue.value
    })

    if (res.code === 0) {
      spiderOptions.value = (res.data || []).map((item: string) => ({
        label: item,
        value: item
      }))
    }
  } catch (error) {
    console.error('获取爬虫列表失败:', error)
  }
}

// 处理服务器变化
const handleServerChange = async (val: string) => {
  serverValue.value = val
  emit('update:scrapyd-server-id', val)

  // 清空项目和爬虫选择
  projectValue.value = ''
  emit('update:project', '')
  spiderValue.value = ''
  emit('update:spider', '')

  // 重新加载项目列表
  await getProjects()
}

// 处理项目变化
const handleProjectChange = async (val: string) => {
  projectValue.value = val
  emit('update:project', val)

  // 清空爬虫选择
  spiderValue.value = ''
  emit('update:spider', '')

  // 重新加载爬虫列表
  await getSpiders()

  // 触发项目变化事件
  emit('project-change')
}

// 处理爬虫变化
const handleSpiderChange = async (val: string) => {
  spiderValue.value = val
  emit('update:spider', val)

  // 触发爬虫变化事件
  emit('spider-change')
}

// 搜索按钮
const handleSearch = () => {
  emit('success')
}

// 批量删除成功回调
const handleRemoveSuccess = () => {
  emit('success')
}

// 确认清空统计数据
const confirmClear = () => {
  ElMessageBox.confirm('确认清空所有统计数据?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    customClass: 'custom-message-box',

  })
    .then(async () => {
      try {
        const res = await statsApi.clearAllStats({
          scrapydServerId: serverValue.value,
          project: projectValue.value,
          spider: spiderValue.value
        })

        if (res.code === 0) {
          ElMessage({
            type: 'success',
            message: '清空成功!'
          })
          emit('success')
        }
      } catch (error) {
        console.error('清空统计数据失败:', error)
      }
    })
    .catch(() => {
      // 取消操作
    })
}

// 监听属性变化
watch(() => props.scrapydServerId, (val) => {
  serverValue.value = val
})

watch(() => props.project, (val) => {
  projectValue.value = val
})

watch(() => props.spider, (val) => {
  spiderValue.value = val
})

onMounted(async () => {
  if (serverValue.value) {
    await getProjects()

    if (projectValue.value) {
      await getSpiders()
    }
  }
})
</script>

<style lang="scss" scoped>
// .custom-message-box .el-button--primary {
//   outline: none;
//   // background-color: aqua;
// }

.stats-tool {
  margin-bottom: 20px;
  text-align: left;
}



:deep(.Border) {
  border-color: white;
}

::v-deep .el-button:focus {
  outline: none;
}
</style>

<style>
.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>
