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

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

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

import { getDrugCategoriesTree, getZoneOptions } from '#/views/business/product/drug-categories/api';

import { updateZoneCategory } from '../api';

const gridApi = ref();
const currentRow = ref<Record<string, any>>({});

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

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

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

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

// 监听分区变化，动态加载分类
watch(
  () => formData.value.zone_id,
  async (newZoneId, oldZoneId) => {
    // 只有在用户手动切换分区时才清空分类（排除初始化）
    if (oldZoneId !== undefined) {
      formData.value.category_id = undefined;
    }
    await loadCategoryTree(newZoneId);
  }
);

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  async onConfirm() {
    modalApi.setState({ loading: true, confirmLoading: true });
    try {
      await updateZoneCategory({
        id: formData.value.id!,
        zone_id: formData.value.zone_id || null,
        category_id: formData.value.category_id || null,
      });
      message.success('设置成功');
      gridApi.value?.reload();
      modalApi.close();
    } finally {
      modalApi.setState({ loading: false, confirmLoading: false });
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const data = modalApi.getData<Record<string, any>>();
      gridApi.value = data?.gridApi;
      currentRow.value = data?.row || {};

      // 初始化表单数据
      formData.value = {
        id: currentRow.value.id,
        drug_name: currentRow.value.drug_name,
        zone_id: currentRow.value.zone_id || undefined,
        category_id: currentRow.value.category_id || undefined,
      };

      // 加载分区选项
      await loadZoneOptions();
      // 如果有初始 zone_id，加载对应分类
      if (formData.value.zone_id) {
        await loadCategoryTree(formData.value.zone_id);
      }
    }
  },
});
</script>

<template>
  <Modal title="分区分类设置" class="w-[450px]">
    <Form :model="formData" layout="horizontal" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <FormItem label="产品名称">
        <Input v-model:value="formData.drug_name" disabled />
      </FormItem>

      <FormItem label="所属分区">
        <Select
          v-model:value="formData.zone_id"
          :options="zoneOptions"
          :field-names="{ label: 'title', value: 'id' }"
          placeholder="请选择分区"
          allow-clear
        />
      </FormItem>

      <FormItem label="所属分类">
        <TreeSelect
          v-model:value="formData.category_id"
          :tree-data="categoryTreeData"
          :field-names="{ label: 'category_name', value: 'id', children: 'children' }"
          :placeholder="formData.zone_id ? '请选择分类' : '请先选择分区'"
          :loading="categoryLoading"
          :disabled="!formData.zone_id"
          allow-clear
          tree-default-expand-all
        />
      </FormItem>
    </Form>
  </Modal>
</template>
