<!-- Shopping.vue -->
<template>
	<view class="div container">
		<uni-popup
				background-color="#fff"
				ref="isShowcartInfo"
				type="bottom"
				v-if="detailInfo"
		>
			<view class="div ui-add-shopping" :style="'height:'+(screenHeight*.7)+'px'" v-if="detailInfo">
				<view class="div shopping-info">
					<view class="div info-header">
						<image mode="aspectFit"
								v-bind:src="detailInfo.photos[0]"
								class="img info-image"
								v-if="detailInfo.photos && detailInfo.photos.length > 0"
						/>
						<view class="div">
							<text class="span header-price" >￥{{ propertiPrice }}</text>
							<text class="span">
							<text class="span iconfont" v-if="detailInfo.activity">&#xe631;</text>
							<text class="span" v-if="detailInfo.activity">{{
								detailInfo.activity.name
							}}</text>
						</text>
							<!-- {{ chooseinfo}} -->
							<text class="span">库存{{ currentStock }}件</text>
							<text class="span">数量：{{ numbers }}</text>
						</view>

						<text class="span iconfont close" v-on:click="closeCartInfo(false)">&#xe65a;</text>
					</view>

					<view class="div goods-detail-properties">
						<view class="div"
								v-if="
							detailInfo &&
								detailInfo.goods_spec
						"
								v-for="(item, index) in detailInfo.spec_name"
								:key="index"
						>
							<view
									class="div goods-properties"
									v-if="detailInfo.spec_value && detailInfo.spec_value[index] && Object.keys(detailInfo.spec_value[index]).length"
							>
								<view class="p">{{ item }}</view>
								<view class="div properties-list">
									<view class="div" v-for="(key, keyindex) in detailInfo.spec_value[index]" :key="keyindex">
								<text class="span"
										@click="setCurrentIndex(keyindex,detailInfo.spec_value[index])"
										v-bind:class="{
										'active-properties': detailInfo.goods_spec[keyindex],
										'disabled-properties':(detailInfo.spec_disable.indexOf(keyindex)>-1)
									}"
								>{{ key }}</text
								>

									</view>
								</view>
							</view>
						</view>
						<view class="div info-body">
							<view class="p">数量</view>
							<view class="div ui-number">
								<view
										class="div reduce ui-common"
										@click.stop="reduceNumber()"
										v-bind:class="{ 'reduce-opacity': numbers <= 1 }"
								>
									-
								</view>
								<input
										type="number"
										min="1"
										class="number"
										value="1"
										v-model="numbers"
								/>
								<view class="div add ui-common" @click.stop="addNumber()">+</view>
							</view>
						</view>
					</view>
					<view class="div info-footer">
						<view
								class="div footer-button"
								:class="canBuy?'active-cart':'disabled-cart'"
								v-on:click="checkProduct(false)"
								v-if="!detailInfo.bargain_info && ((!detailInfo.pintuan_type && detailInfo.cart) || (detailInfo.pintuan_type && (detailInfo.pintuangroup_list.length || detailInfo.pintuanorder_state)))"
						>
							{{addCartText}}
						</view>
						<view
								class="div footer-button"
								:class="canBuy?'active-buy':'disabled-buy'"
								v-on:click="checkProduct(true)"
						>
							{{buyNowText}}
						</view>

					</view>
				</view>
			</view>
		</uni-popup>
		<uni-popup background-color="#fff" v-if="detailInfo.pintuan_type && detailInfo.pintuangroup_list.length" ref="subjectVisible" type="right" >
			<view :style="'width:'+screenWidth+'px'" class="common-popup-wrapper">
			<view class="div common-header-wrap">
				<view :style="'height:'+navHeight+'px'"></view>
				<view class="common-header-holder"></view>
				<view class="common-header-fixed">
				<title-header />
				<uni-nav-bar title="拼团列表" class="common-header" left-icon="back" @clickLeft="hidePopup('subjectVisible')">
				</uni-nav-bar>
			</view>
			</view>
			<view class="div common-popup-content">
				<scroll-view style="position: absolute;top:0;right:0;left:0;bottom:0" scroll-y="true">
				<view class="div" v-for="(item, index) in detailInfo.pintuangroup_list" :key="index" @click="goPintuan(item)">
          <flex-line :is-link="true" :show-border="true" v-if="!(detailInfo.pintuangroup_share_id>0 && item.pintuangroup_headid != detailInfo.pintuangroup_share_id)"><!--通过拼团分享会员ID判断其他组团是否显示-->
          <view class="div">
            <image mode="aspectFit" class="img" :src="item.pintuangroup_avatar" width="24" height="24">
            <text class="span">{{item.member_name}}</text>
          </view>
          <view class="div" slot="right">
            <text class="span">{{item.pintuangroup_surplus>0?('还差'+item.pintuangroup_surplus+'人'):'已满员'}}&nbsp;</text>
						<count-down :timetype="2" :timesurplus="item.pintuangroup_starttime" :timelimithour="item.pintuangroup_limit_hour"></count-down>
          </view>
          </flex-line>

				</view>
				</scroll-view>
			</view>
		</view>
		</uni-popup>
	</view>
</template>

<script>
import TitleHeader from '../../../TitleHeader'
import { urlencode } from '@/util/common'
import CountDown from '../../../CountDown'
import { mapState, mapMutations, mapActions } from 'vuex'
import { cartAdd } from '../../../../api/homecart'
import { addBargain } from '../../../../api/memberBargain'
import flexLine from '../../../flexLine'
export default {
  components:{
    TitleHeader,
    flexLine,
    CountDown
  },
  data(){
    return {
      navHeight: 0,
      screenWidth:0,
      screenHeight:0,
      pintuangroup_id: 0,
      addCartText: '加入购物车',
      buyNowText: '立即购买',
      numbers: this.$store.state.goodsdetail.number > 0 ? this.$store.state.goodsdetail.number : 1, // todo 临时解决
      currentStock: this.$store.state.goodsdetail.detailInfo.goods_storage,
      productId: this.$store.state.goodsdetail.currentProductId,
      toastConfig: {
        message: '商品达到每单限购数量',
        position: 'middle'
      },
      ids: [],
      info: [],
      propertiPrice: 0,
      earlier: {}
    }
  },
  created () {
	  if (this.detailInfo.promotion_type) {
		  this.propertiPrice = this.detailInfo.promotion_price
	  } else {
		  this.propertiPrice = this.detailInfo.goods_price
	  }
    if (this.detailInfo.bargain_info) {
      if (this.detailInfo.bargainorder_info) {
        if (this.detailInfo.bargainorder_info.bargainorder_state == 2) {
          this.buyNowText = '砍价成功去下单'
        } else {
          this.buyNowText = '正在砍价'
        }
      } else {
        this.buyNowText = '发起砍价'
      }
      this.propertiPrice = this.detailInfo.bargain_info.bargain_floorprice
    } else if (this.detailInfo.pintuan_type) {
      if (this.detailInfo.pintuanorder_state) {
        if (this.detailInfo.pintuanorder_state == 1) {
          this.addCartText = '参团中'
        } else {
          this.addCartText = '已成团'
        }
        this.buyNowText = '原价购买'
      } else {
        this.addCartText = '参加拼团'
        this.buyNowText = '立刻开团'
      }
      this.propertiPrice = this.detailInfo.pintuan_price
    } else if (this.detailInfo.is_goodsfcode == 1) {
      this.buyNowText = 'F码购买'
    } else if (this.detailInfo.presell_type) {
      this.buyNowText = '预售购买'
    }
    this.info = this.chooseinfo.specification
    this.ids = Object.assign([], this.chooseinfo.ids)
  },

  computed: {
    ...mapState({
      // 是否显示购物车浮层
      isShowcartInfo: state => state.goodsdetail.isShowcartInfo,
      isOnline: state => state.member.isOnline,
      token: state => state.member.token,
      user: state => state.member.info,
      detailInfo: state => state.goodsdetail.detailInfo,
      storeInfo: state => state.goodsdetail.storeInfo,
      specList: state => state.goodsdetail.specList,
      number: state => state.goodsdetail.number,
      chooseinfo: state => state.goodsdetail.chooseinfo
    }),
    canBuy () {
      if (this.detailInfo.goods_storage > 0 && this.detailInfo.goods_state == 1 && this.detailInfo.goods_verify == 1) {
        return true
      } else {
        return false
      }
    }
  },

  watch: {
    isShowcartInfo: function (value) {
      if(value){
        this.showPopup('isShowcartInfo')
      }else{
        this.hidePopup('isShowcartInfo')
      }
    },
    numbers: function (value) {
      if (value) {
        let goodStorage = this.detailInfo.goods_storage
        if (value <= 0) {
          this.numbers = 1
          this.toastConfig.message = '受不了了，宝贝不能再少了'
          uni.showToast({icon:'none',title: this.toastConfig})
        } else if (value > goodStorage) {
          this.toastConfig.message = '商品库存不足'
          uni.showToast({icon:'none',title: this.toastConfig})
          this.numbers = goodStorage
        }
        // 批发
        if (this.detailInfo.wholesale_info) {
          this.propertiPrice = this.detailInfo.goods_price
          for (var i in this.detailInfo.wholesale_info.wholesalegoods_price) {
            if (this.detailInfo.wholesale_info.wholesalegoods_price[i].num <= this.numbers) {
              this.propertiPrice = this.detailInfo.wholesale_info.wholesalegoods_price[i].price
            }
          }
        }
        this.saveNumber(this.numbers)
      }
    }
  },

  mounted(){
    // #ifdef  MP-WEIXIN
    this.navHeight = uni.getMenuButtonBoundingClientRect().top
    // #endif
    const res = uni.getSystemInfoSync()
    this.screenWidth = res.windowWidth
    this.screenHeight = res.windowHeight
  },

  methods:{
    showPopup(id){
      this.$refs[id].open()
    },
    hidePopup(id){
      this.$refs[id].close()
    },
    ...mapActions({
      getGoodsDetail: 'getGoodsDetail'
    }),
    ...mapMutations({
      saveCartState: 'saveCartState',
      saveNumber: 'saveNumber',
      saveChooseInfo: 'saveChooseInfo',
      saveProperties: 'saveProperties',
      setCartNumber: 'setCartNumber',
      saveSelectedCartGoods: 'saveSelectedCartGoods'
    }),
    goPintuan (item) {
    	if (this.detailInfo.pintuanorder_state) {
    		if (this.detailInfo.pintuanorder_state == 1) {
          uni.showToast({icon:'none',title: '您正在参团中'})
        } else {
          uni.showToast({icon:'none',title: '您已拼团成功'})
        }
    		return
      }
      if (item.pintuangroup_surplus > 0) {
        this.pintuangroup_id = item.pintuangroup_id
        this.checkProduct(true)
      } else {
		  uni.showToast({icon:'none',title: '该团已满员'})
	  }
    },
    // 关闭购物车浮层
    closeCartInfo (value) {
      this.saveCartState(value)
    },

    // 数量加
    addNumber () {
      if (this.detailInfo.goods_storage && this.numbers > this.detailInfo.goods_storage) {
        this.toastConfig.message = '商品库存不足'
        uni.showToast({icon:'none',title: this.toastConfig})
        this.numbers = this.detailInfo.goods_storage
      } else {
        this.numbers++
      }
    },

    // 数量减
    reduceNumber () {
      if (this.numbers > 1) {
        this.numbers--
      } else {
        this.numbers = 1
        this.toastConfig.message = '受不了了，宝贝不能再少了'
        uni.showToast({icon:'none',title: this.toastConfig})
      }
    },

    // 加入购物车
    checkProduct (checkout) {
      if (!this.canBuy) {
        return
      }
      if (!this.isOnline) {
        uni.navigateTo({ url: '/pages/home/memberlogin/Login' })
      } else {
        if (checkout) { // 立即购买
          if (this.user.store_id == this.storeInfo.store_id) {
            uni.showToast({icon:'none',title: '不能购买自己的商品'})
            return
          }
          if (this.detailInfo.is_virtual == '1') {
            let params = { goods_id: this.detailInfo.goods_id, quantity: this.numbers }
            if (this.detailInfo.pintuan_type && !this.detailInfo.pintuanorder_state) {
              params['pintuan_id'] = this.detailInfo.pintuan_id
              params['pintuangroup_id'] = this.pintuangroup_id
            }
            uni.navigateTo({ url: '/pages/member/vrbuy/step1'+'?'+urlencode( params )})
          } else {
            let params = { buy_now: 1, cart_id: this.detailInfo.goods_id + '|' + this.numbers }
            if (this.detailInfo.bargain_info) {
              if (this.detailInfo.bargainorder_info) {
                if (this.detailInfo.bargainorder_info.bargainorder_state == 2) {
                  params['bargainorder_id'] = this.detailInfo.bargainorder_info.bargainorder_id
                } else {
                  uni.navigateTo({ url: '/pages/home/bargain/Bargainshare'+'?'+urlencode( { bargainorder_id: this.detailInfo.bargainorder_info.bargainorder_id } )})
                  return
                }
              } else {
                // 新增砍价
                addBargain(this.detailInfo.bargain_info.bargain_id).then(res => {
                  uni.navigateTo({ url: '/pages/home/bargain/Bargainshare'+'?'+urlencode( { bargainorder_id: res.result.bargainorder_id  })})
                  }).catch(function (error) {
                  uni.showToast({icon:'none',title: error.message})
                })
                return
              }
            } else if (this.detailInfo.pintuan_type && !this.detailInfo.pintuanorder_state) {
              params['pintuan_id'] = this.detailInfo.pintuan_id
              params['pintuangroup_id'] = this.pintuangroup_id
            }
            uni.navigateTo({ url: '/pages/member/buy/step1'+'?'+urlencode( params )})
          }
        } else {
          if (this.detailInfo.pintuan_type) {
            this.showPopup('subjectVisible')
          } else {
            cartAdd(this.detailInfo.goods_id, this.numbers).then(
              res => {
                uni.$emit('update-cart-num')
                uni.$emit('end-addcart-animation')
                uni.showToast({icon:'none',title: res.message})
              },
              error => {
                uni.showToast({icon:'none',title: error.message})
              }
            )
          }
        }
      }
    },

    keyDown (event) {},

    /*
                 * setCurrentIndex: 设置当前选中的规格的id,
                 * @parmas: index 当前规格的index
                 * @parmas: specList 同类规格的列表
                 */
    setCurrentIndex (index, specList) {
    	if(this.detailInfo.spec_disable.indexOf(index)>-1){
    		return
		}
      let specIndex = []
      for (var k in specList) {
        if (typeof (this.detailInfo.goods_spec[k]) !== 'undefined') {
          delete this.detailInfo.goods_spec[k]
          this.detailInfo.goods_spec[index] = specList[index]
          break
        }
      }
      for (var k in this.detailInfo.goods_spec) {
        specIndex.push(k)
      }
      specIndex = specIndex.sort(this.sortNumber).join('|')
      this.getGoodsDetail({ goods_id: this.specList[specIndex], token: this.token, extra: {} }).then(res => {
        if (res.result.goods_info.promotion_type) {
          this.propertiPrice = res.result.goods_info.promotion_price
        } else {
          this.propertiPrice = res.result.goods_info.goods_price
        }
        this.currentStock = res.result.goods_info.goods_storage
      }).catch(error => {
        uni.showToast({icon:'none',title: error.message})
      })
    },
    sortNumber (a, b) {
      return a - b
    }
  }
}
</script>

<style lang="scss" scoped>
	.mint-popup-bottom {
		overflow: initial;
		height: 70%;
	}
	.ui-add-shopping {
		/* position: fixed;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        width: 100%;
        height: 100%; */
		/* z-index: 200; */
		/* background:rgba(0,0,0, 0.4); */
		.shopping-info {
			background: rgba(255, 255, 255, 1);
			height: 100%;
			position: relative;
			width: -webkit-fill-available;
			/* bottom: 0; */
			z-index: 10;
			width: 100%;
			.info-header {
				padding:0.75rem;
				display: flex;
				justify-content: flex-start;
				padding-bottom:1.25rem;
				border-bottom: 0.5px solid rgba(232, 234, 237, 1);
				.img.info-image {
					width:6rem;
					height:6rem;
					border-radius: 1px;
					margin-top: -0.75rem;
					position: absolute;
					top: -0.65rem;
				}
				.div {
					padding-left:6.5rem;
					width: 100%;
					.span {
						display: block;
						color: #999999;
						&.header-price {
							font-size:$h1;
							line-height:1rem;
							padding-bottom:0.6rem;
							color: $primaryColor;
						}
						&:nth-child(2) {
							.img {
								vertical-align: middle;
								padding-right:0.5rem;
								width:2.5rem;
								height:1rem;
							}
							.span {
								display: inline;
								font-size:$subFontSize;
								line-height:0.7rem;
								padding-bottom:0.45rem;
								padding-top:0.6rem;
							}
						}
						&:nth-child(3) {
							line-height:1rem;
							font-size:$subFontSize;
							width: 100%;
							overflow: hidden;
							text-overflow: ellipsis;
							white-space: nowrap;
							padding-right:0.75rem;
						}
						&:last-child {
							line-height:1rem;
							font-size:$subFontSize;
							padding-top:0.6rem;
							width: 100%;
							overflow: hidden;
							text-overflow: ellipsis;
							white-space: nowrap;
							padding-right:0.75rem;
						}
					}
				}
				.close {
					position: absolute;
					top:0.75rem;
					right:0.75rem;
					width:0.65rem;
					height:0.65rem;
					cursor: pointer;
					opacity: 1;
				}
			}
			.div.goods-detail-properties {
				width: 100%;
				overflow: auto;
				height: auto;
				position: absolute;
				top:6.2rem;
				bottom:2.2rem;
				/* height: 100%; */
			}
			.div.goods-properties {
				padding: 0.75rem 0;
				.p {
					font-size:$subFontSize;
					color: rgba(41, 43, 45, 1);
					line-height:0.8rem;
					margin: 0;
					padding: 0 0.75rem;
				}
				.div.properties-list {
					.div {
						display: inline-block;
						margin-left: 0.75rem;
						.span {
							font-size:$subFontSize;
							color: rgba(78, 84, 93, 1);
							line-height: 0.7rem;
							display: inline-block;
							padding: 0.35rem 0.7rem;
							border: 1px solid #404245;
							border-radius:0.1rem;
							cursor: pointer;
							margin-top:0.75rem;
							&.active-properties {
								background: $primaryColor;
								color: rgba(255, 255, 255, 1);
								border: 1px solid $primaryColor;
							}
							&.disabled-properties {
								color: #b1b5bb;
								cursor: none;
								border: 1px solid #a2a6ad;
							}
						}
						/* &:nth-child(even) {
                        margin-left: 0.75rem;
                        } */
					}
				}
			}
			.info-body {
				padding:0.75rem 0.75rem 1rem 0.75rem;
				.p {
					font-size:$subFontSize;
					color: rgba(41, 43, 45, 1);
					line-height:0.8rem;
					padding: 0;
					margin: 0;
					padding-bottom:0.8rem;
				}
				.div.ui-number {
					height: 1.5rem;
					display: flex;
					border-radius: 0.15rem 0 0 0.15rem;
					input,
					.div {
						height:1.4rem;
						line-height:1.4rem;
						text-align: center;
						color: #404245;
						display: inline-block;
						padding: 0;
						margin: 0;
						border: 0;
						outline-offset: 0;
					}
					.ui-common {
						line-height:1.4rem;
						width:1.4rem ;
						height:1.4rem;
						border: 1px solid #c7c7cd;
						cursor: pointer;
					}
					.reduce {
						border-right: 0;
					}
					.reduce-opacity {
						opacity: 0.4;
					}
					.add {
						border-left: 0;
					}
					.number {
						width:2rem;
						border: 1px solid #c7c7cd;
						border-radius: 0;
						border-image-width: 0;
						box-shadow: 0;
						vertical-align: bottom;
						&:focus {
							outline: none;
						}
					}
				}
			}
			.info-footer {
				width: 100%;
				position: fixed;
				bottom: 0;
				display: flex;
				.footer-button {
					flex: 1;
					color: #ffffff;
					line-height:2.2rem;
					text-align: center;
					font-size:$subFontSize;
					height:2.2rem;
				}
				.active-cart {
					background: $primaryColor;
				}
				.active-buy {
					background: #000;
				}
				.disabled-buy {
					background: #999999;
				}
				.disabled-cart {
					background: #c3c3c3;
				}
			}
		}

	}

</style>
