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

import { useVbenModal } from '@vben/common-ui';

import { Form, FormItem, Input, InputNumber, message, Select, TreeSelect } from 'ant-design-vue';

import { createDrugCategories, getDrugCategoriesTree, getZoneOptions, updateDrugCategories } from '../api';

const isUpdate = ref(false);
const gridApi = ref();

// 表单数据
const formData = ref({
  id: null as number | null,
  zone_id: undefined as number | undefined,
  category_name: '',
  parent_id: 0 as number | undefined,
  sort: 0,
});

// 是否是添加子分类（有 parent_id 传入）
const isAddChild = ref(false);

// 是否正在初始化（用于避免 watch 清空 parent_id）
const isInitializing = ref(false);

// 选项数据
const zoneOptions = ref<any[]>([]);
const parentTreeData = ref<any[]>([]);
const parentLoading = ref(false);

// 分区是否禁用（添加子分类时禁用）
const zoneDisabled = computed(() => isAddChild.value);

// 加载分区选项
async function loadZoneOptions() {
  const res = await getZoneOptions();
  zoneOptions.value = res || [];
}

// 加载父级分类树（根据 zone_id）
async function loadParentTree(zoneId: number | undefined) {
  if (!zoneId) {
    parentTreeData.value = [];
    return;
  }
  parentLoading.value = true;
  try {
    const res = await getDrugCategoriesTree({ zone_id: zoneId });
    parentTreeData.value = res || [];
  } finally {
    parentLoading.value = false;
  }
}

// 监听分区变化，动态加载父级分类
watch(
  () => formData.value.zone_id,
  async (newZoneId, oldZoneId) => {
    // 只有在用户手动切换分区时才清空父级分类（排除初始化和添加子分类）
    if (!isInitializing.value && oldZoneId !== undefined && oldZoneId !== newZoneId && !isAddChild.value) {
      formData.value.parent_id = 0;
    }
    // 加载父级分类数据
    await loadParentTree(newZoneId);
  },
  { immediate: true }
);

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  async onConfirm() {
    // 简单验证
    if (!formData.value.zone_id) {
      message.error('请选择所属专区');
      return;
    }
    if (!formData.value.category_name?.trim()) {
      message.error('请输入分类名称');
      return;
    }

    modalApi.setState({ loading: true, confirmLoading: true });

    const submitData = {
      ...formData.value,
      parent_id: formData.value.parent_id || 0,
    };

    const submitApi = isUpdate.value ? updateDrugCategories : createDrugCategories;

    try {
      await submitApi(submitData);
      message.success(isUpdate.value ? '编辑成功' : '新增成功');
      gridApi.value?.reload();
      modalApi.close();
    } catch (err: any) {
      message.error(err?.message || '操作失败');
    } finally {
      modalApi.setState({ loading: false, confirmLoading: false });
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const { values, update, gridApi: gApi } = modalApi.getData<Record<string, any>>();
      gridApi.value = gApi;
      isUpdate.value = update;

      // 加载分区选项
      await loadZoneOptions();

      // 标记正在初始化，避免 watch 清空 parent_id
      isInitializing.value = true;

      if (update && values) {
        // 编辑模式
        isAddChild.value = false;
        formData.value = {
          id: values.id,
          zone_id: values.zone_id || undefined,
          category_name: values.category_name || '',
          parent_id: values.parent_id || 0,
          sort: values.sort || 0,
        };
      } else if (values?.parent_id) {
        // 添加子分类模式
        isAddChild.value = true;
        formData.value = {
          id: null,
          zone_id: values.zone_id || undefined,
          category_name: '',
          parent_id: values.parent_id,
          sort: 0,
        };
      } else {
        // 新增顶级分类模式
        isAddChild.value = false;
        formData.value = {
          id: null,
          zone_id: undefined,
          category_name: '',
          parent_id: 0,
          sort: 0,
        };
      }

      // 初始化完成后，重置标记
      // 使用 nextTick 确保 watch 已经处理完初始化的值变化
      setTimeout(() => {
        isInitializing.value = false;
      }, 0);
    }
  },
});
</script>

<template>
  <Modal :title="`${isUpdate ? '编辑' : '新增'}商品分类`" class="w-[500px]">
    <Form :model="formData" layout="horizontal" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
      <FormItem label="所属专区" required>
        <Select
          v-model:value="formData.zone_id"
          :options="zoneOptions"
          :field-names="{ label: 'title', value: 'id' }"
          placeholder="请选择所属专区"
          :disabled="zoneDisabled"
        />
      </FormItem>

      <FormItem label="分类名称" required>
        <Input v-model:value="formData.category_name" placeholder="请输入分类名称" />
      </FormItem>

      <FormItem label="父级分类">
        <TreeSelect
          v-model:value="formData.parent_id"
          :tree-data="parentTreeData"
          :field-names="{ label: 'category_name', value: 'id', children: 'children' }"
          :placeholder="formData.zone_id ? '请选择父级分类（不选则为顶级）' : '请先选择所属专区'"
          :loading="parentLoading"
          :disabled="!formData.zone_id || isAddChild"
          allow-clear
          tree-default-expand-all
        />
      </FormItem>

      <FormItem label="排序">
        <InputNumber
          v-model:value="formData.sort"
          :min="0"
          :max="9999"
          placeholder="请输入排序值，数值越小越靠前"
          style="width: 100%"
        />
      </FormItem>
    </Form>
  </Modal>
</template>
