<!-- 商品分类编辑弹窗 -->
<template>
  <ele-modal
    :width="560"
    :visible="visible"
    :maskClosable="false"
    :title="isUpdate ? '编辑分类' : '添加分类'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ flex: '90px' }"
      :wrapper-col="{ flex: '1' }"
    >
      <a-form-item label="分类名称" name="title">
        <a-input
          allow-clear
          placeholder="请输入分类名称"
          v-model:value="form.title"
          style="width: 100%"
        />
      </a-form-item>
      <a-form-item label="上级分类" name="parentId">
        <a-tree-select
          allow-clear
          :tree-data="parentTreeData"
          tree-default-expand-all
          style="width: 100%"
          placeholder="顶级分类（不选则为顶级）"
          :value="form.parentId || undefined"
          @update:value="(val?: number) => (form.parentId = val)"
        />
      </a-form-item>
      <a-form-item label="分类类型" name="type">
        <a-radio-group v-model:value="form.type">
          <a-radio :value="0">商城分类</a-radio>
          <a-radio :value="1">外卖分类</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="分类图片" name="image">
        <a-upload
          :before-upload="handleImageUpload"
          :show-upload-list="false"
          accept="image/*"
        >
          <a-button v-if="!form.image">
            <template #icon><UploadOutlined /></template>
            上传图片
          </a-button>
          <div v-else class="flex items-center gap-2">
            <img :src="form.image" style="width: 60px; height: 60px; object-fit: cover; border-radius: 4px; border: 1px solid #d9d9d9;" />
            <a-button type="text" danger size="small" @click.stop="form.image = undefined">删除</a-button>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item label="广告图" name="adImage">
        <a-upload
          :before-upload="handleAdImageUpload"
          :show-upload-list="false"
          accept="image/*"
        >
          <a-button v-if="!form.adImage">
            <template #icon><UploadOutlined /></template>
            上传广告图
          </a-button>
          <div v-else class="flex items-center gap-2">
            <img :src="form.adImage" style="width: 120px; height: 60px; object-fit: cover; border-radius: 4px; border: 1px solid #d9d9d9;" />
            <a-button type="text" danger size="small" @click.stop="form.adImage = undefined">删除</a-button>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item label="排序号" name="sortNumber">
        <a-input-number
          :min="0"
          :max="9999"
          style="width: 100%"
          placeholder="数值越小越靠前"
          v-model:value="form.sortNumber"
        />
      </a-form-item>
      <a-form-item label="分类标识" name="categoryCode">
        <a-input
          allow-clear
          placeholder="可选，如：shoes、clothing"
          v-model:value="form.categoryCode"
          style="width: 100%"
        />
      </a-form-item>
      <a-form-item label="状态" name="status">
        <a-radio-group v-model:value="form.status">
          <a-radio :value="0">正常</a-radio>
          <a-radio :value="1">禁用</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="备注" name="comments">
        <a-textarea
          :rows="3"
          :maxlength="200"
          placeholder="可选备注说明"
          v-model:value="form.comments"
        />
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch, computed } from 'vue';
  import { message } from 'ant-design-vue';
  import { UploadOutlined } from '@ant-design/icons-vue';
  import { assignObject, toTreeData } from 'ele-admin-pro';
  import { addShopGoodsCategory, updateShopGoodsCategory } from '@/api/shop/shopGoodsCategory';
  import { uploadFile } from '@/api/system/file';
  import type { ShopGoodsCategory } from '@/api/shop/shopGoodsCategory/model';
  import type { FormInstance } from 'ant-design-vue/es/form';

  const isUpdate = ref(false);

  const props = defineProps<{
    visible: boolean;
    data?: ShopGoodsCategory | null;
    categoryList?: ShopGoodsCategory[];
  }>();

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  const loading = ref(false);
  const formRef = ref<FormInstance | null>(null);

  const form = reactive<ShopGoodsCategory>({
    categoryId: undefined,
    categoryCode: undefined,
    title: undefined,
    type: 0,
    image: undefined,
    adImage: undefined,
    parentId: undefined,
    path: undefined,
    component: undefined,
    pageId: undefined,
    userId: undefined,
    count: undefined,
    sortNumber: 100,
    comments: undefined,
    hide: 0,
    recommend: 0,
    showIndex: 0,
    merchantId: undefined,
    status: 0,
    deleted: 0,
    tenantId: undefined,
    createTime: undefined,
    updateTime: undefined
  });

  // 父级分类树数据
  const parentTreeData = computed(() => {
    if (!props.categoryList) return [];
    // 排除自己和自己的子孙节点，防止循环引用
    const excludeIds = new Set<number>();
    const collectIds = (id?: number) => {
      if (!id) return;
      excludeIds.add(id);
      const children = props.categoryList?.filter((c) => c.parentId === id) || [];
      children.forEach((c) => collectIds(c.categoryId));
    };
    if (props.data?.categoryId) {
      collectIds(props.data.categoryId);
    }
    const filtered = props.categoryList?.filter((c) => !excludeIds.has(c.categoryId || 0)) || [];
    return toTreeData({
      data: filtered.map((c) => ({
        ...c,
        value: c.categoryId,
        label: c.title,
        title: c.title,
        key: c.categoryId
      })),
      idField: 'categoryId',
      parentIdField: 'parentId'
    });
  });

  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  // 表单验证规则
  const rules: Record<string, any> = {
    title: [
      {
        required: true,
        type: 'string',
        message: '请填写分类名称',
        trigger: 'blur'
      }
    ],
    type: [
      {
        required: true,
        type: 'number',
        message: '请选择分类类型',
        trigger: 'change'
      }
    ]
  };

  const save = () => {
    if (!formRef.value) return;
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const saveOrUpdate = isUpdate.value ? updateShopGoodsCategory : addShopGoodsCategory;
        saveOrUpdate({ ...form })
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  // 图片上传
  const handleImageUpload = async (file: File) => {
    const isImage = file.type?.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件');
      return false;
    }
    try {
      const res = await uploadFile(file);
      if (res?.path) {
        form.image = res.path;
      }
    } catch (e: any) {
      message.error(e.message || '上传失败');
    }
    return false; // 阻止默认上传
  };

  const handleAdImageUpload = async (file: File) => {
    const isImage = file.type?.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件');
      return false;
    }
    try {
      const res = await uploadFile(file);
      if (res?.path) {
        form.adImage = res.path;
      }
    } catch (e: any) {
      message.error(e.message || '上传失败');
    }
    return false;
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          assignObject(form, props.data);
          isUpdate.value = true;
        } else {
          // 重置为默认值
          Object.assign(form, {
            categoryId: undefined,
            categoryCode: undefined,
            title: undefined,
            type: 0,
            image: undefined,
            adImage: undefined,
            parentId: undefined,
            sortNumber: 100,
            comments: undefined,
            status: 0
          });
          isUpdate.value = false;
        }
      } else {
        formRef.value?.resetFields();
      }
    },
    { immediate: true }
  );
</script>
