<template>
  <ele-modal
    :width="620"
    title="商品链接采集"
    :visible="visible"
    :confirm-loading="loading"
    @update:visible="updateVisible"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ flex: '90px' }"
      :wrapper-col="{ flex: '1' }"
    >
      <a-form-item label="商品链接" name="url">
        <a-input
          v-model:value="form.url"
          allow-clear
          placeholder="请输入商品详情页链接"
        />
      </a-form-item>
      <a-form-item label="商品分类" name="categoryId">
        <a-tree-select
          v-model:value="form.categoryId"
          allow-clear
          :tree-data="navigationList"
          tree-default-expand-all
          :listHeight="600"
          placeholder="请选择分类"
          :dropdown-style="{ overflow: 'auto' }"
        />
      </a-form-item>
      <a-form-item label="入库状态" name="status">
        <a-radio-group v-model:value="form.status">
          <a-radio :value="1">待上架</a-radio>
          <a-radio :value="0">直接上架</a-radio>
        </a-radio-group>
      </a-form-item>
    </a-form>
    <template #footer>
      <a-space>
        <a-button @click="updateVisible(false)">取消</a-button>
        <a-button type="primary" :loading="loading" @click="submit">
          开始采集
        </a-button>
      </a-space>
    </template>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { reactive, ref, watch } from 'vue';
  import { message } from 'ant-design-vue';
  import type { FormInstance, RuleObject } from 'ant-design-vue/es/form';
  import { collectShopGoods } from '@/api/shop/shopGoods';
  import type { ShopGoodsCollectParam } from '@/api/shop/shopGoods/model';
  import type { ShopGoodsCategory } from '@/api/shop/shopGoodsCategory/model';
  import { getMerchantId } from '@/utils/merchant';

  const props = defineProps<{
    visible: boolean;
    navigationList?: ShopGoodsCategory[];
  }>();

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

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

  const form = reactive<ShopGoodsCollectParam>({
    url: '',
    categoryId: undefined,
    status: 1,
    merchantId: getMerchantId() || undefined
  });

  const validateUrl = async (_rule: RuleObject, value?: string) => {
    if (!value) {
      return Promise.reject('请输入商品链接');
    }
    try {
      const parsed = new URL(value);
      if (!['http:', 'https:'].includes(parsed.protocol)) {
        return Promise.reject('请输入正确的商品链接');
      }
      return Promise.resolve();
    } catch (_) {
      return Promise.reject('请输入正确的商品链接');
    }
  };

  const rules = reactive<Record<string, RuleObject[]>>({
    url: [
      {
        required: true,
        validator: validateUrl,
        trigger: 'blur'
      }
    ]
  });

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

  const resetForm = () => {
    form.url = '';
    form.categoryId = undefined;
    form.status = 1;
    form.merchantId = getMerchantId() || undefined;
    formRef.value?.clearValidate();
  };

  const submit = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        collectShopGoods({
          ...form,
          url: form.url.trim()
        })
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        form.merchantId = getMerchantId() || undefined;
      } else {
        resetForm();
      }
    }
  );
</script>
