<template>
	<view class="card-add">
		<u-navbar title="卡劵管理" :border-bottom="false" :background="bgc" back-icon-color="#262B37" title-color='#262B37'
			title-size='36' height='44' id="navbar">
		</u-navbar>

		<!-- 表单内容 -->
		<view class="form-content">
			<view class="form-item">
				<text class="label">卡券名称</text>
				<input type="text" style="text-align: right;width: 100%;" v-model="formData.name" placeholder="请输入"
					placeholder-class="placeholder" />
			</view>

			<view class="form-item" @click="showTypeSelect">
				<text class="label">卡券类型</text>
				<view class="value-box">
					<text>{{kalx}}</text>
					<uni-icons type="right" size="16" color="#999"></uni-icons>
				</view>
			</view>

			<view class="form-item" v-if="kalx == '小时卡' || kalx == '次卡' || kalx == '储存卡'">
				<text class="label" v-if="kalx == '小时卡' || kalx == '次卡'">使用</text>
				<text class="label" v-if="kalx == '储存卡'">储存</text>
				<view class="value-box">
					<input type="number" v-model="formData.duration" placeholder="请输入"
						placeholder-class="placeholder" />
					<text class="unit" v-if="kalx == '小时卡'">小时</text>
					<text class="unit" v-if="kalx == '次卡'">次数</text>
					<text class="unit" v-if="kalx == '储存卡'">金额</text>
				</view>
			</view>

			<view class="form-item" @click="showStoreSelect">
				<text class="label">适用门店</text>
				<view class="value-box">
					<text>{{formData.store}}</text>
					<uni-icons type="right" size="16" color="#999"></uni-icons>
				</view>
			</view>

			<view class="form-item" style="display: block;">
				<text class="label">适用房间</text>
				<view class="value-box" style="display: block;">
					<view class="listroom" style="display: flex;flex-wrap: wrap;">
						<view v-for="(item,index) in roomlist" :key="index"
							:class="['week-item', {'actives': roomids.includes(item.roomId)}]"
							@click="btnroom(item.roomId)"
							style="border: 1px solid #ccc;padding: 10rpx 20rpx;box-sizing: border-box;margin-right: 10rpx;margin-top: 10rpx;">
							{{item.roomName}}
						</view>
					</view>
				</view>
			</view>

			<view class="form-item">
				<text class="label">购买价格（元）</text>
				<input type="digit" v-model="formData.buyPrice" placeholder="请输入" placeholder-class="placeholder" />
			</view>

			<view class="form-item" v-if="kalx == '团购劵'">
				<text class="label">抖音sku_id</text>
				<input type="digit" v-model="dyid" placeholder="请输入抖音sku_id" placeholder-class="placeholder" />
			</view>
			<!-- <view class="form-item">
        <text class="label">划线价格（元）</text>
        <input type="digit" v-model="formData.originalPrice" placeholder="请输入" placeholder-class="placeholder"/>
      </view> -->

			<!-- 有效期选择 -->
			<!-- <view class="validity-section" v-if="kalx != '团购劵'">
        <view class="validity-type">
          <text class="type-label">长期有效</text>
		  <text class="desc">自购卡后长期有效</text>
          <switch :checked="formData.isLongTerm" @change="handleValidityTypeChange"/>
        </view>
        
        <view class="validity-type">
          <text class="type-label">相对有效期</text>
		  <text class="desc">自购卡后开始，{{formData.useTimes}}天后过期</text>
          <switch :checked="formData.isRelative" @change="handleRelativeChange"/>
        </view>
      </view> -->

			<view class="form-item" v-if="kalx != '团购劵'">
				<text class="label">使用天数</text>
				<input type="number" v-model="formData.useTimes" placeholder="请输入" placeholder-class="placeholder" />
				<text class="unit">天</text>
			</view>

			<!-- 适用周天选择 -->
			<view class="week-select">
				<text class="label">适用周天</text>
				<view class="week-list">
					<view v-for="(day, index) in weekDays" :key="index"
						:class="['week-item', {'active': formData.weekDays.includes(day)}]" @click="toggleWeekDay(day)">
						{{day}}
					</view>
				</view>
			</view>

			<!-- 使用时段 -->
			<view class="time-range">
				<text class="label">适用时段</text>
				<view class="time-picker">
					<picker mode="time" :value="formData.startTime" @change="onStartTimeChange">
						<text>{{formData.startTime}}</text>
					</picker>
					<text class="separator">至</text>
					<picker mode="time" :value="formData.endTime" @change="onEndTimeChange">
						<text>{{formData.endTime}}</text>
					</picker>
				</view>
			</view>

			<view class="form-item">
				<text class="label">描述</text>
				<input type="text" style="text-align: right;width: 100%;" v-model="miaoshu" placeholder="请输入"
					placeholder-class="placeholder" />
			</view>

		</view>
		<u-select v-model="show" :list="list" @confirm="confirm"></u-select>

		<!-- 选择店铺 -->
		<u-select v-model="showshop" :list="listshop" @confirm="confirmshop"></u-select>

		<!-- 底部编辑按钮 -->
		<view class="anniu" v-if="couponId != ''">
			<view class="del" @click="btndel">
				删除
			</view>
			<view class="bj" @click="handleSave">
				编辑
			</view>
		</view>
		<!-- 底部保存按钮 -->
		<view v-else class="save-btn" @click="handleSave">保存</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				bgc: {
					backgroundColor: "#fff",
				},
				show: false,
				list: [{
						value: '1',
						label: '储存卡'
					},
					{
						value: '2',
						label: '小时卡'
					}, {
						value: '3',
						label: '团购劵'
					},
					{
						value: '4',
						label: '次卡'
					}
				],
				listshop: [],
				miaoshu: '',
				showshop: false,
				kalx: '请选择卡劵类型',
				kalxid: '',
				formData: {
					name: '',
					type: '小时卡',
					store: '请选择门店',
					buyPrice: '',
					originalPrice: '',
					duration: '',
					isLongTerm: false,
					isRelative: false,
					useTimes: '',
					weekDays: [],
					startTime: '00:00',
					endTime: '00:00',
				},
				weekDays: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
				roomlist: [],
				roomids: [],
				storeid: '',
				dyid: '',

				couponId: ''
			}
		},
		onLoad(option) {
			if (option.couponId) {
				this.couponId = option.couponId
				this.getxq()
			}
		},
		onShow() {
			this.getstorlist()
		},
		methods: {
			// 点击删除卡劵
			btndel() {
				let that = this
				uni.showModal({
					title: '提示',
					content: '您确定要删除该卡劵吗？',
					success: function(res) {
						if (res.confirm) {
							that.$u.delete(`/app/card/${that.couponId}`).then(res => {
								if (res.code == 200) {
                                    uni.navigateBack()
								} else {
									uni.showToast({
										title: res.msg,
										icon: 'none',
										duration: 2000
									})
								}
							})
						}
					}
				})
			},
			// 请求卡劵详情
			getxq() {
				this.$u.get(`/app/card/${this.couponId}`).then(res => {
					if (res.code == 200) {
						this.storeid = res.data.storeId //门店id
						this.formData.name = res.data.name //卡劵名称
						this.kalxid = res.data.type //卡劵类型
						this.$u.get(`/app/room/getRoomListByStoreId?storeId=${this.storeid}`).then(res => {
							if (res.code == 200) {
								this.roomlist = res.data
							}
						})
						this.roomids = res.data.availableRooms //房间id
						res.data.availableWeek.forEach(item => {
							if (item == 1) {
								this.formData.weekDays.push('周一')
							} else if (item == 2) {
								this.formData.weekDays.push('周二')
							} else if (item == 3) {
								this.formData.weekDays.push('周三')
							} else if (item == 4) {
								this.formData.weekDays.push('周四')
							} else if (item == 5) {
								this.formData.weekDays.push('周五')
							} else if (item == 6) {
								this.formData.weekDays.push('周六')
							} else if (item == 7) {
								this.formData.weekDays.push('周日')
							}
						})
						this.formData.startTime = res.data.availableTimeStart //适用时段开始时间
						this.formData.endTime = res.data.availableTimeEnd //适用时段结束时间
						this.miaoshu = res.data.descr //描述
						if (this.kalxid == 1) {
							this.kalx = '储存卡'
							this.formData.duration = res.data.storedAmount //储存金额
						} else if (this.kalxid == 2) {
							this.kalx = '小时卡'
							this.formData.duration = res.data.hours //可用时间小时
						} else if (this.kalxid == 4) {
							this.kalx = '次卡'
							this.formData.duration = res.data.limitNum //次数
						} else {
							this.kalx = '团购劵'
							console.log('团购')
						}
						this.formData.buyPrice = res.data.retailPrice //零售价
						this.formData.useTimes = res.data.validityValue //有效期多少天
						this.dyid = res.data.skuId //抖音sku_id
					}
				})
			},


			// 新建卡卷
			handleSave() {
				let dayarr = []
				this.formData.weekDays.forEach(item => {
					if (item == '周一') {
						dayarr.push(1)
					} else if (item == '周二') {
						dayarr.push(2)
					} else if (item == '周三') {
						dayarr.push(3)
					} else if (item == '周四') {
						dayarr.push(4)
					} else if (item == '周五') {
						dayarr.push(5)
					} else if (item == '周六') {
						dayarr.push(6)
					} else if (item == '周日') {
						dayarr.push(7)
					}
				})
				console.log(dayarr);
				let storedAmount = ''
				let availableTime = ''
				let limitNum = ''
				if (this.kalx == '储存卡') {
					storedAmount = this.formData.duration
				} else if (this.kalx == '小时卡') {
					availableTime = this.formData.duration
				} else if (this.kalx == '次卡') {
					limitNum = this.formData.duration
				} else {
					console.log('团购');
				}
				let data = {
					name: this.formData.name, //卡劵名称
					type: this.kalxid, //卡劵类型
					storeId: this.storeid, //门店id
					availableRooms: this.roomids, //房间id
					availableWeek: dayarr, //星期
					availableTimeStart: this.formData.startTime, //适用时段开始时间
					availableTimeEnd: this.formData.endTime, //适用时段结束时间
					descr: this.miaoshu, //描述
					storedAmount: storedAmount, //储存金额
					hours: availableTime, //可用时间小时
					limitNum: limitNum, //次数
					retailPrice: this.formData.buyPrice, //零售价
					validityValue: this.formData.useTimes, //有效期多少天
					validityUnit: 'day', //有效期单位
					skuId: this.dyid ,//抖音sku_id
					couponId:this.couponId
				}
				if(this.couponId == ''){
					this.$u.post(`/app/card`, data).then(res => {
						if (res.code == 200) {
							uni.navigateBack()
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none',
								duration: 2000
							})
						}
					})
				}else{
					this.$u.put(`/app/card`, data).then(res => {
						if (res.code == 200) {
							uni.showToast({
								title: '修改成功',
								icon: 'success',
								duration: 2000
							})
							setTimeout(()=>{
								uni.navigateBack()
							},1000)
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none',
								duration: 2000
							})
						}
					})
				}
			},
			// 获取本人门店
			getstorlist() {
				this.$u.get(`/app/store/list`).then(res => {
					if (res.code == 200) {
						this.listshop = res.rows.map(item => ({
							label: item.name,
							value: item.storeId
						}))
						if (this.couponId != '') {
							this.listshop.forEach(item => {
								if (item.value == this.storeid) {
									this.formData.store = item.label
								}
							})
						}
					}
				})
			},
			// 点击选择房间
			btnroom(id) {
				const index = this.roomids.indexOf(id)
				if (index > -1) {
					this.roomids.splice(index, 1)
				} else {
					this.roomids.push(id)
				}
				console.log("当前选中的ID:", this.roomids)
			},
			// 选择卡劵类型
			confirm(e) {
				this.kalx = e[0].label
				this.kalxid = e[0].value
			},
			// /选择店铺
			confirmshop(e) {
				this.formData.store = e[0].label
				this.storeid = e[0].value
				this.$u.get(`/app/room/getRoomListByStoreId?storeId=${e[0].value}`).then(res => {
					if (res.code == 200) {
						this.roomlist = res.data
					}
				})
			},
			showTypeSelect() {
				// 显示卡券类型选择
				this.show = true
			},
			showStoreSelect(e) {
				// 显示门店选择
				this.showshop = true
			},
			handleValidityTypeChange(e) {
				this.formData.isLongTerm = e.detail.value
				this.formData.isRelative = false
			},
			handleRelativeChange(e) {
				this.formData.isRelative = e.detail.value
				this.formData.isLongTerm = false
			},
			toggleWeekDay(day) {
				const index = this.formData.weekDays.indexOf(day)
				if (index > -1) {
					this.formData.weekDays.splice(index, 1)
				} else {
					this.formData.weekDays.push(day)
				}
				console.log(this.formData.weekDays);
			},
			onStartTimeChange(e) {
				this.formData.startTime = e.detail.value
			},
			onEndTimeChange(e) {
				this.formData.endTime = e.detail.value
			},
			showDeductSelect() {
				// 显示抵扣选择
			},
		}
	}
</script>

<style lang="scss" scoped>
	.actives {
		background-color: #4CAF50;
		color: #fff;
		border-color: #4CAF50;
	}

	.anniu {
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100%;
		height: 180rpx;
		display: flex;
		justify-content: space-between;
		padding: 0 30rpx;
		box-sizing: border-box;
		background-color: #fff;
		padding-top: 50rpx;
		box-sizing: border-box;
		z-index: 9;

		.del {
			width: 46%;
			border-radius: 20rpx;
			height: 90rpx;
			line-height: 90rpx;
			color: #fff;
			font-size: 32rpx;
			background-color: red;
			text-align: center;
		}

		.bj {
			width: 46%;
			border-radius: 20rpx;
			height: 90rpx;
			line-height: 90rpx;
			color: #fff;
			font-size: 32rpx;
			background-color: #4CAF50;
			text-align: center;
		}
	}

	.card-add {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding-bottom: 140rpx;
		box-sizing: border-box;

		.nav-header {
			display: flex;
			align-items: center;
			height: 44px;
			padding: 0 15px;
			background-color: #fff;
			border-bottom: 1px solid #eee;

			.title {
				flex: 1;
				text-align: center;
				font-size: 16px;
				color: #333;
			}
		}

		.form-content {
			padding: 15px;

			.form-item {
				display: flex;
				align-items: center;
				padding: 15px;
				background-color: #fff;
				border-radius: 4px;
				margin-bottom: 10px;

				.label {
					width: 120px;
					color: #333;
					font-size: 14px;
				}

				.value-box {
					flex: 1;
					display: flex;
					align-items: center;
					justify-content: flex-end;

					input {
						text-align: right;
					}

					.unit {
						margin-left: 5px;
						color: #999;
					}
				}
			}
		}

		.validity-section {
			background-color: #fff;
			padding: 15px;
			border-radius: 4px;
			margin-bottom: 10px;

			.validity-type {
				display: flex;
				align-items: center;
				margin-bottom: 10px;
				justify-content: space-between;

				.type-label {
					width: 100px;
					font-size: 14px;
					color: #333;
				}

				.desc {
					margin-left: 10px;
					font-size: 12px;
					color: #999;
				}
			}
		}

		.week-select {
			background-color: #fff;
			padding: 15px;
			border-radius: 4px;
			margin-bottom: 10px;

			.label {
				font-size: 14px;
				color: #333;
				margin-bottom: 10px;
			}

			.week-list {
				display: flex;
				flex-wrap: wrap;
				margin-top: 20rpx;

				.week-item {
					width: 60px;
					height: 30px;
					line-height: 30px;
					text-align: center;
					border: 1px solid #ddd;
					border-radius: 4px;
					margin-right: 10px;
					margin-bottom: 10px;
					font-size: 14px;
					color: #666;

					&.active {
						background-color: #4CAF50;
						color: #fff;
						border-color: #4CAF50;
					}
				}
			}
		}

		.time-range {
			background-color: #fff;
			padding: 15px;
			border-radius: 4px;
			margin-bottom: 10px;

			.label {
				font-size: 14px;
				color: #333;
				margin-bottom: 10px;
			}

			.time-picker {
				display: flex;
				align-items: center;
				justify-content: space-between;

				.separator {
					margin: 0 10px;
					color: #999;
				}
			}
		}

		.save-btn {
			position: fixed;
			left: 15px;
			right: 15px;
			bottom: 20px;
			height: 44px;
			line-height: 44px;
			text-align: center;
			background-color: #4CAF50;
			color: #fff;
			border-radius: 22px;
			font-size: 16px;
		}
	}

	.placeholder {
		color: #999;
	}
</style>