<template>
  <el-dialog
      :model-value="visible"
      title="移动笔记到"
      width="400px"
      @close="handleClose"
      :close-on-click-modal="false"
  >
    <el-cascader
        v-model="moveToGroupId"
        :options="categoryOptions"
        :props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'grouping' }"
        clearable
        placeholder="请选择目标分类"
        style="width: 100%;"
    ></el-cascader>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { updateMarkdown } from '@/api/CommonApi.js';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  categoryOptions: {
    type: Array,
    default: () => [],
  },
  noteToMove: {
    type: Object,
    default: null,
  }
});

const emit = defineEmits(['update:visible', 'move-success']);

const moveToGroupId = ref(null);

watch(() => props.visible, (newVal) => {
  if (!newVal) {
    moveToGroupId.value = null;
  }
});

const handleClose = () => {
  emit('update:visible', false);
};

const handleSubmit = async () => {
  if (!moveToGroupId.value) {
    ElMessage.error('请选择目标分类');
    return;
  }
  if (!props.noteToMove) {
    ElMessage.error('没有需要移动的笔记');
    return;
  }

  try {
    const payload = {
      ...props.noteToMove,
      groupingId: moveToGroupId.value,
    };
    await updateMarkdown(payload);
    ElMessage.success('笔记移动成功');
    emit('move-success');
    handleClose();
  } catch (error) {
    ElMessage.error('移动失败: ' + error.message);
  }
};
</script>
