<template>
  <div class="step-detail-page">
    <!-- 顶部操作栏 -->
    <div class="action-bar">
      <el-button @click="handleCancel">返回</el-button>
      <el-button type="primary" @click="handleSave" :loading="saveLoading">保存</el-button>
    </div>

    <!-- 富文本编辑器 -->
    <div class="editor-container">
      <TinyMCE
        v-model:value="stepDescription"
        :height="700"
        placeholder="请输入内容..."
        @update:value="handleContentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import TinyMCE from "@/components/TinyMCE/index.vue"
import { updateSopWorkflowStep } from '@/api/sop/sopStep'

const route = useRoute()
const router = useRouter()

const stepDescription = ref('')
const saveLoading = ref(false)
const stepData = ref(null) // 存储完整的步骤数据

// 内容变化处理
const handleContentChange = (content: string) => {
  // console.log('内容变化:', content)
  stepDescription.value = content
}

// 保存操作
const handleSave = async () => {
  try {
    saveLoading.value = true

    // 更新步骤数据中的描述字段
    const updateData = {
      ...stepData.value,
      stepDescription: stepDescription.value
    }

    // 调用更新接口
    await updateSopWorkflowStep(updateData)

    ElMessage.success('保存成功')


  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请稍后重试')
  } finally {
    saveLoading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  // 如果有内容变化，提示用户
  if (stepDescription.value !== stepData.value?.stepDescription) {
    ElMessageBox.confirm(
      '内容已修改，确定要取消吗？',
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '继续编辑',
        type: 'warning'
      }
    ).then(() => {

      router.back()
    }).catch(() => {
      // 用户选择继续编辑，不做任何操作
    })
  } else {
    router.back()
  }
}

// 页面初始化
onMounted(() => {
  const tempData = localStorage.getItem('sopTableDetail')
  if (tempData) {
    stepData.value = JSON.parse(tempData)
    stepDescription.value = stepData.value.stepDescription || ''
    // 清除临时数据
    localStorage.removeItem('sopTableDetail')
  }

})
</script>

<style scoped lang="scss">
.step-detail-page {
  padding: 20px;

  .action-bar {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
    justify-content: flex-end;
  }

  .editor-container {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
  }
}
</style>
