<template>
  <el-dialog
    v-model="dialogVisible"
    title="异常操作"
    width="500px"
    :close-on-click-modal="false"
    @close="onCancel"
  >
    <el-form :model="form" label-width="80px">
      <el-form-item label="异常说明">
        <el-input
          v-model="form.condition"
          type="textarea"
          :rows="3"
          placeholder="请输入异常说明"
        />
      </el-form-item>
      <el-form-item label="照片">
        <el-upload
          class="upload-demo"
          action="#"
          :auto-upload="false"
          :on-change="handleChange"
          :file-list="fileList"
          list-type="picture"
          multiple
        >
          <el-button type="primary">选择图片</el-button>
          <template #tip>
            <div class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="onCancel">取消</el-button>
        <el-button type="primary" @click="onConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';

const props = defineProps<{
  visible: boolean;
}>();

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

const dialogVisible = ref(props.visible);

// 监听 props.visible 的变化
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal;
});

// 监听 dialogVisible 的变化
watch(() => dialogVisible.value, (newVal) => {
  emit('update:visible', newVal);
});

const fileList = ref<any[]>([]);

const form = ref({
  condition: '',
  photos: [] as Array<{
    filename: string;
    data: string;
  }>
});

const handleChange = (file: any) => {
  // 将文件转换为Base64
  const reader = new FileReader();
  reader.readAsDataURL(file.raw);
  reader.onload = () => {
    form.value.photos.push({
      filename: file.name,
      data: reader.result?.toString().split(',')[1] || ''
    });
  };
};

const onCancel = () => {
  form.value = {
    condition: '',
    photos: []
  };
  fileList.value = [];
  emit('update:visible', false);
};

const onConfirm = () => {
  emit('confirm', form.value);
  onCancel();
};

defineExpose({
  dialogVisible
});
</script>

<style scoped>
.upload-demo {
  text-align: left;
}
</style> 