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

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

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

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

/** 弹窗模式：enable=开启包邮，edit=编辑已有包邮条件 */
type FreeShippingModalMode = 'enable' | 'edit';

const gridApi = ref<any>();
const spId = ref(0);
const spName = ref('');
const mode = ref<FreeShippingModalMode>('enable');
/** 包邮条件剂数：0=始终包邮，>0=大于该剂数才包邮 */
const freeShippingMinDoses = ref(0);

const modalTitle = computed(() =>
  mode.value === 'edit' ? '编辑包邮条件' : '设置包邮条件',
);

const [Modal, modalApi] = useVbenModal({
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    if (spId.value <= 0) {
      return;
    }
    const minDoses = Math.max(0, Number(freeShippingMinDoses.value) || 0);
    modalApi.setState({ loading: true, confirmLoading: true });
    try {
      await updateSpecialPrescriptionFreeShipping({
        id: spId.value,
        is_free_shipping: 1,
        free_shipping_min_doses: minDoses,
      });
      message.success(mode.value === 'edit' ? '包邮条件已更新' : '已设为包邮');
      gridApi.value?.reload?.();
      gridApi.value?.query?.();
      modalApi.close();
    } finally {
      modalApi.setState({ loading: false, confirmLoading: false });
    }
  },
  onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      return;
    }
    const data = modalApi.getData<{
      id: number;
      name?: string;
      free_shipping_min_doses?: number;
      mode?: FreeShippingModalMode;
      gridApi?: any;
    }>();
    gridApi.value = data?.gridApi;
    spId.value = data?.id ?? 0;
    spName.value = data?.name ?? '';
    mode.value = data?.mode ?? 'enable';
    freeShippingMinDoses.value = data?.free_shipping_min_doses ?? 0;
  },
});
</script>

<template>
  <Modal :title="modalTitle" class="w-[80%]">
    <div class="free-shipping-dose-modal">
      <p v-if="spName" class="sp-name">特色方：{{ spName }}</p>
      <div class="form-row">
        <span class="label">包邮条件（剂数）</span>
        <InputNumber
          v-model:value="freeShippingMinDoses"
          :min="0"
          :precision="0"
          placeholder="0 表示始终包邮"
          style="width: 100%"
        />
      </div>
      <p class="hint">0 表示始终包邮；大于该剂数才包邮</p>
    </div>
  </Modal>
</template>

<style scoped>
.free-shipping-dose-modal {
  padding: 8px 0;
}

.sp-name {
  margin-bottom: 16px;
  color: #666;
  font-size: 13px;
}

.form-row {
  margin-bottom: 8px;
}

.form-row .label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-size: 14px;
}

.hint {
  margin: 0;
  color: #999;
  font-size: 12px;
}
</style>
