<template>
	<u-popup mode="bottom" :border-radius="borderRadius" :popup="false" v-model="value" :maskCloseAble="maskCloseAble"
	 length="auto" :safeAreaInsetBottom="true" @close="popupClose" :z-index="9999" close-icon="close">
		<view class="goodsku">
			<view class="goods">
				<image :src="goodimage" class="img" @click="previewImage(0,goodimage)"></image>
				<view class="chosen-info">
					<view class="price" :style="{ color: mc }">
						<text class="small">￥</text>
						<text>{{ goodprice }}</text>
					</view>
					<view class="amount">{{g.form_id ==1?'余位':'库存'}}  {{ goodamount }} {{ g.unit }}</view>
					<view class="sku">{{ skuObj ? '已选择' : '选择' }} {{ sku }}</view>
					<view class="sku_close">
						<u-icon name="cross" color="#9F9F9F" @click="cloGood()" size="40" />
					</view>
				</view>
			</view>
			<scroll-view scroll-y class="sku-box">
				<view class="sku-item" v-for="(x, i) in g.attr_groups" :key="i">
					<view class="sku-title">{{ x.attr_group_name }}</view>
					<view>
						<view class="sku-chi" :style="{
								background: y.attr_id == x.checkId ? mc : '#eee',
								color: y.attr_id == x.checkId ? '#FFF' : '#333'
							}"
						 :class="{ disable: notStockGood.indexOf(y.attr_id) != -1 }" v-for="(y, yi) in x.attr_list" :key="yi" @click="clickSkuItemHandler(yi, i)">
							<image :src="y.pic_url" class="img" v-if="i == 0 && y.pic_url"></image>
							<text class="val">{{ y.attr_name }}</text>
						</view>
					</view>
				</view>
			</scroll-view>
			<view class="count-box">
				<text class="label">购买数量</text>
				<u-number-box :disabled="!skuObj" v-model="gc" :min="1" :max="goodamount" @change="valChange"></u-number-box>
			</view>
			<view class="btn-box" v-if="g.totalStock>0&& g.status==1 && (g.form_id == -1 || g.form_id ==0)">
				<view style="flex: 1;" v-if="optionType != 1">
					<u-button @click="joinCar" :ripple="true" :hair-line="false" :custom-style="btn1">加入购物车</u-button>
				</view>
				<view style="flex: 1;" v-if="optionType != 0">
					<u-button @click="buy" :ripple="true" :hair-line="false" :custom-style="btn2">立即购买</u-button>
				</view>
			</view>
			<view class="btn-box" v-if="g.totalStock>0&& g.status==1 && g.form_id ==1">
				<view style="flex: 1;">
					<u-button :ripple="true" :hair-line="false" :custom-style="btn4" @click='signup'>立即报名5</u-button>
				</view>
			</view>
			<view class="btn-box" v-if="g.totalStock==0">
				<view style="flex: 1;">
					<u-button :ripple="true" :hair-line="false" :custom-style="btn3">售馨</u-button>
				</view>
			</view>
			<view class="btn-box" v-if="g.status==2">
				<view style="flex: 1;">
					<u-button :ripple="true" :hair-line="false" :custom-style="btn3">已下架</u-button>
				</view>
			</view>
		</view>
	</u-popup>
</template>

<script>
	export default {
		model: {},
		props: {
			borderRadius: {
				type: [String, Number],
				default: 0
			},
			value: {
				type: Boolean,
				default: false
			},
			maskCloseAble: {
				type: Boolean,
				default: true
			},
			safeAreaInsetBottom: {
				type: Boolean,
				default: true
			},
			good: {
				type: Object,
				default: {}
			},
			optionType: {
				type: [String, Number],
				default: 0
			},
			skued: {
				type: Object,
				default: {}
			}
		},

		data() {
			return {
				goodimage: '',
				goodprice: '',
				goodamount: '',
				mc: '',
				fu: '',
				secondary: '',
				gc: 1,
				bian: false,
				btn1: {
					flex: 1,
					height: '100%',
					borderRadius: '40px',
					border: 'none',
					color: '#FFF',
					fontSize: '13px',
					width: '100%'
				},
				btn2: {
					flex: 1,
					height: '100%',
					borderRadius: '40px',
					border: 'none',
					color: '#FFF',
					fontSize: '13px',
					width: '100%'
				},
				btn3: {
					flex: 1,
					height: '100%',
					borderRadius: '40px',
					border: 'none',
					color: '#FFF',
					fontSize: '13px',
					width: '100%',
					background: '#ababab'
				},
				btn4: {
					flex: 1,
					height: '100%',
					borderRadius: '40px',
					border: 'none',
					color: '#FFF',
					fontSize: '13px',
					width: '100%'
				},
				sku: '',
				g: {},
				skuObj: null,
				notStockGood: [],
				forms: {
					list: [{
						mch_id: 0,
						goods_list: [],
						distance: 0,
						remark: '',
						order_form: [],
						use_integral: 0,
						user_coupon_id: 0
					}],
					address_id: 0
				}
			};
		},
		mounted() {
			this.request2({
					url: '/api/AppletGoods/GetAppletGoodsInfo',
					data: {
						GoodsId: this.good.id
					}
				},
				res => {
					this.g = res.data.goods;
					this.g.totalStock = 0;
					this.g.attr.forEach(x => {
						this.g.totalStock += x.stock
					})
					this.goodimage = this.g.cover_pic;

					this.mc = this.$uiConfig.mainColor;
					this.fu = this.$uiConfig.secondary;
					this.secondary = this.$uiConfig.secondary;
					this.skuObj = this.skued.id ? this.skued : null;
					if (this.skuObj) {
						this.goodimage = this.skuObj.pic_url || this.g.cover_pic;
						this.goodprice = (parseFloat(this.skuObj.price) * 1).toFixed(2);
						this.goodamount = this.skuObj.stock;
					} else {
						this.goodimage = this.g.cover_pic;
						this.goodprice = this.g.price_min && this.g.price_min != '' ? this.g.price_min : this.g.price_content;
						this.goodamount = this.g.goods_stock;
					}
					this.bian = this.$utils.is_biang;
					this.btn1.background = this.secondary;
					this.btn2.background = this.mc;
					this.btn4.background = this.mc;
					if (this.optionType == 2) {
						this.btn1.borderRadius = '40px 0 0 40px';
						this.btn2.borderRadius = '0 40px 40px 0';
					}
					if (this.g.attr_groups && this.g.attr_groups.length > 0) {
						this.g.attr_groups.forEach(x => {
							if (!this.skuObj) {
								//(x.checkId = 0), (x.checkName = x.attr_group_name);
								(x.checkId = 0), (x.checkName = x.attr_list[0].attr_name);
								x.checkId = x.attr_list[0].attr_id;
							} else {
								let sign = `:${this.skuObj.sign_id}:`;
								x.attr_list.forEach(y => {
									if (sign.indexOf(`:${y.attr_id}:`) != -1) {
										x.checkId = y.attr_id;
										x.checkName = y.attr_name;
									}
								});
							}
						});
					}
					this.getfu()
					this.formatDisableSku();
					this.formatChosenTips();
				}
			);
			// this.g = this.good;
		},
		methods: {
			getfu() {

				let fucolor = this.colorRgb(this.fu);
				var RgbValue = fucolor.replace("rgb(", "").replace(")", "");
				var RgbValueArry = RgbValue.split(",");
				var grayLevel = RgbValueArry[0] * 0.299 + RgbValueArry[1] * 0.587 + RgbValueArry[2] * 0.114;
				console.log(grayLevel)
				if (grayLevel >= 192) {
					this.btn1.color = this.mc;
				} else {
					this.btn1.color = '#FFF';
				}

			},
			colorRgb(color) {
				var sColor = color.toLowerCase();
				//十六进制颜色值的正则表达式
				var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
				// 如果是16进制颜色
				if (sColor && reg.test(sColor)) {
					if (sColor.length === 4) {
						var sColorNew = "#";
						for (var i = 1; i < 4; i += 1) {
							sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
						}
						sColor = sColorNew;
					}
					//处理六位的颜色值
					var sColorChange = [];
					for (var i = 1; i < 7; i += 2) {
						sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
					}
					return sColorChange.join(",");
				}
				return sColor;
			},
			joinCar() {
				if (this.skuObj && this.skuObj.id) {
					this.request2({
							url: '/api/AppletOrder/SetGoodsShoppingCartInfo',
							data: {
								GoodsId: this.skuObj.goods_id,
								SpecificationSort: this.skuObj.sign_id,
								Number: this.gc == 0 ? 1 : this.gc
							}
						},
						res => {
							uni.showToast({
								title: '加入购物车成功',
								icon: 'success',
								duration: 2000
							});
							this.popupClose();
						}
					);
				} else {
					uni.showToast({
						title: '请选择商品',
						position: 'bottom',
						icon: 'none',
						duration: 2000
					});
				}
			},
			buy() {
				let ShoppingCartIdList = [];
				if (this.skuObj && this.skuObj.id) {
					let good = {
						DetailList: [],
						Use_Integral: 0,
						User_Coupon_Id: 0,
						DeliveryMethod: 0,
						AddressId: 0
					};
					let g = {
						GoodsId: this.skuObj.goods_id,
						Number: this.gc,
						SpecificationSort: this.skuObj.sign_id
					};
					good.DetailList.push(g);
					uni.navigateTo({
						url: '/pages/order-submit/order-submit?formData=' +
							encodeURIComponent(JSON.stringify(good)) +
							'&IsFormShoppingCart=2&ShoppingCartIdList=' +
							JSON.stringify(ShoppingCartIdList),
						complete(res) {
							console.log(res);
						}
					});
				} else {
					uni.showToast({
						title: '请选择商品',
						position: 'bottom',
						icon: 'none',
						duration: 2000
					});
				}
			},
			signup(){//教育报名
				let ShoppingCartIdList = [];
				if (this.skuObj && this.skuObj.id) {
					let good = {
						DetailList: [],
						Use_Integral: 0,
						User_Coupon_Id: 0,
						DeliveryMethod: 0,
						AddressId: 0
					};
					let g = {
						GoodsId: this.skuObj.goods_id,
						Number: this.gc,
						SpecificationSort: this.skuObj.sign_id
					};
					good.DetailList.push(g);
					uni.navigateTo({
						url: '/pages/order-submit/neweducation-submit?formData=' +
							encodeURIComponent(JSON.stringify(good)) +
							'&IsFormShoppingCart=2&ShoppingCartIdList=' +
							JSON.stringify(ShoppingCartIdList),
						complete(res) {
							console.log(res);
						}
					});
				} else {
					uni.showToast({
						title: '请选择商品',
						position: 'bottom',
						icon: 'none',
						duration: 2000
					});
				}
			},
			//关闭弹窗
			cloGood() {
				this.popupClose();
			},
			clickSkuItemHandler(index, groupRow) {
				let temp = this.g.attr_groups[groupRow].attr_list[index];
				if (this.notStockGood.indexOf(temp.attr_id) == -1) {
					if (this.g.attr_groups[groupRow].checkId != temp.attr_id) {
						this.g.attr_groups[groupRow].checkId = temp.attr_id;
						this.g.attr_groups[groupRow].checkName = temp.attr_name;
					} else {
						this.g.attr_groups[groupRow].checkId = 0;
						this.g.attr_groups[groupRow].checkName = this.g.attr_groups[groupRow].attr_group_name;
					}
					this.formatDisableSku();
					this.$forceUpdate();
					this.formatChosenTips();
				}
			},
			formatChosenTips() {
				let unchosen = '';
				let chosen = '';
				if (this.g.attr_groups && this.g.attr_groups.length > 0) {
					this.g.attr_groups.forEach(x => {
						// if (x.checkId != 0) {
						if (x.checkId != -1) {
							chosen += (chosen == '' ? '' : ',') + x.checkName;
						} else {
							unchosen += (unchosen == '' ? '' : ',') + x.attr_group_name;
						}
					});
				}

				if (unchosen != '') {
					this.sku = unchosen;
					this.skuObj = null;
					this.goodimage = this.g.cover_pic;
					this.goodprice = this.g.price_min && this.g.price_min != '' ? this.g.price_min : this.g.price_content;
					this.goodamount = this.g.goods_stock;
				} else {
					this.sku = chosen;
					this.formatSku();
				}
			},
			formatDisableSku() {
				let sign = [];
				if (this.g.attr_groups && this.g.attr_groups.length > 0) {
					this.g.attr_groups.forEach(x => {
						if (x.checkId != 0) {
							sign.push(`${x.checkId}`);
						}
					});

					if (sign.length == this.g.attr_groups.length - 1) {
						this.formatDisable(sign);
					} else if (sign.length == this.g.attr_groups.length) {
						let t = sign.join(':');
						let len = -1;
						this.g.attr.forEach(x => {
							if (x.sign_id == t && x.stock == 0) {
								len = this.g.attr_groups.length - 1;
							}
						});
						if (len != -1) {
							this.g.attr_groups[len].checkId = 0;
							this.g.attr_groups[len].checkName = this.g.attr_groups[len].attr_name;
							this.formatDisableSku();
						} else {
							this.formatDisable(sign.splice(sign.length - 1, 1));
						}
					}
				}
			},
			formatDisable(sign) {
				this.notStockGood = [];
				this.g.attr.forEach(x => {
					if (x.stock == 0) {
						let t = x.sign_id.split(':');
						let t1 = [];
						t.forEach(x => {
							if (sign.indexOf(x) == -1) {
								t1.push(x);
							}
						});
						if (t1.length == 1) {
							this.notStockGood.push(parseInt(t1[0]));
						}
					}
				});
				this.$forceUpdate();
			},
			formatSku() {
				let sign = '';
				if (this.g.attr_groups && this.g.attr_groups.length > 0) {
					this.g.attr_groups.forEach(x => {
						if (x.checkId != -1) {
							sign += (sign == '' ? '' : ':') + x.checkId;
						}
					});
				}
				if (this.g.attr && this.g.attr.length) {
					this.g.attr.forEach(x => {
						if (x.sign_id == sign) {
							this.skuObj = x;
						}
					});
				}

				if (this.skuObj != null) {
					this.goodimage = this.skuObj.pic_url || this.g.cover_pic;
					this.goodprice = (parseFloat(this.skuObj.price) * parseFloat(this.gc)).toFixed(2);
					this.goodamount = this.skuObj.stock;
				}
			},
			// 弹窗关闭
			popupClose() {
				this.$emit('close', this.skuObj);
				this.$emit('input', false);
			},
			valChange(e) {
				this.gc = e.value;
				if (this.skuObj) {
					this.goodprice = (parseFloat(this.skuObj.price) * parseFloat(this.gc)).toFixed(2);
				}
			},
			previewImage(index, images) {
				images = [images]
				uni.previewImage({
					urls: images,
					current: index,
				});
			},
		}
	};
</script>

<style>
	.goodsku {
		position: relative;
		padding: 10px;
		padding-bottom: 0;
	}

	.goodsku .goods {
		display: flex;
		background: transparent;
		padding-bottom: 10px;
	}

	.goodsku .goods .img {
		width: 116px;
		height: 116px;
		border-radius: 4px;
		margin-top: -45px;
		border: 2px solid #fff;
	}

	.goodsku .goods .chosen-info {
		margin-left: 15px;
		flex: 1;
		width: 1px;
		position: relative;
	}

	.goodsku .chosen-info .sku_close {
		position: absolute;
		right: 4px;
		top: 5px;
	}

	.goodsku .goods .chosen-info .price {
		font-size: 24px;
		font-family: 'oswald';
		font-weight: unset;
	}

	.goodsku .goods .chosen-info .price .small {
		font-size: 16px;
		margin-right: 5px;
	}

	.goodsku .goods .chosen-info .amount {
		font-size: 13px;
		color: gray;
	}

	.goodsku .goods .chosen-info .sku {
		font-size: 13px;
		margin-top: 5px;
	}

	.goodsku .sku-box {
		padding: 0;
		max-height: 300px;
		overflow: hidden;
		overflow-y: auto;
		display: block;
	}

	.goodsku .sku-box .sku-item {
		padding: 15px 0;
		border-bottom: 1px solid #eee;
		width: 100%;
	}

	.goodsku .sku-box .sku-item .sku-title {
		color: #333;
		font-size: 14px;
	}

	.goodsku .sku-box .sku-item .sku-chi {
		background: #eee;
		border-radius: 3px;
		padding: 3px;
		display: flex;
		color: #111;
		display: inline-block;
		margin-top: 10px;
		margin-right: 10px;
		font-size: 13px;
	}

	.goodsku .sku-box .sku-item .sku-chi.disable {
		background: #eee !important;
		color: #ddd !important;
	}

	.goodsku .sku-box .sku-item .sku-chi .val {
		width: 1px;
		height: 24px;
		line-height: 24px;
		padding: 0 7px;
	}

	.goodsku .sku-box .sku-item .sku-chi .img {
		width: 24px;
		height: 24px;
		border-radius: 2px;
		margin-right: 5px;
		vertical-align: bottom;
	}

	.goodsku .count-box {
		display: flex;
		padding: 15px 0;
	}

	.goodsku .count-box .label {
		font-size: 14px;
		color: #333;
		width: 1px;
		flex: 1;
	}

	.goodsku .btn-box {
		display: flex;
		background: #fff;
		height: 60px;
		align-items: center;
		border-top: 1px solid #eee;
		padding: 5px 10px;
	}
</style>
