<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" @close="handleClose">
    <el-form :model="form" label-width="80px" ref="formRef">
      <el-form-item label="部门名称">
        <el-input v-model="form.name" placeholder="请输入部门名称" />
      </el-form-item>
      <el-form-item label="部门编码">
        <el-input v-model="form.code" placeholder="请输入部门编码" />
      </el-form-item>
      <el-form-item label="部门描述">
        <el-input 
          v-model="form.description" 
          type="textarea"
          :rows="3"
          placeholder="请输入部门描述" 
        />
      </el-form-item>
      <el-form-item label="排序">
        <el-input-number v-model="form.sort_order" :min="0" />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="form.status" placeholder="请选择状态">
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">保存</el-button>
    </template>
  </el-dialog>
</template>

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

interface DepartmentForm {
  id: number | null;
  name: string;
  code: string;
  description: string;
  sort_order: number;
  status: number;
  tenant_id: number | null;
}

const props = defineProps<{
  visible: boolean;
  isEdit: boolean;
  formData: DepartmentForm | null;
}>();

const emit = defineEmits<{
  'update:visible': [value: boolean];
  submit: [data: DepartmentForm];
  close: [];
}>();

const dialogVisible = ref(false);
const formRef = ref();
const form = ref<DepartmentForm>({
  id: null,
  name: "",
  code: "",
  description: "",
  sort_order: 0,
  status: 1,
  tenant_id: null,
});

const dialogTitle = computed(() => {
  return props.isEdit ? '编辑部门' : '添加部门';
});

watch(() => props.visible, (val) => {
  dialogVisible.value = val;
  if (val && props.formData) {
    form.value = { ...props.formData };
  } else if (val && !props.isEdit) {
    form.value = {
      id: null,
      name: "",
      code: "",
      description: "",
      sort_order: 0,
      status: 1,
      tenant_id: null,
    };
  }
});

watch(dialogVisible, (val) => {
  if (!val) {
    emit('update:visible', false);
    emit('close');
  }
});

const handleClose = () => {
  dialogVisible.value = false;
};

const handleSubmit = () => {
  emit('submit', { ...form.value });
};
</script>

