<template>
  <el-dialog
    title="编辑"
    v-model="dialogVisible"
    width="500px"
    :before-close="handleClose"
    :close-on-click-modal="false"
  >
    <div class="edit-container">
      <div class="form-item">
        <span class="required">*</span>名称
        <el-input v-model="form.name" placeholder="请输入名称"></el-input>
      </div>
      <div class="form-item">
        <span class="required">*</span>分组
        <el-select v-model="form.dictId" placeholder="请选择">
          <el-option 
            v-for="group in groupList" 
            :key="group.id" 
            :label="group.dictName" 
            :value="group.id"
          ></el-option>
        </el-select>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineEmits, defineProps, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { editMediaItem } from '@/store/mediaLibrary';

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

const emit = defineEmits(['update:visible', 'refresh']);

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
});

const form = ref({
  id: '',
  dictId: '',
  uploadId: '',
  name: ''  // 添加文件名字段
});

// 监听媒体数据变化，初始化表单
watch(() => props.mediaData, (newVal) => {
  if (newVal && newVal.id) {
    form.value.id = newVal.id;
    form.value.dictId = newVal.dictId || '';
    form.value.uploadId = newVal.uploadId || '';
    form.value.name = newVal.name || '';  // 初始化文件名
  }
}, { immediate: true, deep: true });

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false;
};

// 确认编辑
const handleConfirm = async () => {
  if (!form.value.dictId) {
    ElMessage.warning('请选择分组');
    return;
  }
  
  if (!form.value.name || !form.value.name.trim()) {
    ElMessage.warning('请输入文件名称');
    return;
  }
  
  try {
    await editMediaItem({
      id: form.value.id,
      dictId: form.value.dictId,
      uploadId: form.value.uploadId,
      name: form.value.name.trim()  // 添加文件名到提交数据
    });
    
    ElMessage.success('编辑成功');
    handleClose();
    emit('refresh');
  } catch (error) {
    console.error('编辑失败:', error);
    ElMessage.error('编辑失败');
  }
};
</script>

<style lang="scss" scoped>
.edit-container {
  padding: 20px;
}

.form-item {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  
  .required {
    color: #f56c6c;
    margin-right: 5px;
  }
  
  .el-select, .el-input {
    margin-left: 10px;
    width: 300px;
  }
}
</style>