<template>
	<view class="content">
		<header-title :title="'小游戏'+$test.$test"></header-title>


		<view class="main">

			<!-- <form @submit="Submit" data-type='2' > -->

			<view class="box-pack-between ft32 item flex-y-center">
				<text class="item_name">小游戏类型<text style="color:red">*</text></text>
				<picker class="ft30" :range="game_list" range-key="name" @change="bindGame">
					<view class="flex-y-center">
						<view v-if="game_index<=-1">{{game_name}}</view>
						<view v-else>{{game_list[game_index].name}}</view>
						<text class="iconfont icon-prev"></text>
					</view>
				</picker>
			</view>

			<view>
				<view class="box-pack-between ft32 item">
					<text>奖品设置</text>
					<view class="add-home flex-center ft24" @click="open">
						添加
					</view>
				</view>
				<view class="item-bg" v-if="prize.length>0">
					<view class="box-pack-between mar64 flex-y-center" v-for="(item,index) of prize" :key='index'>
						<view class="flex-y-center flex-grow-1 pdr-20">
							<text style="margin-right: 10rpx;">{{item.name}}/<text
									class="col-num">{{item.num}}张</text>/<text class="col-num">
									{{item.probability}}%</text></text>
						</view>
						<image class="item-del" @click="delprize" :data-index='index' src="../../static/images/del.png"
							mode=""></image>
					</view>
				</view>
			</view>

			<view>
				<view class="box-pack-between ft32 item">
					<text>抽奖次数</text>
					<view class="flex-center ft24">
						<input type="number" @input="bindgamenum" :value="info.game_num" placeholder="请填写抽奖次数(正整数)"
							name="game_num" />
					</view>
				</view>
			</view>

			<view>
				<view class="box-pack-between ft32 item">
					<text>{{$test.$test}}场景</text>
					<view class="add-home flex-center ft24">
						<picker @change="bindPickerChange" :range-key="'name'" :range="allwayList">
							添加
						</picker>
					</view>
				</view>
				<view class="item-bg" v-if="arr.length>0">
					<view class="box-pack-between mar64 flex-y-center" v-for="(item,index) of arr" :key='index'>
						<view class="flex-y-center flex-grow-1 pdr-20">
							<text style="margin-right: 10rpx;">{{item.name}}</text>
							<input class="flex-grow-1" type="text" @input="getScene" :data-index="index"
								placeholder="请填写链接或内容" :value="item.way_power" maxlength="5000" />
						</view>
						<image class="item-del" @click="delScene" :data-index='index' src="../../static/images/del.png"
							mode=""></image>
					</view>

				</view>
			</view>

			<view>
				<view class="box-pack-between ft32 item">
					<text>配置微信文章分享</text>
					<view class="flex-center ft24">
						<switch name="wx_state" :checked="wx_state==1?true:false" @change="switch2"
							style="transform:scale(0.7)" />
					</view>
				</view>

				<view class="item-bg" v-if="wx_state==1">
					<view class="box-pack-between mgr57">
						<view class="flex-row">
							<text class="item-bg-32">分享标题</text>
							<input @input="bindwxtitle" type="text" name="wx_title" placeholder="请填写分享标题"
								:value="info.wx_title" />
						</view>
					</view>
					<view class=" flex-row mgr57">
						<text class="item-bg-32">分享描述</text>
						<input @input="bindwxdesc" type="text" name="wx_desc" placeholder="请填写分享描述"
							:value="info.wx_desc" />
					</view>
					<view class="box-pack-between flex-y-center">
						<text class="item-bg-32">分享图标</text>
						<image v-if="wx_img" @click="ChooseImage" :data-type="2" class="upimg" :src="URL+wx_img"
							mode="">
						</image>
						<image v-else @click="ChooseImage" :data-type="2" class="upimg"
							src="../../static/images/upimg.png" mode="">
						</image>
					</view>
				</view>
			</view>
			<view class="box-pack-between ft32  descp ">
				<textarea :value='rule' @input="bindrule" placeholder-class="desc-placeholder" maxlength="200"
					placeholder="抽奖规则说明" name='description' />
			</view>

			<view class="hg200rpx">
			</view>

			<view class="bottom-bar">
				<block v-if="card_num">
					<button @click="getCode" type="2" class="btn2 flex-center">
						确定修改
					</button>
				</block>
				<block v-else>
					<button @click="bangCode" data-type="1" class="btn1 flex-center">
						绑定二维码
					</button>
					<button @click="getCode" data-type='2' form-type="submit" class="btn2 flex-center">
						生成二维码
					</button>
				</block>
			</view>
			<!-- </form> -->
		</view>

		<zx-uni-popup ref="popup" type="center">
			<view class="games-model">
				<form @submit="sure">
					<view class="title">
						设置奖品
					</view>
					<view class="flex-y-center item" @click="bindCoupon">
						<view style="min-width: 100rpx;">奖品<text class="red">*</text></view>
						<view class="flex-y-center box-pack-between flex-grow-1 ft28">
							<text></text>
							<view class="flex-y-center">
								<text>{{coupon_title}}</text>
								<text class="iconfont icon-prev"></text>
							</view>
						</view>
					</view>

					<view class="flex-y-center item">
						<view style="min-width: 100rpx;">数量<text class="red">*</text></view>
						<view class="border-b flex-grow-1">
							<input name="num" :value="num" type="number" value="" placeholder="输入抽奖次数(正整数)"/>
						</view>
					</view>

					<view class="flex-y-center item">
						<text style="min-width: 100rpx;"> 概率<text class="red">*</text></text>
						<view class="border-b flex-grow-1">
							<input name="probability" :value="probability" type="digit" value="" placeholder="输入抽奖概率"/>
						</view>
						<text>%</text>
					</view>
					<text class="ft20 red">*中奖概率封顶为100%，单个奖品占比概率设置，例：20%+30%+50%,</text>
					<button class="btn flex-center" form-type="submit">确定</button>
				</form>

			</view>
		</zx-uni-popup>

	</view>
</template>

<script>
	import headerTitle from '@/components/header/header-title.vue';
	import zxUniPopup from '@/components/zx-uni-popup/uni-popup.vue'
	export default {
		components: {
			headerTitle,
			zxUniPopup,
		},
		data() {
			return {
				$test: this.$test.$test,
				game_list: [
					// "抽奖", "砸金蛋",
				],
				game_index: -1,
				game_name: "请选择小游戏类型",
				arr: [],
				allwayList: [],
				coupon_title: "",
				probability: "",
				num: "",
				prize: [],
				info: {},
				wx_state: 1,
				wx_img: "",
				URL: getApp().globalData.URL,
				card_num: "",
				result: "",
				id: "",
				rule: "",
				game_id: "",
			}
		},

		onLoad(e) {
			this.card_num = e.card_num;
			if (!this.card_num) {
				// this.allmuban();
			}
			this.gameList();
		},

		onShow() {
			uni.$on("handleFun", res => {
				console.log(res, "res")
				this.coupon_title = res.title;
				this.coupon_id = res.coupon_id;
				this.num = res.num;
				// 清除监听
				uni.$off('handleFun');
			})
		},

		methods: {
			bindgamenum(e) {
				this.game_num = e.detail.value;
			},

			bindwxtitle(e) {
				this.wx_title = e.detail.value;
			},
			bindwxdesc(e) {
				this.wx_desc = e.detail.value;
			},
			bindrule(e) {
				this.rule = e.detail.value;
			},
			switch2(e) {
				this.wx_state = e.target.value ? 1 : 0;
			},

			// 编辑修改返回的内容
			gameList() {
				this.request({
					url: "Youxifuneng/gameList",
					data: {},
				}).then(res => {
					console.log(res, "res")
					if (res.code === '200') {
						this.game_list = res.data;
						this.allways();
					}
				}).catch((res) => {});
			},

			open() {
				if (this.prize.length > 8) {
					uni.showToast({
						title: "奖品已超限制长度",
						icon: 'none'
					})
					return
				}
				this.$refs.popup.open();
			},

			sure(e) {

				let num = e.detail.value.num;

				if (!this.coupon_title || !num || !e.detail.value.probability) {
					uni.showToast({
						title: "必选项不能为空",
						icon: 'none'
					})
					return
				}


				if (e.detail.value.probability > 100) {
					uni.showToast({
						title: "概率不能大于100",
						icon: 'none'
					})
					return
				}

				if (e.detail.value.num > Number(this.num)) {
					uni.showToast({
						title: "数量不能大于优惠劵数量",
						icon: 'none'
					})
					return
				}
				let sum = this.prize.reduce((acc, curVal) => acc + Number(curVal.probability), 0);
				if ((sum + Number(e.detail.value.probability)) > 100) {
					uni.showToast({
						title: "奖品合计概率不能超过100%",
						icon: 'none'
					})
					return
				}
				if (this.prize.length > 0) {
					let hasGoodStudentType = this.prize.some((v, i) => v.coupon_id == this.coupon_id)
					console.log(hasGoodStudentType); // true
					if (hasGoodStudentType) {
						uni.showToast({
							title: "已有此优惠劵",
							icon: 'none'
						})
						return
					}
				}

				this.prize.push({
					coupon_id: this.coupon_id,
					name: this.coupon_title,
					num: e.detail.value.num,
					probability: e.detail.value.probability,
				})

				this.probability = "";
				this.num = "";
				this.coupon_title = ""
				this.$refs.popup.close();
			},

			ChooseImage(e) {
				let type = e.currentTarget.dataset.type;
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						console.log(res)
						var tempFilesSize = res.tempFiles[0].size; //获取图片的大小，单位B
						if (type == 2 && tempFilesSize > 1000000) { //图片小于或者等于2M时 可以执行获取图片
							uni.showToast({
								title: '上传图片不能大于1M!', //标题
								icon: 'none' //图标 none不使用图标，详情看官方文档
							})
							return
						}
						var path;
						// #ifdef MP-WEIXIN
						path = res.tempFiles[0].path;
						// #endif
						// #ifdef H5
						path = res.tempFiles[0].name;
						// #endif
						var formatImage = path.split(".")[(path.split(".")).length - 1];
						if (formatImage != "png" && formatImage != "jpg" && formatImage != "jpeg") {
							uni.showToast({
								title: '只能上传png、jpg、jpeg格式',
								icon: 'none',
								duration: 2000,
								mask: true,
							})
							return
						}
						res.tempFilePaths.forEach((v, i) => {
							this.Upload({
								url: "Spread/upload_img",
								data: {
									url: v,
									type: 0,
									token: uni.getStorageSync("token"),
								}
							}).then(res => {
								console.log(res, "res")
								type == 1 ? (
									this.mid_img = res.file,
									this.url = res.url
								) : (
									this.wx_img = res.file
								)
							}).catch(err => {
								uni.showToast({
									title: err.message,
									icon: 'none'
								})
							});
						})
					},
				});
			},

			delprize(e) {
				var index = e.currentTarget.dataset.index;
				this.prize.splice(index, 1)
			},

			bindCoupon() {
				uni.navigateTo({
					url: "./CouponList"
				})
			},

			bindGame(e) {
				console.log(e.detail.value, "e.detail.value")
				this.game_index = e.detail.value;
				this.game_id = this.game_list[e.detail.value].id;
			},

			getScene(e) {
				var index = e.currentTarget.dataset.index;
				this.arr[index].way_power = e.detail.value
			},

			delScene(e) {
				var index = e.currentTarget.dataset.index;
				this.arr.splice(index, 1);
			},

			bindPickerChange(e) {
				if (this.arr.length > 0) {
					for (let i of this.arr) {
						if (i.id == this.allwayList[e.target.value].id) {
							uni.showToast({
								title: "场景重复",
								icon: 'none'
							})
							return
						}
					}
				}
				this.arr.push({
					id: this.allwayList[e.target.value].id,
					name: this.allwayList[e.target.value].name,
					super_id: this.allwayList[e.target.value].super_id,
				});
			},

			// 编辑修改返回的内容
			allways() {
				this.request({
					url: "funeng/allways",
					data: {},
				}).then(res => {
					console.log(res, "res")
					if (res.code === '200') {
						this.allwayList = res.data;

						this.arr.push({
							id: res.data[0].id,
							name: res.data[0].name,
							super_id: res.data[0].super_id,
						});

						if (this.card_num) {
							this.edit_detail();
						}
					}
				}).catch((res) => {});
			},

			edit_detail(e) {
				this.request({
					url: "funeng/edit_detail",
					data: {
						card_num: this.card_num,
					},
				}).then(res => {
					console.log(res, "res")
					if (res.code === '200') {
						this.info = res.data;
						this.arr = res.data.funeng;
						this.wx_state = res.data.wx_state;
						this.wx_img = res.data.wx_img;
						this.prize = res.data.prize;
						this.game_index = this.game_list.findIndex(item => item.id === res.data.game);
						this.id = res.data.id;
						this.game_id = res.data.game;
						this.rule = res.data.rule;

					}
				}).catch((res) => {});
			},

			bangCode(e) {
				console.log(e, "bangCode")
				// #ifdef MP-WEIXIN
				uni.scanCode({
					success: (res) => {
						console.log('条码类型：' + res.scanType);
						console.log('条码内容：' + res.result);
						var params = (() => {
							var search = res.result; //获取location的search属性，保存在search中          
							var params = {}; //创建空对象params
							if (search != "") { //如果search不是空字符串
								search.slice(1).split("?")
									.forEach( //?username=zhangdong&pwd=123456;//search去开头?，按&切割为数组，forEach
										function(val) {
											var arr = val.split("="); //将当前元素值按=切割，保存在arr中
											params[arr[0]] = arr[
												1]; //向params中添加一个元素,属性名为arr[0],值为arr[1]
										}
									);
							}
							return params; //返回params
						})();
						this.result = params.card_num;
						this.Submit(1)
					}
				});
				// #endif
				// #ifdef H5
				getWXSign().then(res => {
					console.log('wx_getLocation');
					this.$wx.scanQRCode({
						needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
						scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
						success: (res) => {
							console.log(res, "qrCode")
							// this.result = res.resultStr;
							var params = (() => {
								var search = res
									.resultStr; //获取location的search属性，保存在search中          
								var params = {}; //创建空对象params
								if (search != "") { //如果search不是空字符串
									search.slice(1).split("?")
										.forEach( //?username=zhangdong&pwd=123456;//search去开头?，按&切割为数组，forEach
											function(val) {
												var arr = val.split("="); //将当前元素值按=切割，保存在arr中
												params[arr[0]] = arr[
													1]; //向params中添加一个元素,属性名为arr[0],值为arr[1]
											}
										);
								}
								return params; //返回params
							})();
							this.result = params.card_num;
							this.Submit(1)
						}
					})
				})
				// #endif
			},

			getCode() {
				this.Submit(2);
			},

			Submit(save_type) {
				let arr = this.arr,
					url,
					way_id = [],
					way_power = [];
				for (let i of arr) {
					way_id.push(i.id);
					way_power.push(i.way_power)
				}
				if (way_id.length <= 0) {
					uni.showToast({
						title: "场景为空",
						icon: 'none'
					})
					return
				}
				var prized = [];

				for (let i of this.prize) {
					prized.push({
						coupon_id: i.coupon_id,
						name: i.name,
						num: i.num,
						probability: i.probability,
					})
				}

				if (this.game_num <= 0) {
					uni.showToast({
						title: "次数不能为空",
						icon: 'none'
					})
					return
				}

				if (!this.game_id) {
					uni.showToast({
						title: "请选择游戏类型",
						icon: 'none'
					})
					return
				}
				if (prized.length <= 0) {
					uni.showToast({
						title: "请设置游戏奖品",
						icon: 'none'
					})
					return
				}
				let data = {
					token: uni.getStorageSync("token"),
					way_id: way_id.join(","),
					prize: JSON.stringify(prized),
					way_power: way_power.join(","),
					game: this.game_id,
					wx_state: this.wx_state == 1 ? 1 : 2,
					wx_title: this.wx_state == 1 ? this.wx_title : "",
					wx_desc: this.wx_state == 1 ? this.wx_desc : "",
					wx_img: this.wx_state == 1 ? this.wx_img : "",
					type: 7,
					moshi: 1,
					game_num: this.game_num,
					save_type,
					qrcode: this.result,
					rule: this.rule,
				}
				this.card_num ? (data.id = this.id, url = "Youxifuneng/youxiEdit") : url = "Youxifuneng/youxi";
				this.request({
					url,
					data,
				}).then(res => {
					console.log(res, "res")
					if (res.code === '200') {
						this.card_num ? (
							uni.showToast({
								title: "设置成功",
								icon: 'none'
							}),
							setTimeout(() => {
								uni.navigateBack({
									delta: 1
								})
							}, 2e3)
						) : (
							uni.showToast({
								title: "生成成功",
								icon: 'none'
							}),
							uni.redirectTo({
								url: "code?type=7" + '&card_num=' + res.data.card_num
							})
						)
					}
				}).catch((res) => {
					uni.showToast({
						title: res.message,
						icon: 'none'
					})
				});
			}


		},
	}
</script>

<style lang="scss">
	.col-num {
		color: #007AFF;
	}

	.item_name {
		-webkit-box-flex: 0;
		-webkit-flex: none;
		flex: none;
		width: 176rpx;
	}

	.content {
		word-wrap: break-word;
		word-break: break-all;
	}

	.pdr-20 {
		padding-right: 20rpx;
	}

	.item {
		padding: 32rpx 40rpx;
	}

	.item input {
		text-align: right;
	}

	.upimg {
		width: 126rpx;
		height: 126rpx;
	}

	.add-home {
		color: #FFFFFF;
		width: 126rpx;
		height: 54rpx;
		background: linear-gradient(315deg, #3387ff 2%, #569bff 99%);
		border-radius: 8rpx;
		box-shadow: 0px 0px 8rpx 0px rgba(51, 135, 255, 0.2);
	}

	.item-bg {
		width: 670rpx;
		/* height: 298rpx; */
		background: #f6f8fe;
		border-radius: 12rpx;
		margin: 0 auto;
		font-size: 28rpx;
		font-family: PingFang SC, PingFang SC-Regular;
		font-weight: 400;
		color: #333333;
		padding: 36rpx 32rpx;

	}

	.item-del {
		width: 40rpx;
		height: 40rpx;
		min-width: 40rpx;
	}

	.item-bg-32 {
		margin-right: 32rpx;
	}

	.mgr57 {
		margin-bottom: 57rpx;
	}

	.hg200rpx {
		height: 100rpx;
	}

	.mar64 {
		margin-bottom: 64rpx;
	}

	.item-bg .mar64:last-child {
		margin-bottom: 0rpx;
	}

	.look-icon {
		width: 200rpx;
		height: 300rpx;
		display: block;
	}

	.por {
		position: relative;
	}

	.look-icon-left {
		font-size: 26rpx;
		text-align: center;
	}

	.look-icon-right {
		font-size: 26rpx;
		margin-left: 20rpx;
		text-align: center;
	}

	.mr-top24 {
		margin-top: 24rpx;
		color: #999;
	}

	.look-jiao {
		width: 50rpx;
		height: 50rpx;
		position: absolute;
		bottom: 0;
		right: 0;
	}

	.games-model {
		background: #FFFFFF;
		width: 500rpx;
		padding: 0rpx 40rpx 40rpx 40rpx;
		border-radius: 12rpx;

		.title {
			text-align: center;
			padding: 20rpx 0;
		}

		.item {
			padding: 20rpx 0;

			.border-b input {
				margin-left: 10rpx;
				text-align: center;
			}
		}

		.red {
			color: red;
		}

		.btn {
			margin: 0 auto;
			color: #FFFFFF;
			width: 250rpx;
			height: 60rpx;
			background: linear-gradient(315deg, #3387ff 2%, #569bff 99%);
			border-radius: 8rpx;
			box-shadow: 0px 0px 8rpx 0px rgba(51, 135, 255, 0.2);
			margin-top: 30rpx;
		}
	}
</style>
