<template>
	<view class="container">
		<u-form label-position="top" labelWidth="200" :model="form" :rules="rules" ref="formRef">
			<view class="card">
				<u-form-item label="活动名称" prop="title">
					<u-input placeholder="请输入活动名称" v-model="form.title" border="bottom" :customStyle="inputStyle"></u-input>
				</u-form-item>
				<u-form-item label="可用门店" prop="useShops">
					<my-shop-select-w v-model:useType="form.useShopType" v-model:selShops="form.useShops"></my-shop-select-w>
				</u-form-item>
			</view>
			<view class="card">
				<u-form-item label="活动日期" prop="validStartTime">
					<my-time-area v-model:startDate="form.validStartTime" v-model:endDate="form.validEndTime"></my-time-area>
				</u-form-item>
				<u-form-item label="可用日期" prop="useDays">
					<my-week-sel v-model="form.useDays"></my-week-sel>
				</u-form-item>
				<u-form-item label="指定时间段可用" prop="useTimeType">
					<my-hour-area v-model:useTimeType="form.useTimeType" v-model:startValue="form.useStartTime" v-model:endValue="form.useEndTime"></my-hour-area>
				</u-form-item>
			</view>
			<view class="card">
				<u-form-item label="可使用类型" prop="useType">
					<my-dine-types v-model="form.useType"></my-dine-types>
				</u-form-item>
			</view>
			<view class="card">
				<u-form-item label="折扣" prop="discountRate">
					<view class="center">
						<u-input placeholder="请输入折扣" type="number" v-model="form.discountRate" @change="discountRateInput">
							<template v-slot:suffix>%</template>
						</u-input>
						<text class="red-tips">范围：1-99%</text>
					</view>
					<view class="tips">
						<text class="t">例如：填写90，那么折扣后价格=原价*90%</text>
					</view>
				</u-form-item>
				<u-form-item label="优先级">
					<view class="center">
						<u-input placeholder="默认值：0" v-model="form.sort"></u-input>
					</view>
					<view class="tips">
						<text class="red-tips">数值越大，排序越靠前。重复时段下，按照排序值最高的折扣使用</text>
					</view>
				</u-form-item>
				<u-form-item label="限时折扣优先级">
					<u-radio-group v-model="form.discountPriority" placement="column">
						<u-radio label="优先使用限时折扣价" name="limit-time"></u-radio>
						<u-radio label="优先使用会员价/会员折扣" name="vip-price"></u-radio>
					</u-radio-group>
				</u-form-item>
			</view>
			<view class="card">
				<u-form-item label="参与商品" prop="foodType">
					<my-select-goods v-model:foodType="form.foodType" v-model="form.foods"></my-select-goods>
				</u-form-item>
			</view>
		</u-form>
		<my-footer-btn confirmText="保存" @confirm="submitHandle"></my-footer-btn>
	</view>
</template>

<script setup>
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
dayjs.extend(customParseFormat); // 注册插件
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { filterNumberInput } from '@/utils/index.js';
import { limitTimeDiscount } from '@/http/api/market/index.js';

const inputStyle = ref({
	paddingLeft: 0
});

const formRef = ref(null);

const form = ref({
	id: '',
	shopId: '',
	title: '', // 活动名称
	useShopType: 'only', // only-仅本店 all全部 /custom 指定
	useShops: [], // 可用门店
	validStartTime: '', // 有效期开始时间
	validEndTime: '', // 有效期结束时间
	useDays: ['周一', '周二', '周三'], // 周一,周二,周三,周四,周五,周六,周日
	useTimeType: 'all', // all-全时段，custom-指定时段
	useStartTime: '', // 可用开始时间
	useEndTime: '', // 可用结束时间
	useType: ['dine-in', 'take-out'], // 堂食 dine-in 外带 take-out 外卖 take-away 配送 post
	discountRate: '', // 折扣% 范围1-99
	sort: '', // 数字越小级别越高
	discountPriority: 'limit-time', // 折扣优先级 限时折扣优先limit-time/会员价优先vip-price
	foodType: 1, // 1全部 2部分
	foods: [] // 参与商品
});

const rules = ref({
	title: {
		type: 'string',
		required: true,
		message: '请输入活动名称',
		trigger: ['blur']
	},
	useShops: [
		{
			trigger: ['change'],
			message: '请选择可用门店',
			validator: (rule, value, callback) => {
				if (form.value.useShopType == 'custom' && form.value.useShops.length == 0) {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	validStartTime: [
		{
			required: true,
			trigger: ['change'],
			message: '请选择活动日期',
			validator: (rule, value, callback) => {
				if (form.value.validStartTime.length == 0 || form.value.validEndTime.length == 0) {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	useDays: [
		{
			required: true,
			message: '请选择可用日期',
			trigger: ['change'],
			validator: (rule, value, callback) => {
				if (form.value.useDays.length == 0) {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	useTimeType: [
		{
			required: true,
			trigger: ['change'],
			message: '请选择活动日期',
			validator: (rule, value, callback) => {
				if (form.value.useTimeType == 'custom' && (form.value.useStartTime.length == 0 || form.value.useEndTime.length == 0)) {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	useType: [
		{
			required: true,
			message: '请选择可使用类型',
			trigger: ['change'],
			validator: (rule, value, callback) => {
				if (form.value.useType.length == 0) {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	discountRate: [
		{
			required: true,
			type: 'string',
			message: '请输入折扣',
			trigger: ['blur'],
			validator: (rule, value, callback) => {
				if (form.value.discountRate == '') {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	foodType: [
		{
			trigger: ['change'],
			message: '请选择商品',
			validator: (rule, value, callback) => {
				if (form.value.foodType == 2 && form.value.foods.length == 0) {
					return false;
				} else {
					return true;
				}
			}
		}
	]
});

// 输入折扣率
function discountRateInput(e) {
	setTimeout(() => {
		form.value.discountRate = filterNumberInput(e, 1);
		if (form.value.discountRate > 99) {
			form.value.discountRate = 99;
		}
	}, 50);
}

/**
 * 时间格式互转：HH:mm → HH:mm:ss；HH:mm:ss → HH:mm
 * @param {string} timeStr - 输入的时间字符串
 * @returns {string} 转换后的时间字符串
 */
const convertTimeFormat = (timeStr) => {
	if (!timeStr) return '00:00';

	// 正则判断格式
	const isHms = /^\d{1,2}:\d{2}:\d{2}$/.test(timeStr); // HH:mm:ss
	const isHm = /^\d{1,2}:\d{2}$/.test(timeStr); // HH:mm

	if (isHm) {
		// HH:mm → 解析后格式化为 HH:mm:ss
		return dayjs(timeStr, 'HH:mm').format('HH:mm:ss');
	}

	if (isHms) {
		// HH:mm:ss → 解析后格式化为 HH:mm
		return dayjs(timeStr, 'HH:mm:ss').format('HH:mm');
	}

	// 非法格式兜底
	return '00:00';
};

// 提交保存
function submitHandle() {
	// console.log('前置form', form.value);
	formRef.value
		.validate()
		.then(async (res) => {
			try {
				const data = { ...form.value };

				console.log('通过了', data);
				data.shopId = uni.getStorageSync('shopInfo').id;
				data.useShops = form.value.useShops.join(',');
				data.useDays = form.value.useDays.join(',');
				data.useType = form.value.useType.join(',');
				data.foods = form.value.foods.join(',');
				data.useStartTime = convertTimeFormat(form.value.useStartTime);
				data.useEndTime = convertTimeFormat(form.value.useEndTime);

				uni.showLoading({
					title: '提交中...',
					mask: true
				});
				await limitTimeDiscount(data);
				uni.showToast({
					title: '添加成功',
					icon: 'none'
				});
				setTimeout(() => {
					uni.navigateBack();
				}, 1000);
			} catch (error) {
				console.log(error);
			}
			setTimeout(() => {
				uni.hideLoading();
			}, 500);
		})
		.catch((err) => {
			console.log(err);
		});
}

// 从本地获取限时折扣信息
function getLocalLimitDiscount() {
	const data = uni.getStorageSync('limitDiscountObj');
	if (data.id) {
		// uni.setStorageSync('limitDiscountObj', '');
		data.useShops = data.useShops.split(',');
		data.useDays = data.useDays.split(',');
		data.useType = data.useType.split(',');
		data.foods = data.foods.split(',');

		if (data.useStartTime) {
			data.useStartTime = convertTimeFormat(data.useStartTime);
			data.useEndTime = convertTimeFormat(data.useEndTime);
		}
		console.log('从本地获取限时折扣信息', data);
		form.value = { ...data };
	}
}

onLoad(() => {
	getLocalLimitDiscount();
});
</script>

<style>
page {
	background-color: #f7f7f7;
}
</style>

<style scoped lang="scss">
.container {
	padding: 28upx;
}
.card {
	background-color: #fff;
	border-radius: 20upx;
	padding: 0 28upx 14upx;
	margin-bottom: 28upx;
}
.center {
	display: flex;
	align-items: center;
	gap: 28upx;
}
.red-tips {
	font-size: 28upx;
	color: #eb4f4f;
}
.tips {
	padding-top: 8upx;
	.t {
		font-size: 28upx;
		color: #999;
	}
}
</style>
