<template>
  <el-dialog :v-model="visible" :title="dialogTitle" width="600px" destroy-on-close :close-on-click-modal="false">
    <el-form ref="formRef" :model="formModel" :rules="rules" :disabled="isView" label-width="100px">
      <el-form-item label="地块名称" prop="name">
        <el-input v-model="formModel.name" placeholder="请输入地块名称" />
      </el-form-item>

      <el-form-item label="所属区域" prop="areaCode">
        <AreaSelect v-model="formModel.areaCode" :emit-path="false" />
      </el-form-item>

      <el-form-item label="面积（亩）" prop="area">
        <el-input-number v-model="formModel.area" :min="0" placeholder="请输入面积" />
      </el-form-item>

      <el-form-item label="图像文件" prop="image">
        <FileUploader v-model="formModel.image" :limit="1" />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input v-model="formModel.remark" type="textarea" placeholder="请输入备注" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button v-if="!isView" type="primary" :loading="submitting" @click="submit">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, computed } from 'vue';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  initialData: {
    type: Object,
    default: () => ({}),
  },
  mode: {
    type: String,
    default: 'create', // 'create' | 'edit' | 'view'
  },
  type: {
    type: String,
    default: '', // 地块类型：grass / forest / field
  },
});

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

const formRef = ref(null);
const formModel = ref({});
const submitting = ref(false);

const isView = computed(() => props.mode === 'view');
const dialogTitle = computed(() => {
  switch (props.mode) {
    case 'create':
      return '新增地块';
    case 'edit':
      return '编辑地块';
    case 'view':
      return '查看地块';
    default:
      return '地块信息';
  }
});

const rules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  areaCode: [{ required: true, message: '请选择区域', trigger: 'change' }],
  area: [{ required: true, message: '请输入面积', trigger: 'blur' }],
};

watch(
  () => props.visible,
  (val) => {
    if (val) {
      formModel.value = { ...props.initialData };
    }
  }
);

function close() {
  emit('update:visible', false);
}

async function submit() {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
    submitting.value = true;
    emit('submit', { ...formModel.value });
  } catch (err) {
    console.warn('表单校验失败', err);
  } finally {
    submitting.value = false;
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
