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

import { message, Tag } from 'ant-design-vue';

import { toggleDrugFreeShipping } from './drug-free-shipping-api';

const props = defineProps<{
  /** 列表行：需含 id、is_free_shipping */
  row: {
    id: number | string;
    is_free_shipping?: number;
  };
}>();

const emit = defineEmits<{
  /** 切换成功后通知父级刷新列表 */
  (e: 'changed'): void;
}>();

const loading = ref(false);

/**
 * 点击 Tag 切换单品包邮；成功后回写行内状态并通知父级
 */
const onToggle = async () => {
  if (loading.value) {
    return;
  }
  const drugId = Number(props.row.id);
  if (!drugId) {
    return;
  }
  loading.value = true;
  try {
    const res = await toggleDrugFreeShipping(drugId);
    const next = Number(res?.is_free_shipping ?? 0);
    props.row.is_free_shipping = next;
    message.success(next === 1 ? '已设为单品包邮' : '已取消单品包邮');
    emit('changed');
  } finally {
    loading.value = false;
  }
};
</script>

<template>
  <Tag
    :color="row.is_free_shipping === 1 ? 'success' : 'default'"
    class="cursor-pointer"
    :class="{ 'opacity-60': loading }"
    @click="onToggle"
  >
    {{ row.is_free_shipping === 1 ? '包邮' : '不包邮' }}
  </Tag>
</template>
