<template>
  <el-dialog 
    :title="dataForm.id ? '编辑' : '新增'" 
    v-model="visible" 
    width="600px"
    :close-on-click-modal="false"
    draggable>
    <el-form 
      ref="formRef" 
      :model="dataForm" 
      :rules="dataRules" 
      label-width="100px" 
      v-loading="loading">
      <el-form-item label="父级节点" prop="parentCode">
        <el-tree-select
          v-model="dataForm.parentCode"
          :data="parentData"
          :props="{ value: 'code', label: 'name', children: 'children' }"
          class="w100"
          clearable
          check-strictly
          :render-after-expand="false"
          placeholder="请选择父级节点（不选则为根节点）"
        />
      </el-form-item>
      <el-form-item label="品目编码" prop="code">
        <el-input 
          v-model="dataForm.code" 
          placeholder="请输入品目编码" 
          clearable 
          :disabled="!!dataForm.id" />
      </el-form-item>
      <el-form-item label="品目名称" prop="name">
        <el-input 
          v-model="dataForm.name" 
          placeholder="请输入品目名称" 
          clearable />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input 
          v-model="dataForm.remark" 
          type="textarea" 
          :rows="3"
          placeholder="请输入备注" 
          clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="PurchasingCategoryForm">
import { reactive, ref, nextTick } from 'vue'
import { getTree, addObj, editObj } from '/@/api/finance/purchasingcategory';
import { useMessage } from '/@/hooks/message';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const formRef = ref();
const dataForm = reactive({
  id: '',
  parentCode: '',
  code: '',
  name: '',
  remark: '',
  isMallService: '',
  isMallProject: '',
});
const parentData = ref<any[]>([]);
const visible = ref(false);
const loading = ref(false);

const dataRules = ref({
  code: [
    { required: true, message: '请输入品目编码', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入品目名称', trigger: 'blur' }
  ],
});

// 打开弹窗
const openDialog = (type: string, rowData?: any) => {
  visible.value = true;
  dataForm.id = '';
  dataForm.parentCode = '';
  dataForm.code = '';
  dataForm.name = '';
  dataForm.remark = '';
  dataForm.isMallService = '';
  dataForm.isMallProject = '';

  nextTick(() => {
    formRef.value?.resetFields();
    if (type === 'add' && rowData?.code) {
      // 新增时，rowData 是父节点数据，设置父级编码
      dataForm.parentCode = rowData.code;
    } else if (type === 'edit' && rowData) {
      // 编辑时，rowData 是当前行数据
      Object.assign(dataForm, {
        id: rowData.id || '',
        parentCode: rowData.parentCode || '',
        code: rowData.code || '',
        name: rowData.name || '',
        remark: rowData.remark || '',
        isMallService: rowData.isMallService || '',
        isMallProject: rowData.isMallProject || '',
      });
    }
  });

  getTreeData();
};

// 提交
const onSubmit = async () => {
  // 立即设置 loading，防止重复点击
  if (loading.value) return;
  loading.value = true;

  try {
    const valid = await formRef.value.validate().catch(() => {});
    if (!valid) {
      loading.value = false;
      return false;
    }

    if (dataForm.id) {
      await editObj(dataForm);
      useMessage().success('编辑成功');
    } else {
      await addObj(dataForm);
      useMessage().success('新增成功');
    }
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg || (dataForm.id ? '编辑失败' : '新增失败'));
  } finally {
    loading.value = false;
  }
};

// 从后端获取树形数据
const getTreeData = async () => {
  try {
    const res = await getTree();
    parentData.value = [];
    const root = {
      code: '',
      name: '根节点',
      children: [] as any[],
    };
    if (res.data && Array.isArray(res.data)) {
      root.children = res.data;
    }
    parentData.value.push(root);
  } catch (err: any) {
    useMessage().error(err.msg || '获取树形数据失败');
    parentData.value = [];
  }
};

// 暴露变量
defineExpose({
  openDialog,
});
</script>

<style scoped>
.w100 {
  width: 100%;
}
</style>

