<template>
	<view class="box">
		<view class="bg-fff container u-flex u-m-b-32 top">
			<image style="width: 60rpx; height: 60rpx" src="/pageMarket/static/images/cost.png"></image>
			<view class="u-flex-1 u-flex u-p-l-24">
				<view class="u-font-28 u-flex-1 u-p-r-4">
					<view class="color-333 font-bold">消费返现</view>
					<view class="color-666 u-m-t-4 u-font-24">用户下单后返现一定的金额到余额，可促进复购</view>
				</view>
				<up-switch v-model="form.isEnable" :disabled="isMainShop() ? false : true" size="18" :active-value="1" :inactive-value="0"></up-switch>
			</view>
		</view>
		<view class="u-m-t-32 container">
			<view class="u-flex u-row-between u-m-b-16">
				<text class="font-bold color-333">可用门店</text>
			</view>
			<my-shop-select v-model:selShops="form.shopIdList" v-model:useType="form.useType"></my-shop-select>
		</view>

		<view class="u-m-t-32 container">
			<view class="u-flex u-row-between">
				<text class="font-bold color-333 u-m-b-16">适用用户</text>
			</view>
			<userTypes v-model="form.applicableUser"></userTypes>
		</view>

		<view class="u-m-t-32 container">
			<view class="u-flex u-row-between">
				<text class="font-bold color-333">返现类型</text>
			</view>
			<view class="u-m-t-16">
				<up-radio-group v-model="form.cashbackType" placement="row">
					<up-radio v-for="item in cashbackTypes" :key="item.value" :name="item.value" :label="item.label">
						<template #label>
							<text>
								{{ item.label }}
							</text>
						</template>
					</up-radio>
				</up-radio-group>
			</view>
			<view class="u-flex u-row-between u-m-t-32">
				<text class="font-bold color-333">阶梯设置</text>
			</view>
			<view class="u-m-t-32 u-flex u-row-between gap-40" v-for="(item, index) in form.cashbackStepList" :key="index">
				<view class="u-flex u-col-top">
					<view class="no-wrap u-m-r-16 u-m-t-14">{{ returnName(index) }}</view>
					<view class="u-flex-1">
						<view class="u-flex">
							<text class="u-m-r-24">返现门槛</text>
							<input class="my-input" type="digit" v-model="item.amount" placeholder="" />
							<text class="text-tips text-tips1">元</text>
						</view>
						<view class="u-flex u-m-t-24">
							<text class="u-m-r-24">{{ form.cashbackType === 'percentage' ? '返现比例' : '返现金额' }}</text>
							<input
								class="my-input"
								type="number"
								v-model="item.cashbackAmount"
								@blur="inputBlur($event, index)"
								:max="form.cashbackType === 'percentage' ? 100 : 999999"
								placeholder=""
							/>
							<text class="text-tips text-tips1">{{ returnUnit }}</text>
							<text class="color-red u-m-l-10" @click="deleteThreshold(index)">删除</text>
						</view>
					</view>
				</view>
			</view>

			<button class="add u-m-t-32" @click="addcashbackStepList">添加</button>
		</view>
		<my-bottom-btn-group @save="save" isOpenPermission @cancel="cancel"></my-bottom-btn-group>
	</view>
</template>

<script setup>
import { reactive, computed, onMounted } from 'vue';
import userTypes from './user-types.vue';
import * as consumeCashbackApi from '@/http/api/market/consumeCashback.js';
import { isMainShop } from '@/store/account';
import { onLoad, onReady, onShow, onPageScroll, onReachBottom, onBackPress } from '@dcloudio/uni-app';

//返现类型
const cashbackTypes = [
	{
		value: 'percentage',
		label: '按比例返现'
	},
	{
		value: 'fix',
		label: '固定金额'
	}
];
const form = reactive({
	isEnable: 0,
	cashbackStepList: [],
	shopIdList: [],
	useType: 'all',
	applicableUser: 'all',
	cashbackType: 'percentage'
});
function addcashbackStepList() {
	form.cashbackStepList.push({
		amount: 0,
		cashbackAmount: 0
	});
}

function inputBlur(e, index) {
	const value = e.detail.value;
	if (form.cashbackType === 'percentage') {
		if (e.detail.value >= 100) {
			form.cashbackStepList[index].cashbackAmount = 100;
		} else if (e.detail.value < 0) {
			form.cashbackStepList[index].cashbackAmount = 0;
		} else {
			form.cashbackStepList[index].cashbackAmount = e.detail.value;
		}
	} else {
		if (e.detail.value < 0) {
			form.cashbackStepList[index].cashbackAmount = 0;
		} else if (e.detail.value > form.cashbackStepList[index].amount) {
			form.cashbackStepList[index].cashbackAmount = form.cashbackStepList[index].amount;
		} else {
			form.cashbackStepList[index].cashbackAmount = e.detail.value;
		}
	}
}

async function save() {
	console.log(form);
	const submitData = {
		...form
	};
	const res = await consumeCashbackApi.update(submitData);
	uni.showToast({
		title: '更新成功',
		icon: 'none',
		duration: 2000,
		success: function () {}
	});
}
function cancel() {
	uni.navigateBack();
}

function deleteThreshold(index) {
	form.cashbackStepList.splice(index, 1);
}
function setForm(data) {
	data.cashbackStepList = data.cashbackStepList || [];
	Object.assign(form, data);
	console.log(form);
}
const returnUnit = computed(() => {
	return form.cashbackType === 'percentage' ? '%' : '元';
});

const numChineseMap = {
	0: '零',
	1: '一',
	2: '二',
	3: '三',
	4: '四',
	5: '五',
	6: '六',
	7: '七',
	8: '八',
	9: '九',
	10: '十',
	100: '百',
	1000: '千'
};

// 辅助函数：将数字转换为中文数字
function numberToChinese(n) {
	if (n < 10) {
		return numChineseMap[n];
	}

	// 处理10-99
	if (n < 100) {
		const ten = Math.floor(n / 10);
		const unit = n % 10;
		if (ten === 1) {
			return unit === 0 ? '十' : `十${numChineseMap[unit]}`;
		} else {
			return unit === 0 ? `${numChineseMap[ten]}十` : `${numChineseMap[ten]}十${numChineseMap[unit]}`;
		}
	}

	// 处理100-999
	if (n < 1000) {
		const hundred = Math.floor(n / 100);
		const remainder = n % 100;
		if (remainder === 0) {
			return `${numChineseMap[hundred]}百`;
		} else {
			return `${numChineseMap[hundred]}百${remainder < 10 ? '零' : ''}${numberToChinese(remainder)}`;
		}
	}

	// 处理1000-9999
	if (n < 10000) {
		const thousand = Math.floor(n / 1000);
		const remainder = n % 1000;
		if (remainder === 0) {
			return `${numChineseMap[thousand]}千`;
		} else {
			return `${numChineseMap[thousand]}千${remainder < 100 ? '零' : ''}${numberToChinese(remainder)}`;
		}
	}

	// 更大的数字可以继续扩展（如万、亿等），这里以千为单位示例
	return n.toString(); // 超过范围时返回数字本身（可根据需求扩展）
}

// 主函数：根据索引返回对应的组名
function returnName(index) {
	const groupNumber = index + 1; // 索引从0开始，组号从1开始
	const chineseNumber = numberToChinese(groupNumber);
	return `第${chineseNumber}组`;
}

const emits = defineEmits(['get']);
async function getData() {
	const res = await consumeCashbackApi.getConfig();
	emits('get', res);
	if (res) {
		setForm(res);
	}
}
onMounted(() => {
	getData();
});
</script>

<style lang="scss" scoped>
page {
	background: #f7f7f7;
}
.x-padding {
	padding: 0 24rpx;
}
.text-tips {
	color: #999999;
	font-size: 14px;
	padding: 0 28rpx;
	border-radius: 6rpx 0 0 6rpx;
	border: 2rpx solid #d9d9d9;
	background-color: #f7f7fa;
	line-height: 60rpx;
}
.text-tips1 {
	border-radius: 0 6rpx 6rpx 0;
}
.gap-40 {
	gap: 40rpx;
}
.my-input {
	border: 2rpx solid #d9d9d9;
	height: 60rpx;
	border-right: none;
	width: 240rpx;
	text-align: center;
	padding: 0 2px;
	font-size: 14px;
}
.box {
	padding: 0 28rpx;
	font-size: 28rpx;
}
.container {
	background: #fff;
	padding: 32rpx 24rpx;
	margin-top: 32rpx;
	border-radius: 16rpx;
	overflow: hidden;
}
.add {
	padding: 8rpx 32rpx;
	border-radius: 12rpx;
	background: #318afe;
	color: #ffffff;
	font-size: 28rpx;
	line-height: 56rpx;
	margin: 0;
}
.color-red {
	color: #ff2f2f;
}
</style>
