<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>并发配置</span>
          <el-button
            v-permission="'polling_concurrency_reset'"
            type="warning"
            @click="handleResetAll"
          >
            重置全部并发
          </el-button>
        </div>
      </template>

      <el-table v-loading="loading" :data="tableData" border stripe>
        <el-table-column prop="task_type" label="任务类型" min-width="200" />
        <el-table-column prop="task_type_name" label="任务名称" min-width="150" />
        <el-table-column prop="max_concurrency" label="最大并发数" min-width="120" align="center" />
        <el-table-column prop="current" label="当前并发数" min-width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="row.current > row.max_concurrency * 0.8 ? 'danger' : 'success'">
              {{ row.current }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="available" label="可用并发数" min-width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="row.available === 0 ? 'danger' : 'info'">
              {{ row.available }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="utilization" label="使用率" min-width="150" align="center">
          <template #default="{ row }">
            <el-progress
              :percentage="row.utilization"
              :color="getUtilizationColor(row.utilization)"
              :stroke-width="8"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">修改配置</el-button>
            <el-button type="danger" link @click="handleReset(row)">重置</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="修改并发配置"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
        <el-form-item label="任务类型">
          <el-input v-model="currentRow.task_type_name" disabled />
        </el-form-item>
        <el-form-item label="最大并发数" prop="max_concurrency">
          <el-input-number
            v-model="formData.max_concurrency"
            :min="1"
            :max="1000"
            :step="10"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { PollingConcurrencyService } from '@/api/modules'
  import type { PollingConcurrency, UpdateConcurrencyParams } from '@/types/api'

  const loading = ref(false)
  const tableData = ref<PollingConcurrency[]>([])
  const dialogVisible = ref(false)
  const formRef = ref<FormInstance>()

  const currentRow = ref<PollingConcurrency>({
    task_type: '',
    task_type_name: '',
    max_concurrency: 0,
    current: 0,
    available: 0,
    utilization: 0
  })

  const formData = reactive<UpdateConcurrencyParams>({
    max_concurrency: 100
  })

  const formRules: FormRules = {
    max_concurrency: [
      { required: true, message: '请输入最大并发数', trigger: 'blur' },
      { type: 'number', min: 1, max: 1000, message: '并发数范围为 1-1000', trigger: 'blur' }
    ]
  }

  const getUtilizationColor = (percentage: number) => {
    if (percentage >= 90) return '#f56c6c'
    if (percentage >= 70) return '#e6a23c'
    if (percentage >= 50) return '#409eff'
    return '#67c23a'
  }

  const loadData = async () => {
    loading.value = true
    try {
      const { data } = await PollingConcurrencyService.getConcurrencyList()
      tableData.value = data.items
    } catch (error) {
      console.log('加载并发配置失败')
    } finally {
      loading.value = false
    }
  }

  const handleEdit = async (row: PollingConcurrency) => {
    try {
      // 调用接口#2：获取指定任务类型的最新并发配置
      const { data } = await PollingConcurrencyService.getConcurrencyByType(row.task_type)
      currentRow.value = { ...data }
      formData.max_concurrency = data.max_concurrency
      dialogVisible.value = true
    } catch (error) {
      console.log('获取并发配置失败')
    }
  }

  const handleReset = async (row: PollingConcurrency) => {
    try {
      await ElMessageBox.confirm(`确定要重置 ${row.task_type_name} 的并发计数吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })

      await PollingConcurrencyService.resetConcurrency({ task_type: row.task_type })
      ElMessage.success('重置成功')
      await loadData()
    } catch (error) {
      if (error !== 'cancel') {
        console.log('重置失败')
      }
    }
  }

  const handleResetAll = async () => {
    try {
      await ElMessageBox.confirm('确定要重置所有任务类型的并发计数吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })

      await PollingConcurrencyService.resetConcurrency()
      ElMessage.success('重置成功')
      await loadData()
    } catch (error) {
      if (error !== 'cancel') {
        console.log('重置失败')
      }
    }
  }

  const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
      if (!valid) return

      try {
        await PollingConcurrencyService.updateConcurrency(currentRow.value.task_type, formData)
        ElMessage.success('修改成功')
        dialogVisible.value = false
        await loadData()
      } catch (error) {
        console.log('修改失败')
      }
    })
  }

  const handleDialogClose = () => {
    formRef.value?.resetFields()
  }

  onMounted(() => {
    loadData()
  })
</script>

<style scoped lang="scss">
  .card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
</style>
