import { normalizeQuickOptions as normalizeQuickOptionsFromUtil } from '@/subPackages/sub_business_shared/common/pricePercentAdjust.js'

export const orderPriceAdjustMixin = {

	data() {

		return {

			priceAdjustVisible: false,

			priceAdjustQuickOptions: [],

			priceAdjustScopeMode: 'sale_only',

			priceAdjustSubmitting: false,

		}

	},

	computed: {

		canOrderPercentAdjust() {

			return Number(this.info?.is_pay) !== 1

				&& Number(this.info?.store?.enable_order_price_percent_adjust) === 1

		},

		orderPriceDiscountLabel() {

			const d = Number(this.info?.price_discount ?? 100)

			if (d === 100) return ''

			return this.info?.price_discount_label || this.formatDiscountLabel(d)

		},

	},

	methods: {

		formatDiscountLabel(discount) {

			const d = Number(discount) || 100

			if (d <= 0 || d === 100) return ''

			if (d < 100) {

				if (d % 10 === 0 && d >= 10) return `${d / 10}折`

				return `折扣 ${d}%`

			}

			return `涨 ${d - 100}%`

		},

		normalizeQuickOptions(raw) {
			return normalizeQuickOptionsFromUtil(raw)
		},

		async loadPriceAdjustMeta(apiFn) {

			try {

				const w = await apiFn()

				if (w?.ok && w.data) {

					this.priceAdjustScopeMode = w.data.order_price_adjust_scope === 'both' ? 'both' : 'sale_only'

					this.priceAdjustQuickOptions = this.normalizeQuickOptions(w.data.order_discount_quick_options)

				}

			} catch (e) { /* ignore */ }

		},

		openOrderPriceAdjust() {

			if (!this.canOrderPercentAdjust) return

			this.priceAdjustVisible = true

		},

		closePriceAdjust() {

			this.priceAdjustVisible = false

		},

		async onPriceAdjustConfirm(payload, api) {

			if (this.priceAdjustSubmitting) return

			this.priceAdjustSubmitting = true

			try {

				const w = await api.adjustOrderPercent({

					product_order_id: this.info.id,

					price_discount: payload.priceDiscount,

				})

				if (!w.ok) return

				uni.showToast({ title: payload.priceDiscount === 100 ? '已清除浮动' : '调价成功' })

				this.closePriceAdjust()

				await this.load()

			} finally {

				this.priceAdjustSubmitting = false

			}

		},

		async clearOrderPriceDiscount(api) {

			return this.onPriceAdjustConfirm({ priceDiscount: 100 }, api)

		},

	},

}



export { applyRatioToDrug, applyRatioToDrugs } from '@/subPackages/sub_business_shared/common/pricePercentAdjust.js'

