<template>
  <el-switch
    v-model="status"
    :loading="loading"
    :active-value="true"
    :inactive-value="false"
    @change="handleChange"
  />
</template>

<script lang="ts" setup>
import { ref, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import * as scheduleApi from '@/api/schedule'

const props = defineProps({
  job_id: {
    type: String,
    required: true
  },
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue'])

const status = ref(props.modelValue)
const loading = ref(false)

const handleChange = async (val: boolean) => {
  loading.value = true
  try {
    const res = val 
      ? await scheduleApi.resumeJob({ job_id: props.job_id })
      : await scheduleApi.pauseJob({ job_id: props.job_id })
      
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: val ? '恢复任务成功!' : '暂停任务成功!'
      })
      emit('update:modelValue', val)
    } else {
      // 操作失败，回滚开关状态
      status.value = !val
    }
  } catch (error) {
    console.error(val ? '恢复任务失败:' : '暂停任务失败:', error)
    // 出错，回滚开关状态
    status.value = !val
  } finally {
    loading.value = false
  }
}
</script>
