<template>
	<view class="container">
		<u-form ref="formRef" :model="form" :rules="rules" label-position="top">
			<view class="card">
				<u-form-item prop="useShops">
					<view class="switch-wrap">
						<view class="top">
							<text class="t">可用门店</text>
						</view>
						<view class="info">
							<view class="ipt" v-if="isMainShop()">
								<my-shop-select-w v-model:useType="form.useShopType" v-model:selShops="form.useShops"></my-shop-select-w>
							</view>
							<view class="ipt" v-else>
								<u-radio-group v-model="form.useShopType">
									<u-radio label="仅本店" name="only"></u-radio>
								</u-radio-group>
							</view>
						</view>
					</view>
				</u-form-item>
			</view>
			<view class="card">
				<u-form-item prop="wareName">
					<view class="switch-wrap">
						<view class="top">
							<text class="t">商品名称</text>
							<text class="t2" @click="toSelectGoodS">导入已有商品</text>
						</view>
						<view class="info">
							<view class="ipt">
								<u-input placeholder="请输入" :maxlength="30" v-model="form.wareName"></u-input>
							</view>
						</view>
					</view>
				</u-form-item>
				<u-form-item>
					<view class="switch-wrap">
						<view class="top">
							<text class="t">商品描述</text>
						</view>
						<view class="info">
							<view class="ipt">
								<u-textarea placeholder="请输入" :maxlength="50" v-model="form.wareDetail"></u-textarea>
							</view>
						</view>
					</view>
				</u-form-item>
			</view>
			<view class="card">
				<u-form-item prop="wareImgs">
					<view class="switch-wrap">
						<view class="top column">
							<text class="t">商品图片</text>
							<text class="tips">*建议优先选择jpg格式，并且最好控制在500kb内</text>
						</view>
						<view class="info">
							<my-upload-imgs v-model="form.wareImgs"></my-upload-imgs>
						</view>
					</view>
				</u-form-item>
			</view>
			<view class="card">
				<u-form-item prop="originalPrice">
					<view class="switch-wrap">
						<view class="top">
							<text class="t">原价</text>
						</view>
						<view class="info">
							<view class="ipt">
								<u-input v-model="form.originalPrice" placeholder="请输入" @change="originalPriceInput">
									<template #suffix>
										<text>元</text>
									</template>
								</u-input>
							</view>
						</view>
					</view>
				</u-form-item>
				<u-form-item prop="groupPrice">
					<view class="switch-wrap">
						<view class="top">
							<text class="t">拼团价</text>
						</view>
						<view class="info">
							<view class="ipt">
								<u-input v-model="form.groupPrice" placeholder="请输入" @change="groupPriceInput">
									<template #suffix>
										<text>元</text>
									</template>
								</u-input>
							</view>
						</view>
					</view>
				</u-form-item>
				<u-form-item prop="groupPeopleNum">
					<view class="switch-wrap">
						<view class="top column">
							<text class="t">成团人数</text>
						</view>
						<view class="info">
							<view class="ipt">
								<u-input v-model="form.groupPeopleNum" placeholder="当参与人数达到成团人数才能完成拼团" @change="groupPeopleNumInput"></u-input>
							</view>
						</view>
					</view>
				</u-form-item>
				<u-form-item prop="groupTimeoutHour">
					<view class="switch-wrap">
						<view class="top column">
							<text class="t">成团期限（小时）</text>
						</view>
						<view class="info">
							<view class="ipt">
								<u-input v-model="form.groupTimeoutHour" placeholder="最小不低于1小时，最大不超过72小时" @change="groupTimeoutHourInput"></u-input>
							</view>
						</view>
					</view>
				</u-form-item>
			</view>
			<view class="card">
				<u-form-item prop="limitBuyNum">
					<view class="switch-wrap">
						<view class="top">
							<text class="t">限购数量</text>
							<u-switch v-model="limitBuyNumSwitch" @change="limitBuyNumSwitchChange"></u-switch>
						</view>
						<view class="info" v-if="limitBuyNumSwitch == 1">
							<view class="ipt">
								<u-input placeholder="请输入限购数量" :maxlength="8" v-model="form.limitBuyNum" @change="limitBuyNumInput"></u-input>
							</view>
						</view>
					</view>
				</u-form-item>
			</view>
			<view class="card">
				<u-form-item>
					<view class="switch-wrap">
						<view class="top column">
							<text class="t">商品详情</text>
							<text class="tips">*建议优先选择jpg格式，并且最好控制在500kb内</text>
						</view>
						<view class="info">
							<my-upload-imgs v-model="form.wareCommentImgs"></my-upload-imgs>
						</view>
					</view>
				</u-form-item>
			</view>
		</u-form>
		<my-footer-btn showCancel type="horizontal" @confirm="submitHandle" @cancel="backHandle"></my-footer-btn>
	</view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { filterNumberInput } from '@/utils/index.js';
import { addGbWare, updateGbWareById } from '@/http/api/ware.js';
import { isMainShop } from '@/store/account.js';

const type = ref('add'); // add添加商品 editor编辑商品
const formRef = ref(null);
const limitBuyNumSwitch = ref(false);
const form = ref({
	id: '',
	useShopType: 'only', // only-仅本店 all全部 /custom 指定
	useShops: [], // 可用门店（指定门店时存储门店ID，逗号分隔）
	wareName: '', // 商品名称
	wareDetail: '', // 商品描述
	wareImgs: [], // 商品图片（多个用逗号分隔）
	originalPrice: '', // 原价
	groupPrice: '', // 拼团价
	groupPeopleNum: '', // 成团人数 最小为1
	groupTimeoutHour: '', // 成团期限（小时）不低于1小时，最大72小时
	limitBuyNum: -10086, // 限购数量（每人最多购买次数） -10086
	onlineStatus: 1, // 上架状态（0下架 1上架）
	wareCommentImgs: [] // 商品详情图片（多个用逗号分隔）
});

const rules = ref({
	useShops: [
		{
			trigger: ['change'],
			message: '请选择可用门店',
			validator: (rule, value, callback) => {
				if (form.value.useShopType == 'custom' && form.value.useShops.length == 0) {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	wareName: [
		{
			required: true,
			trigger: ['blur'],
			message: '请输入',
			validator: (rule, value, callback) => {
				if (form.value.wareName === '') {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	wareImgs: [
		{
			required: true,
			trigger: ['blur'],
			message: '请选择商品图片',
			validator: (rule, value, callback) => {
				if (form.value.wareImgs.length == 0) {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	originalPrice: [
		{
			required: true,
			trigger: ['blur'],
			message: '请输入',
			validator: (rule, value, callback) => {
				if (form.value.originalPrice === '') {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	groupPrice: [
		{
			required: true,
			trigger: ['blur'],
			message: '请输入',
			validator: (rule, value, callback) => {
				if (form.value.groupPrice === '') {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	groupPeopleNum: [
		{
			required: true,
			trigger: ['blur'],
			message: '请输入',
			validator: (rule, value, callback) => {
				if (form.value.groupPeopleNum === '') {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	groupTimeoutHour: [
		{
			required: true,
			trigger: ['blur'],
			message: '请输入',
			validator: (rule, value, callback) => {
				if (form.value.groupTimeoutHour === '') {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	limitBuyNum: [
		{
			trigger: ['change', 'blur'],
			message: '请输入限购数量',
			validator: (rule, value, callback) => {
				if (limitBuyNumSwitch.value && form.value.limitBuyNum == '') {
					return false;
				} else {
					return true;
				}
			}
		}
	]
});

// 跳转去选择商品
function toSelectGoodS() {
	uni.navigateTo({
		url: '/pageMarket/groupGoods/selectGoods'
	});
}

const limitBuyNumFalseNum = -10086;
function limitBuyNumSwitchChange(e) {
	if (e) {
		form.value.limitBuyNum = '';
	} else {
		form.value.limitBuyNum = limitBuyNumFalseNum;
	}
}

// 原价
function originalPriceInput(e) {
	setTimeout(() => {
		form.value.originalPrice = filterNumberInput(e);
	}, 50);
}

// 拼团价
function groupPriceInput(e) {
	setTimeout(() => {
		form.value.groupPrice = filterNumberInput(e);
	}, 50);
}

// 成团人数
function groupPeopleNumInput(e) {
	setTimeout(() => {
		form.value.groupPeopleNum = filterNumberInput(e, 2);
	}, 50);
}

// 成团期限
function groupTimeoutHourInput(e) {
	setTimeout(() => {
		form.value.groupTimeoutHour = filterNumberInput(e, 1);
	}, 50);
}

// 限制购买数
function limitBuyNumInput(e) {
	setTimeout(() => {
		form.value.limitBuyNum = filterNumberInput(e, 1);
	}, 50);
}

// 保存商品
function submitHandle() {
	console.log(form.value);
	formRef.value
		.validate()
		.then(async () => {
			try {
				uni.showLoading({
					title: '保存中...',
					mask: true
				});
				const data = { ...form.value };
				if (form.value.useShopType.length) {
					data.useShops = form.value.useShops.join(',');
				}

				data.wareImgs = form.value.wareImgs.join(',');

				if (form.value.wareCommentImgs.length) {
					data.wareCommentImgs = form.value.wareCommentImgs.join(',');
				} else {
					data.wareCommentImgs = '';
				}

				if (form.value.id) {
					await updateGbWareById(data);
				} else {
					await addGbWare(data);
				}
				setTimeout(() => {
					uni.showToast({
						title: '保存成功',
						icon: 'none'
					});
				}, 300);
				setTimeout(() => {
					uni.navigateBack();
				}, 1000);
			} catch (error) {
				console.log(error);
			}
			uni.hideLoading();
		})
		.catch(() => {});
}

function backHandle() {
	uni.navigateBack();
}

// 从本地获取商品信息
function getLocalGoods() {
	let groupGoods = uni.getStorageSync('groupGoods');

	console.log(groupGoods);

	if (groupGoods && groupGoods.id) {
		form.value = groupGoods;

		if (form.value.useShops !== '') {
			form.value.useShops = form.value.useShops.split(',');
		} else {
			form.value.useShops = [];
		}

		if (form.value.wareImgs != '') {
			form.value.wareImgs = form.value.wareImgs.split(',');
		}

		if (form.value.wareCommentImgs != '') {
			form.value.wareCommentImgs = form.value.wareCommentImgs.split(',');
		}

		if (form.value.limitBuyNum == -10086) {
			limitBuyNumSwitch.value = false;
		} else {
			limitBuyNumSwitch.value = true;
		}
	}
}

// 从本地获取已选择的拼团商品
function getLocalGroupProduct() {
	let groupGoods = uni.getStorageSync('groupProduct');
	if (groupGoods && groupGoods.coverImg) {
		form.value.wareName = groupGoods.name;
		form.value.wareImgs = [groupGoods.coverImg];
		form.value.originalPrice = groupGoods.price;
	}
}

onShow(() => {
	getLocalGroupProduct();
});

onLoad((options) => {
	uni.setStorageSync('groupProduct', '');
	if (options.type && options.type == 'editor') {
		type.value = options.type;
		uni.setNavigationBarTitle({
			title: '编辑商品'
		});
		getLocalGoods();
	} else {
		type.value = 'add';
	}
});
</script>

<style>
page {
	background-color: #f8f8f8;
}
</style>
<style scoped lang="scss">
.container {
	padding: 28upx;
}
.card {
	background-color: #fff;
	border-radius: 20px;
	padding: 28upx;
	&:not(:last-child) {
		margin-bottom: 28upx;
	}
}
.switch-wrap {
	flex: 1;
	width: 100%;
	.top {
		display: flex;
		align-items: center;
		justify-content: space-between;
		&.column {
			align-items: flex-start;
			flex-direction: column;
		}
		.t {
			font-size: 32upx;
			color: #333;
			font-weight: bold;
		}
		.tips {
			font-size: 24upx;
			color: #666;
		}
		.t2 {
			font-size: 28upx;
			color: #3c9cff;
		}
	}
	.info {
		padding-top: 16upx;
		display: flex;
		align-items: center;
		gap: 16upx;
		.i {
			font-size: 28upx;
			color: #666;
		}
		.ipt {
			flex: 1;
		}
		.t {
			font-size: 24upx;
			color: #666;
		}
	}
}
</style>
