<script setup lang="ts">
import { ref } from 'vue'
import type { IRawStepTask } from '@/stores'
import SvgIcon from '@/components/SvgIcon/index.vue'

const props = defineProps<{
  task: IRawStepTask
}>()

const emit = defineEmits<{
  (e: 'save', taskId: string, content: string): void
}>()

const isEditing = ref(false)
const editingContent = ref('')

const startEditing = () => {
  editingContent.value = props.task.TaskContent || ''
  isEditing.value = true
}

const save = () => {
  const trimmed = editingContent.value.trim()
  emit('save', props.task.Id!, trimmed)
  isEditing.value = false
}

const cancel = () => {
  isEditing.value = false
}

const handleKeydown = (event: KeyboardEvent) => {
  if (event.key === 'Enter') {
    event.preventDefault()
    save()
  } else if (event.key === 'Escape') {
    cancel()
  }
}
</script>

<template>
  <div v-if="isEditing" class="w-full">
    <div class="flex flex-col gap-3">
      <el-input
        v-model="editingContent"
        type="textarea"
        :autosize="{ minRows: 2, maxRows: 4 }"
        placeholder="请输入任务内容"
        @keydown="handleKeydown"
        class="task-content-editor"
        size="small"
      />
      <div class="flex justify-end">
        <svg-icon
          icon-class="Check"
          size="20px"
          color="#328621"
          class="cursor-pointer mr-4"
          @click="save"
          title="保存"
        />
        <svg-icon
          icon-class="Cancel"
          size="20px"
          color="#8e0707"
          class="cursor-pointer mr-1"
          @click="cancel"
          title="取消"
        />
      </div>
    </div>
  </div>
  <div v-else @dblclick="startEditing" class="w-full cursor-pointer">
    <slot name="display">
      <div class="text-[14px] text-[var(--color-text-secondary)] task-content-display">
        {{ task.TaskContent }}
      </div>
    </slot>
  </div>
</template>

<style scoped lang="scss">
.task-content-editor {
  :deep(.el-textarea__inner) {
    font-size: 14px;
    color: var(--color-text-secondary);
    background: transparent;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    resize: none;
  }
}

.task-content-display {
  min-height: 40px;
  word-break: break-word;
  white-space: pre-wrap;
}
</style>
