<template>
	<view class="container">
		<u-form ref="formRef" label-position="top" labelWidth="200" :model="form" :rules="rules">
			<view class="u-form-card">
				<u-form-item :label="`${getEmunListLabel('couponTypes', form.couponType)}名称`" prop="title">
					<u-input placeholder="请输入优惠券名称" :maxlength="20" v-model="form.title" border="bottom" :customStyle="{ paddingLeft: 0 }"></u-input>
				</u-form-item>
				<view v-if="form.couponType == 1">
					<u-form-item label="使用门槛" prop="fullAmount">
						<view class="center">
							<view>
								<u-input placeholder="请输入" v-model="form.fullAmount" :maxlength="8" input-align="center" @change="fullAmountInput">
									<template v-slot:prefix>满</template>
									<template v-slot:suffix>元</template>
								</u-input>
							</view>
							<view>
								<u-input placeholder="请输入" v-model="form.discountAmount" :maxlength="8" input-align="center" @change="discountAmountInput">
									<template v-slot:prefix>减</template>
									<template v-slot:suffix>元</template>
								</u-input>
							</view>
						</view>
					</u-form-item>
				</view>
				<view v-if="form.couponType == 2">
					<u-form-item label="使用门槛" prop="fullAmount2">
						<u-input placeholder="请输入" v-model="form.fullAmount" :maxlength="8" input-align="center" @change="fullAmountInput">
							<template v-slot:prefix>满</template>
							<template v-slot:suffix>可用</template>
						</u-input>
					</u-form-item>
					<u-form-item label="可用商品" prop="foods">
						<my-select-goods v-model="form.foods" v-model:foodType="form.goodsType" @foodTypeChange="goodsTypeChange"></my-select-goods>
					</u-form-item>
					<u-form-item label="使用规则">
						<u-radio-group v-model="form.useRule" placement="column">
							<u-radio :label="item.label" :name="item.value" v-for="item in emunList.useRule" :key="item.value" :customStyle="radioStyle"></u-radio>
						</u-radio-group>
					</u-form-item>
					<u-form-item label="可抵扣商品件数" prop="discountNum">
						<u-input placeholder="请输入可抵扣商品件数" v-model="form.discountNum" @change="discountNumInput"></u-input>
					</u-form-item>
				</view>
				<view v-if="form.couponType == 3">
					<u-form-item label="折扣" prop="discountRate">
						<u-input placeholder="输入折扣（%）" v-model="form.discountRate" @change="discountRateInput">
							<template v-slot:suffix>%</template>
						</u-input>
					</u-form-item>
					<u-form-item label="使用门槛" prop="fullAmount2">
						<u-input placeholder="请输入" v-model="form.fullAmount" :maxlength="8" input-align="center" @change="fullAmountInput">
							<template v-slot:prefix>满</template>
							<template v-slot:suffix>可用</template>
						</u-input>
					</u-form-item>
					<u-form-item label="可抵扣最大金额" prop="maxDiscountAmount">
						<u-input placeholder="请输入内容" v-model="form.maxDiscountAmount" :maxlength="8" input-align="center" @change="maxDiscountAmountInput">
							<template v-slot:prefix>元</template>
						</u-input>
					</u-form-item>
				</view>
				<view v-if="form.couponType == 4 || form.couponType == 6">
					<u-form-item label="可用商品" prop="foods">
						<my-select-goods v-model="form.foods" v-model:foodType="form.goodsType" @foodTypeChange="goodsTypeChange"></my-select-goods>
					</u-form-item>
					<u-form-item label="使用规则">
						<u-radio-group v-model="form.useRule" placement="column">
							<u-radio :label="item.label" :name="item.value" v-for="item in emunList.useRule" :key="item.value" :customStyle="radioStyle"></u-radio>
						</u-radio-group>
					</u-form-item>
				</view>
			</view>
			<view class="u-form-card">
				<u-form-item label="可用门店" prop="useShops" v-if="shopInfo.isHeadShop && shopInfo.shopType != 'only'">
					<my-shop-select-w v-model:useType="form.useShopType" v-model:selShops="form.useShops"></my-shop-select-w>
				</u-form-item>
				<u-form-item label="可用商品" v-if="form.couponType != 2 && form.couponType != 4 && form.couponType != 6" prop="foods">
					<my-select-goods v-model="form.foods" v-model:foodType="form.goodsType" @foodTypeChange="goodsTypeChange"></my-select-goods>
				</u-form-item>
				<u-form-item label="可使用类型" prop="useType">
					<my-dine-types v-model="form.useType"></my-dine-types>
				</u-form-item>
			</view>
			<view class="u-form-card">
				<u-form-item label="有效期类型">
					<u-radio-group v-model="form.validType" placement="column">
						<u-radio :label="item.label" :name="item.value" v-for="item in emunList.validType" :key="item.value"></u-radio>
					</u-radio-group>
				</u-form-item>
				<u-form-item label="有效期" prop="validDays">
					<template v-if="form.validType == 'fixed'">
						<u-input placeholder="请输入有效期" v-model="form.validDays" :maxlength="8" @change="validDaysInput">
							<template v-slot:suffix>天</template>
						</u-input>
					</template>
					<template v-else>
						<my-time-area v-model:startDate="form.validStartTime" v-model:endDate="form.validEndTime"></my-time-area>
					</template>
				</u-form-item>
				<u-form-item label="隔天生效" prop="daysToTakeEffect" v-if="form.validType == 'fixed'">
					<view class="center">
						<div class="ipt">
							<u-input placeholder="请输入隔天生效日期" input-align="center" :maxlength="5" v-model="form.daysToTakeEffect" @change="daysToTakeEffectInput">
								<template v-slot:prefix>隔</template>
								<template v-slot:suffix>天生效</template>
							</u-input>
						</div>
						<div class="tips-icon" @click="showDaysToTakeEffectTipsHandle">
							<u-icon name="question-circle-fill" size="22" color="#999"></u-icon>
						</div>
					</view>
				</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="u-form-card">
				<u-form-item label="发放设置" prop="getType">
					<my-get-type v-model:getType="form.getType" v-model:getMode="form.getMode"></my-get-type>
				</u-form-item>
				<u-form-item label="总发放数量" prop="giveNum">
					<view class="column">
						<view class="center">
							<u-switch v-model="infiniteGiveNum" @change="infiniteGiveNumChange"></u-switch>
							<text class="tips">关闭则为无限制</text>
						</view>
						<view class="center" v-if="infiniteGiveNum">
							<view class="ipt">
								<u-input placeholder="请输入总发放数量" :maxlength="5" v-model="form.giveNum" @change="giveNumInput">
									<template v-slot:suffix>张</template>
								</u-input>
							</view>
						</view>
					</view>
				</u-form-item>
			</view>
			<view class="u-form-card">
				<u-form-item label="可领取用户">
					<u-radio-group v-model="form.getUserType">
						<u-radio :label="item.label" :name="item.value" v-for="item in emunList.getUserType" :key="item.value" :customStyle="radioStyle"></u-radio>
					</u-radio-group>
				</u-form-item>
				<u-form-item label="每人限领量" prop="getLimit">
					<u-input placeholder="请输入每人限领量" :maxlength="5" v-model="form.getLimit" @change="getLimitInput">
						<template v-slot:suffix>张</template>
					</u-input>
				</u-form-item>
				<u-form-item label="每人每日使用限量">
					<u-radio-group v-model="infiniteUseLimit" @change="infiniteUseLimitChange">
						<u-radio label="无限制" :name="true" :customStyle="radioStyle"></u-radio>
						<u-radio label="每日限用" :name="false" :customStyle="radioStyle"></u-radio>
					</u-radio-group>
				</u-form-item>
				<u-form-item label="限用数量" v-if="!infiniteUseLimit" prop="useLimit">
					<u-input placeholder="需小于或等于每人限领量" :maxlength="5" v-model="form.useLimit" @change="useLimitInput">
						<template v-slot:suffix>张/每人1天</template>
					</u-input>
				</u-form-item>
			</view>
			<view class="u-form-card">
				<u-form-item label="与限时折扣同享">
					<view class="column">
						<view class="center">
							<u-switch v-model="form.discountShare" :active-value="1" :inactive-value="0"></u-switch>
						</view>
						<text class="tips">开启后，计算门槛时将会计入已折扣的商品</text>
					</view>
				</u-form-item>
				<u-form-item label="与会员价同享">
					<view class="column">
						<view class="center">
							<u-switch v-model="form.vipPriceShare" :active-value="1" :inactive-value="0"></u-switch>
						</view>
						<text class="tips">开启后，计算门槛时将会计入已享受会员价的商品</text>
					</view>
				</u-form-item>
				<u-form-item label="与其他优惠券同享" v-if="form.couponType == 2">
					<view class="column">
						<view class="center">
							<u-switch v-model="form.otherCouponShare" :active-value="1" :inactive-value="0"></u-switch>
						</view>
						<text class="tips">开启后，可与其他优惠券同时使用</text>
					</view>
				</u-form-item>
			</view>
			<view class="u-form-card">
				<u-form-item label="规则附加说明">
					<u-textarea :maxlength="250" count :height="150" v-model="form.ruleDetails"></u-textarea>
				</u-form-item>
			</view>
		</u-form>
		<my-footer-btn @confirm="submitHandle" v-if="(shopInfo.isHeadShop && shopInfo.shopType != 'only') || !form.syncId"></my-footer-btn>
	</view>
</template>

<script setup>
import dayjs from 'dayjs';
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { emunList, getEmunListLabel } from '../utils/couponUtils.js';
import { filterNumberInput, convertTimeFormat } from '@/utils/index.js';
import { couponAdd, couponDetail } from '@/http/api/market/index.js';

const radioStyle = {
	marginRight: '20px'
};

const shopInfo = ref({});

const formRef = ref(null);
const form = ref({
	id: '',
	shopId: '',
	syncId: '',
	couponType: 1, // 1-满减券，2-商品兑换券，3-折扣券，4-第二件半价券，5-消费送券，6-买一送一券，7-固定价格券，8-免配送费券
	title: '', // 券名称
	fullAmount: '', // 使用门槛
	discountAmount: '', // 使用门槛：减多少金额
	useShopType: 'only', // only-仅本店 all-所有门店，custom-指定门店
	useShops: '', // id字符串拼接
	goodsType: 1, // 1=全部商品参与计算门槛 2=部分商品参与计算门槛
	foods: '', // 指定门槛商品 id拼接
	useType: ['dine-in'], // 堂食 dine-in  外带 take-out 外卖 take-away 配送 post
	validType: 'fixed', // 有效期类型：fixed（固定时间），custom（自定义时间）
	validDays: '', // 有效期(天)
	validStartTime: '', // 有效期开始时间
	validEndTime: '', // 有效期结束时间
	daysToTakeEffect: 0, // 隔天生效
	useDays: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'], // 可用周期，如：'周一','周二','周三' , '周四' , '周五', '周六' , '周七'
	useTimeType: 'all', // 可用时间段类型：all-全时段，custom-指定时段
	useStartTime: '', // 可用开始时间
	useEndTime: '', // 可用结束时间
	getType: 'no', // 发放设置：不可自行领取/no，可领取/yes
	getMode: ['eat'], // 用户领取方式 home/首页-优惠券 eat/点餐页-自动弹出 order/订单支付页面
	giveNum: '', // 总发放数量，-10086为不限量
	getUserType: 'all', // 可领取用户：全部/all，新用户一次/new，仅会员/vip
	getLimit: 1, // 每人领取限量，-10086为不限量
	useLimit: -10086, // 每人每日使用限量，-10086为不限量
	discountShare: 1, // 与限时折扣同享：0-否，1-是
	vipPriceShare: 1, // 与会员价同享：0-否，1-是
	ruleDetails: '', // 附加规则说明
	status: 1, // 状态：0-禁用，1-启用
	useNum: '', // 已使用数量
	leftNum: '', // 剩余数量
	discountRate: '', // 折扣%
	maxDiscountAmount: '', // 可抵扣最大金额 元
	useRule: 'price_asc', // 使用规则：price_asc-价格低到高，price_desc-高到低
	discountNum: 1, // 抵扣数量
	otherCouponShare: 1 // 与其它优惠共享：0-否，1-是
});

function goodsTypeChange(e) {
	console.log('goodsTypeChange===', e);
	if (e == 1) {
		form.value.foods = '';
	}
}

const rules = ref({
	title: [
		{
			type: 'string',
			required: true,
			message: '请输入活动名称',
			trigger: ['blur']
		}
	],
	fullAmount: [
		{
			required: true,
			trigger: ['blur'],
			message: '请输入使用门槛',
			validator: (rule, value, callback) => {
				if (form.value.fullAmount < 0 || form.value.fullAmount === '') {
					return false;
				} else {
					return true;
				}
			}
		},
		{
			required: true,
			trigger: ['blur'],
			message: '请输入满减金额',
			validator: (rule, value, callback) => {
				if (form.value.discountAmount <= 0 || form.value.discountAmount === '') {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	fullAmount2: [
		{
			required: true,
			trigger: ['blur'],
			message: '请输入使用门槛',
			validator: (rule, value, callback) => {
				if (form.value.fullAmount < 0 || form.value.fullAmount === '') {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	useShops: [
		{
			trigger: ['change'],
			message: '请选择门店',
			validator: (rule, value, callback) => {
				if (form.value.useShopType == 'custom' && form.value.useShops.length == 0) {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	foods: [
		{
			trigger: ['change'],
			message: '请选择商品',
			validator: (rule, value, callback) => {
				if (form.value.goodsType == 2 && form.value.foods.length == 0) {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	discountNum: [
		{
			required: true,
			trigger: ['blur'],
			message: '请输入可抵扣商品件数',
			validator: (rule, value, callback) => {
				if (form.value.discountNum === '') {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	discountRate: [
		{
			required: true,
			trigger: ['blur'],
			message: '输入折扣（%）',
			validator: (rule, value, callback) => {
				if (form.value.discountRate === '') {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	maxDiscountAmount: [
		{
			required: true,
			trigger: ['blur'],
			message: '输入可抵扣最大金额',
			validator: (rule, value, callback) => {
				if (form.value.maxDiscountAmount === '') {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	useType: [
		{
			required: true,
			trigger: ['change'],
			message: '请选择可使用类型',
			validator: (rule, value, callback) => {
				if (form.value.useType.length == 0) {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	validDays: [
		{
			trigger: ['blur'],
			message: '请输入有效期',
			validator: (rule, value, callback) => {
				if (form.value.validType == 'fixed' && form.value.validDays === '') {
					return false;
				} else {
					return true;
				}
			}
		},
		{
			trigger: ['change'],
			message: '请选择有效期',
			validator: (rule, value, callback) => {
				if (form.value.validType == 'custom' && (form.value.validStartTime === '' || form.value.validEndTime == '')) {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	daysToTakeEffect: [
		{
			required: true,
			trigger: ['blur'],
			message: '请输入隔天生效日期',
			validator: (rule, value, callback) => {
				if (form.value.daysToTakeEffect === '') {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	useDays: [
		{
			required: true,
			trigger: ['change'],
			message: '请选择可用周期',
			validator: (rule, value, callback) => {
				if (form.value.useDays.length == 0) {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	useTimeType: [
		{
			trigger: ['change'],
			message: '请选择指定时间段',
			validator: (rule, value, callback) => {
				if (form.value.useTimeType == 'custom' && (form.value.useStartTime === '' || form.value.useEndTime == '')) {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	getType: [
		{
			required: true,
			trigger: ['change'],
			message: '请选择用户领取方式',
			validator: (rule, value, callback) => {
				if (form.value.getType == 'yes' && form.value.getMode.length == 0) {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	giveNum: [
		{
			trigger: ['blur'],
			message: '请输入总发放数量',
			validator: (rule, value, callback) => {
				if (infiniteGiveNum.value && form.value.giveNum === '') {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	getLimit: [
		{
			trigger: ['blur'],
			message: '请输入每人限领量',
			validator: (rule, value, callback) => {
				if (form.value.getLimit === '') {
					return false;
				} else {
					return true;
				}
			}
		}
	],
	useLimit: [
		{
			trigger: ['blur'],
			message: '请输入限用数量',
			validator: (rule, value, callback) => {
				if (!infiniteUseLimit.value && form.value.useLimit === '') {
					return false;
				} else {
					return true;
				}
			}
		}
	]
});

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

				console.log('11111111111', data);

				if (form.value.goodsType == 2) {
					data.foods = form.value.foods.join(',');
				}
				if (form.value.useShopType == 'custom') {
					data.useShops = form.value.useShops.join(',');
				}
				if (form.value.getType == 'yes') {
					data.getMode = JSON.stringify(form.value.getMode);
				}
				if (form.value.useTimeType == 'custom') {
					data.useStartTime = convertTimeFormat(form.value.useStartTime);
					data.useEndTime = convertTimeFormat(form.value.useEndTime);
				}
				data.useDays = JSON.stringify(form.value.useDays);
				data.useType = JSON.stringify(form.value.useType);

				console.log('22222222222', data);

				uni.showLoading({
					title: '提交中...',
					mask: true
				});
				await couponAdd(data);
				uni.showToast({
					title: '保存成功',
					icon: 'none'
				});
				setTimeout(() => {
					uni.navigateBack();
				}, 1000);
			} catch (error) {
				console.log(error);
			}

			setTimeout(() => {
				uni.hideLoading();
			}, 500);
		})
		.catch((err) => {});
}

const inputTime = 50;
function fullAmountInput(e) {
	setTimeout(() => {
		form.value.fullAmount = filterNumberInput(e, 0);
	}, inputTime);
}

function discountAmountInput(e) {
	setTimeout(() => {
		form.value.discountAmountInput = filterNumberInput(e);
	}, inputTime);
}

function discountNumInput(e) {
	setTimeout(() => {
		form.value.discountNum = filterNumberInput(e, 1);
	}, inputTime);
}

function discountRateInput(e) {
	setTimeout(() => {
		form.value.discountRate = filterNumberInput(e, 1);
		if (form.value.discountRate >= 100) {
			form.value.discountRate = 100;
		}
	}, inputTime);
}

function maxDiscountAmountInput(e) {
	setTimeout(() => {
		form.value.maxDiscountAmount = filterNumberInput(e);
	}, inputTime);
}

function validDaysInput(e) {
	setTimeout(() => {
		form.value.validDays = filterNumberInput(e);
	}, inputTime);
}

function daysToTakeEffectInput(e) {
	setTimeout(() => {
		form.value.daysToTakeEffect = filterNumberInput(e, 0);
	}, inputTime);
}

function showDaysToTakeEffectTipsHandle() {
	uni.showModal({
		title: '注意',
		content: `领取后${form.value.daysToTakeEffect}天后的0点0分生效`,
		showCancel: false
	});
}

const infiniteNum = -10086; // 无限
const infiniteGiveNum = ref(true);
function infiniteGiveNumChange(e) {
	if (!e) {
		form.value.giveNum = infiniteNum;
	} else {
		form.value.giveNum = '';
	}
}

function giveNumInput(e) {
	setTimeout(() => {
		form.value.giveNum = filterNumberInput(e, 1);
	}, inputTime);
}

function getLimitInput(e) {
	setTimeout(() => {
		form.value.getLimit = filterNumberInput(e, 1);
	}, inputTime);
}

// 是否为无限每人领取限量
const infiniteUseLimit = ref(true);
function infiniteUseLimitChange(e) {
	if (e) {
		form.value.useLimit = infiniteNum.value;
	} else {
		form.value.useLimit = '';
	}
}

function useLimitInput(e) {
	setTimeout(() => {
		form.value.useLimit = filterNumberInput(e, 1);
		if (form.value.useLimit >= form.value.getLimit) {
			form.value.useLimit = form.value.getLimit;
		}
	}, inputTime);
}

// 获取优惠券详情
async function couponDetailAjax() {
	try {
		uni.showLoading({
			title: '加载中...',
			mask: true
		});
		const res = await couponDetail(form.value.id);
		res.goodsType = 1;

		form.value = { ...res };
		form.value.getMode = JSON.parse(form.value.getMode);
		form.value.useDays = JSON.parse(form.value.useDays);
		form.value.useType = JSON.parse(form.value.useType);

		if (!!form.value.syncId) {
			form.value.useShopType = 'only';
		}

		if (form.value.foods != '') {
			form.value.goodsType = 2;
			form.value.foods = form.value.foods.split(',');
		} else {
			form.value.goodsType = 1;
		}

		if (form.value.useShops != '' && form.value.useShopType == 'custom') {
			form.value.useShops = form.value.useShops.split(',');
		}

		if (form.value.validType == 'custom') {
			form.value.validStartTime = dayjs(form.value.validStartTime).format('YYYY-MM-DD');
			form.value.validEndTime = dayjs(form.value.validEndTime).format('YYYY-MM-DD');
		}

		if (form.value.useTimeType == 'custom') {
			form.value.useStartTime = convertTimeFormat(form.value.useStartTime);
			form.value.useEndTime = convertTimeFormat(form.value.useEndTime);
		}

		if (form.value.giveNum == infiniteNum) {
			infiniteGiveNum.value = false;
		}

		if (form.value.useLimit == infiniteNum) {
			infiniteUseLimit.value = true;
		} else {
			infiniteUseLimit.value = false;
		}

		console.log('最终获取到的form', form.value);
	} catch (error) {
		console.log(error);
	}
	setTimeout(() => {
		uni.hideLoading();
	}, 500);
}

onLoad((options) => {
	form.value.couponType = options.couponType;
	shopInfo.value = uni.getStorageSync('shopInfo');

	if (options.id) {
		uni.setNavigationBarTitle({
			title: `编辑${getEmunListLabel('couponTypes', form.value.couponType)}`
		});
		form.value.id = options.id;
		couponDetailAjax();
	} else {
		uni.setNavigationBarTitle({
			title: `添加${getEmunListLabel('couponTypes', form.value.couponType)}`
		});
	}
});
</script>

<style>
page {
	background-color: #f7f7f7;
}
</style>
<style scoped lang="scss">
.container {
	padding: 28upx;
}
.center {
	display: flex;
	gap: 28upx;
	align-items: center;
	.ipt {
		flex: 1;
	}
}
.tips {
	font-size: 28upx;
	color: #999;
}
.column {
	display: flex;
	flex-direction: column;
	gap: 20upx;
}
</style>
